Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

Ray tracing and shaders: a ShaderExtension that doesn't compile refuses the render, and <Pathtracer /> no longer panics on its first frame

shinyobjectz19b72d3dee4e
diff --git a/Cargo.lock b/Cargo.lock
index a1a377ad..f9bb1166 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -15522,6 +15522,7 @@ name = "raea-sys-shader"
version = "0.1.0"
dependencies = [
"bevy",
+ "raea-gpu-device",
"raea-sys-material",
"raea-sys-sampler",
"raea-sys-shader-wgsl",
diff --git a/engine/render/raytrace/src/solari.rs b/engine/render/raytrace/src/solari.rs
index e61d0cc8..93e900de 100644
--- a/engine/render/raytrace/src/solari.rs
+++ b/engine/render/raytrace/src/solari.rs
@@ -10,6 +10,7 @@
use super::*;
use bevy::camera::CameraMainTextureUsages;
+use bevy::core_pipeline::prepass::{DeferredPrepass, DepthPrepass};
use bevy::mesh::{Indices, PrimitiveTopology, VertexAttributeValues};
use bevy::solari::pathtracer::{Pathtracer, PathtracingPlugin};
use bevy::solari::prelude::{RaytracingMesh3d, SolariLighting, SolariPlugins};
@@ -23,11 +24,16 @@ pub fn add(app: &mut App) {
struct Done;
// Solari's camera needs: no MSAA and a main texture it can write to (SolariLighting's docs); Hdr, the prepasses and
-// deferred come with its required components
-fn cameras(mut cmd: Commands, q: Query<(Entity, Option<&CameraMainTextureUsages>), (Or<(With<SolariLighting>, With<Pathtracer>)>, Without<Done>)>) {
- for (e, u) in &q {
+// deferred come with SolariLighting's required components. Pathtracer requires only Hdr, but SolariPlugins makes every
+// StandardMaterial deferred, so a Pathtracer camera without a deferred prepass panicked on its first frame (Bevy's
+// prepass queue unwraps the view's opaque deferred phase): it gets the depth and deferred prepasses too.
+fn cameras(mut cmd: Commands, q: Query<(Entity, Option<&CameraMainTextureUsages>, Has<Pathtracer>), (Or<(With<SolariLighting>, With<Pathtracer>)>, Without<Done>)>) {
+ for (e, u, path) in &q {
let usages = u.map_or_else(|| CameraMainTextureUsages::default().0, |u| u.0) | bevy::render::render_resource::TextureUsages::STORAGE_BINDING;
cmd.entity(e).insert((Msaa::Off, CameraMainTextureUsages(usages), Done));
+ if path {
+ cmd.entity(e).insert_if_new((DepthPrepass, DeferredPrepass));
+ }
}
}
diff --git a/systems/shader/Cargo.toml b/systems/shader/Cargo.toml
index d20cd6c9..777793bd 100644
--- a/systems/shader/Cargo.toml
+++ b/systems/shader/Cargo.toml
@@ -10,6 +10,8 @@ description = "Shaders written in TypeScript over the lit standard surface (docs
raea-sys-material = { path = "../material" }
raea-sys-sampler = { path = "../sampler" }
raea-sys-shader-wgsl = { path = "wgsl" }
+# a shader that does not compile refuses the render (failed.rs)
+raea-gpu-device = { path = "../../gpu/device" }
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render", "bevy_ui", "bevy_ui_render"] }
wgpu = "=30.0.1"
serde_json = "1"
diff --git a/systems/shader/src/failed.rs b/systems/shader/src/failed.rs
new file mode 100644
index 00000000..bba08731
--- /dev/null
+++ b/systems/shader/src/failed.rs
@@ -0,0 +1,78 @@
+//! A shader raea made for a scene (`register`: a ShaderExtension's surface and lit hooks, an own material's, a UI
+//! material's) that didn't compile. Bevy logs the compiler's error, leaves the pipeline out and draws on without it, so
+//! a render came out without the shader (black, for a ShaderExtension) and still said APPLIED. Each frame the render
+//! world looks for those pipelines and refuses the render with the compiler's error (raea-gpu-device `refuse`, which
+//! the render reads back with the frame).
+use bevy::prelude::*;
+use bevy::render::render_resource::{CachedPipelineState, PipelineCache, PipelineDescriptor};
+use bevy::render::{Render, RenderApp, RenderSystems};
+use bevy::shader::{Shader, ShaderCacheError};
+use std::collections::HashSet;
+use std::sync::Mutex;
+
+/// The uuids `register` gave the shaders it added.
+static OURS: Mutex<Option<HashSet<u128>>> = Mutex::new(None);
+
+/// A shader `register` added: its errors refuse the render.
+pub(crate) fn ours(id: u128) {
+ OURS.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashSet::new).insert(id);
+}
+
+pub(crate) fn install(app: &mut App) {
+ if let Some(r) = app.get_sub_app_mut(RenderApp) {
+ r.add_systems(Render, check.in_set(RenderSystems::Cleanup));
+ }
+}
+
+/// The shaders a pipeline runs.
+fn shaders(d: &PipelineDescriptor) -> Vec<AssetId<Shader>> {
+ match d {
+ PipelineDescriptor::RenderPipelineDescriptor(d) => std::iter::once(d.vertex.shader.id()).chain(d.fragment.as_ref().map(|f| f.shader.id())).collect(),
+ PipelineDescriptor::ComputePipelineDescriptor(d) => vec![d.shader.id()],
+ PipelineDescriptor::MeshPipelineDescriptor(d) => d.fragment.as_ref().map(|f| f.shader.id()).into_iter().collect(),
+ }
+}
+
+fn check(cache: Res<PipelineCache>, mut told: Local<HashSet<u128>>) {
+ let ours = OURS.lock().unwrap_or_else(|e| e.into_inner());
+ let Some(ours) = ours.as_ref() else { return };
+ for p in cache.pipelines() {
+ let CachedPipelineState::Err(ShaderCacheError::ProcessShaderError(why) | ShaderCacheError::CreateShaderModule(why)) = &p.state else { continue };
+ for id in shaders(&p.descriptor) {
+ let AssetId::Uuid { uuid } = id else { continue };
+ let u = uuid.as_u128();
+ if ours.contains(&u) && told.insert(u) {
+ raea_gpu_device::check::refuse(message(why));
+ }
+ }
+ }
+}
+
+/// The refusal: the compiler's error without its terminal colours. Its line numbers count in the module raea wraps the
+/// source in, so it quotes the line itself.
+fn message(why: &str) -> String {
+ let mut plain = String::with_capacity(why.len());
+ let mut chars = why.chars();
+ while let Some(c) = chars.next() {
+ if c == '\u{1b}' {
+ // an escape sequence: up to and including its final letter
+ for c in chars.by_ref() {
+ if c.is_ascii_alphabetic() {
+ break;
+ }
+ }
+ } else {
+ plain.push(c);
+ }
+ }
+ format!("a shader in the scene didn't compile, so it would have drawn without it:\n{}", plain.trim_end())
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn the_message_loses_its_colours() {
+ let m = super::message("\u{1b}[31merror\u{1b}[0m: use of a reserved word `patch`\n");
+ assert!(m.ends_with("error: use of a reserved word `patch`"), "{m}");
+ }
+}
diff --git a/systems/shader/src/lib.rs b/systems/shader/src/lib.rs
index e0c2b27e..38c87af7 100644
--- a/systems/shader/src/lib.rs
+++ b/systems/shader/src/lib.rs
@@ -37,6 +37,7 @@ pub mod own;
pub mod own_array;
mod own_images;
pub mod own_live;
+mod failed;
pub mod ui;
use raea_sys_shader_wgsl::ui_bind;
@@ -52,6 +53,7 @@ pub fn install(app: &mut App) {
app.add_plugins(MaterialPlugin::<ShadedMaterial>::default());
own::install(app);
ui::install(app);
+ failed::install(app);
}
#[derive(Asset, AsBindGroup, Reflect, Clone, Debug)]
@@ -284,6 +286,7 @@ pub fn register(world: &mut World, module: String, defs: &[ShaderDefVal], kind:
let hi = h.finish();
kind.hash(&mut h);
let id = ((hi as u128) << 64) | h.finish() as u128;
+ failed::ours(id);
let aid = AssetId::<Shader>::Uuid { uuid: bevy::asset::uuid::Uuid::from_u128(id) };
let mut shaders = world.resource_mut::<Assets<Shader>>();
if shaders.get(aid).is_none() {