learn-wgpu/code/beginner/tutorial7-instancing/build.rs

79 lines
2.2 KiB
Rust
Raw Normal View History

2020-09-05 22:45:52 +00:00
use anyhow::*;
2020-09-28 05:24:43 +00:00
use glob::glob;
2020-09-05 22:45:52 +00:00
use std::fs::{read_to_string, write};
2020-09-28 05:24:43 +00:00
use std::path::PathBuf;
2020-09-05 22:45:52 +00:00
struct ShaderData {
src: String,
src_path: PathBuf,
spv_path: PathBuf,
kind: shaderc::ShaderKind,
}
impl ShaderData {
pub fn load(src_path: PathBuf) -> Result<Self> {
2020-09-28 05:24:43 +00:00
let extension = src_path
.extension()
2020-09-05 22:45:52 +00:00
.context("File has no extension")?
.to_str()
.context("Extension cannot be converted to &str")?;
let kind = match extension {
"vert" => shaderc::ShaderKind::Vertex,
"frag" => shaderc::ShaderKind::Fragment,
"comp" => shaderc::ShaderKind::Compute,
_ => bail!("Unsupported shader: {}", src_path.display()),
};
let src = read_to_string(src_path.clone())?;
let spv_path = src_path.with_extension(format!("{}.spv", extension));
2020-09-28 05:24:43 +00:00
Ok(Self {
src,
src_path,
spv_path,
kind,
})
2020-09-05 22:45:52 +00:00
}
}
fn main() -> Result<()> {
// This tells cargo to rerun this script if something in /src/ changes.
println!("cargo:rerun-if-changed=src/*");
2020-09-28 05:24:43 +00:00
2020-09-05 22:45:52 +00:00
// Collect all shaders recursively within /src/
let mut shader_paths = [
glob("./src/**/*.vert")?,
glob("./src/**/*.frag")?,
glob("./src/**/*.comp")?,
];
2020-09-28 05:24:43 +00:00
2020-09-05 22:45:52 +00:00
// This could be parallelized
2020-09-28 05:24:43 +00:00
let shaders = shader_paths
.iter_mut()
2020-09-05 22:45:52 +00:00
.flatten()
2020-09-28 05:24:43 +00:00
.map(|glob_result| ShaderData::load(glob_result?))
2020-09-05 22:45:52 +00:00
.collect::<Vec<Result<_>>>()
.into_iter()
.collect::<Result<Vec<_>>>();
2020-09-28 05:24:43 +00:00
let mut compiler = shaderc::Compiler::new().context("Unable to create shader compiler")?;
2020-09-05 22:45:52 +00:00
// This can't be parallelized. The [shaderc::Compiler] is not
// thread safe. Also, it creates a lot of resources. You could
// spawn multiple processes to handle this, but it would probably
// be better just to only compile shaders that have been changed
// recently.
for shader in shaders? {
let compiled = compiler.compile_into_spirv(
2020-09-28 05:24:43 +00:00
&shader.src,
shader.kind,
&shader.src_path.to_str().unwrap(),
"main",
None,
2020-09-05 22:45:52 +00:00
)?;
write(shader.spv_path, compiled.as_binary_u8())?;
}
Ok(())
2020-09-28 05:24:43 +00:00
}