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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
The engine's own shaders open to a project: a file in engine-shaders/ replaces one from its first frame, with no build
shinyobjectz737468b8cd25
diff --git a/Cargo.lock b/Cargo.lockindex 1cb6caa6..d45dfea7 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -14965,6 +14965,7 @@ dependencies = ["objc2-metal-fx","raea-io-home","raea-io-trace",+ "raea-sys-frame","serde_json","wgpu",]diff --git a/engine/render/raytrace/Cargo.toml b/engine/render/raytrace/Cargo.tomlindex c7775d3a..af9ca175 100644--- a/engine/render/raytrace/Cargo.toml+++ b/engine/render/raytrace/Cargo.toml@@ -12,6 +12,8 @@ raea-io-home = { path = "../../../io/home" }# each view's effective SolariSettings, once, into the run's trace (settings.rs)raea-io-trace = { path = "../../../io/trace" }serde_json = "1"+# its own wgpu shaders read from a project's engine-shaders/ or the checkout (RAEA_ENGINE_SHADERS), as the embedded ones+raea-sys-frame = { path = "../../../systems/frame" }bevy = { version = "=0.20.0", default-features = false, features = ["std", "3d_bevy_render", "bevy_solari"] }# the same wgpu Bevy uses (the guide pass records on its device; MetalFX runs on its Metal objects)wgpu = "=30.0.1"diff --git a/engine/render/raytrace/src/lib.rs b/engine/render/raytrace/src/lib.rsindex eece6810..808bf618 100644--- a/engine/render/raytrace/src/lib.rs+++ b/engine/render/raytrace/src/lib.rs@@ -90,6 +90,9 @@ impl Default for SolariSettings {pub fn add(app: &mut App) {app.register_type::<RenderScale>().register_type::<SolariSettings>();app.add_plugins(bevy::render::extract_component::ExtractComponentPlugin::<SolariSettings>::default());+ // the denoiser's own shaders, read from a project's engine-shaders/ or the checkout as its pipelines are made+ #[cfg(target_os = "macos")]+ raea_sys_frame::engine_shaders::declare(&[("raea_render_raytrace/metalfx_guides.wgsl", metalfx::DECODE_WGSL), ("raea_render_raytrace/emit_taa.wgsl", emit_taa::WGSL)]);solari::add(app);force::add(app);}diff --git a/engine/render/raytrace/src/metalfx.rs b/engine/render/raytrace/src/metalfx.rsindex 4140a88a..8405a930 100644--- a/engine/render/raytrace/src/metalfx.rs+++ b/engine/render/raytrace/src/metalfx.rs@@ -66,7 +66,7 @@ pub(crate) fn add(app: &mut App) {}// the guides' shader: what it writes and why (the emission's split) is in its file-const DECODE_WGSL: &str = include_str!("metalfx_guides.wgsl");+pub(crate) const DECODE_WGSL: &str = include_str!("metalfx_guides.wgsl");/// A view's denoiser and its textures, made again when its input's or output's size changes, or its depth's kind.@@ -307,7 +307,10 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDelet (pipeline, restore, restore_taa, hist_sampler, pipeline_psr) = kit.pipeline.get_or_insert_with(|| {- let source = format!("{DECODE_WGSL}{}", super::emit_taa::WGSL);+ // read from a project's engine-shaders/ or the checkout when one has them (docs/nobuild.feature NB5b)+ let guides = raea_sys_frame::engine_shaders::text("raea_render_raytrace/metalfx_guides.wgsl", DECODE_WGSL);+ let taa = raea_sys_frame::engine_shaders::text("raea_render_raytrace/emit_taa.wgsl", super::emit_taa::WGSL);+ let source = format!("{guides}{taa}");let module = dev.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("metalfx guides"), source: wgpu::ShaderSource::Wgsl(source.into()) });let make = |entry: &str| dev.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("metalfx guides"), layout: None, module: &module, entry_point: Some(entry), compilation_options: Default::default(), cache: None });(make("main"), make("restore"), make("restore_taa"), super::emit_taa::sampler(&dev), make("main_psr"))diff --git a/engine/render/src/engine/open.rs b/engine/render/src/engine/open.rsindex 53346751..d5717c74 100644--- a/engine/render/src/engine/open.rs+++ b/engine/render/src/engine/open.rs@@ -198,6 +198,8 @@ impl Engine {fn finish_build(mut app: App, prog: &Program, inserted: &[Tup], dir: &Path, timeline: Option<std::sync::Arc<raea_core_program::timeline::Timeline>>, live: bool) -> Result<Engine, String> {let ss = supersampling(live);let (w, h) = (prog.width * ss, prog.height * ss);+ // every plugin has embedded its shaders by now: a project's engine-shaders/ and RAEA_ENGINE_SHADERS replace them+ raea_sys_frame::engine_shaders::shadow(&mut app, dir);app.finish();mem_mark("engine: plugins finished");// RT4: MetalFX's denoiser goes in after Solari's lighting, which Solari's plugin adds as it finishesdiff --git a/sdk/guides/craft/bevy/limits.md b/sdk/guides/craft/bevy/limits.mdindex e789fa38..966dc39f 100644--- a/sdk/guides/craft/bevy/limits.md+++ b/sdk/guides/craft/bevy/limits.md@@ -47,6 +47,17 @@ The router's eight, plus:- A partly transparent page element over the 3D blends slightly differently in a render than in play; keep pageparts over 3D opaque where it matters.+## One of the engine's own shaders, changed for a project++To try a change to a shader raea or Bevy draws with (the PBR lighting, Solari's, the denoiser's emission pass), put+your copy in the project's `engine-shaders/` folder at the path the engine embeds it, `<crate>/<path under its+src>`: `engine-shaders/bevy_pbr/render/pbr.wesl`, `engine-shaders/raea_render_raytrace/emit_taa.wgsl`. Make the+file empty and render once: raea fills it with the shader it draws with. Change it and render again. From then on,+every render and play of the project draws with your copy from its first frame, with no build. raea names each file it+used and warns that each is tied to this raea's version. It calls a file that matches no engine shader stray. A shader+that fails to compile shows Bevy's validation error, and the parts drawn with it go missing. Use this to find what to+change. A look you keep belongs in a prop or a hook of the engine's: ask for one with `raea bug`.+## Not there yet (don't reach for these; they won't render)- A lens over the page: Fisheye and LensDistortion bend the 3D only. (Ambient occlusion, anti-aliasing modes, depth ofdiff --git a/systems/frame/src/bevy_api.rs b/systems/frame/src/bevy_api.rsindex 001ec877..748c34e3 100644--- a/systems/frame/src/bevy_api.rs+++ b/systems/frame/src/bevy_api.rs@@ -32,9 +32,19 @@ pub fn swap_embedded_shader(app: &mut bevy::app::App, path: &str, upstream_fnv:);let mine = ours(std::str::from_utf8(bevy.value()).expect("Bevy's shader is UTF-8"));reg.insert_asset(std::path::PathBuf::from(file!()), path, mine.into_bytes());+ SWAPPED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(path.to_string_lossy().into_owned());true}+/// The embedded shaders swap_embedded_shader replaced with raea's forks: RAEA_ENGINE_SHADERS leaves them as they are,+/// since the source tree holds Bevy's original, not the fork (engine_shaders.rs).+static SWAPPED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());++/// Whether `path` (as Bevy embeds it) is one of raea's forks of a Bevy shader.+pub fn swapped(path: &str) -> bool {+ SWAPPED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).iter().any(|p| p == path)+}+fn fnv1a(bytes: &[u8]) -> u64 {bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3))}diff --git a/systems/frame/src/engine_shaders.rs b/systems/frame/src/engine_shaders.rsnew file mode 100644index 00000000..b201715f--- /dev/null+++ b/systems/frame/src/engine_shaders.rs@@ -0,0 +1,239 @@+//! raea's and Bevy's own shaders read from files when an Engine opens, in place of the ones compiled into this binary+//! (docs/nobuild.feature NB5b), so trying a change to one needs no build:+//! - a project's `engine-shaders/` folder (beside the edit, or up to three folders above it) mirrors the engine's+//! embedded paths, `<crate>/<path under its src>`: `engine-shaders/bevy_solari/realtime/resolve_dlss_rr_textures.wesl`+//! replaces Solari's. raea says which, once, since such a file is tied to this raea's version of the shader. An empty+//! file there is filled with the shader this raea draws with, the copy to start from (an author has no sources);+//! - RAEA_ENGINE_SHADERS=DIR, a raea checkout: every embedded shader whose source is in DIR's git tree is read from+//! that file, so a session editing an engine shader renders it at once (raea says how many differ from the binary's).+//!+//! A shader a crate passes to wgpu itself (include_str!, not one of Bevy's embedded assets) is read the same way when+//! the crate asks through `text` and names it with `declare` (raea-render-raytrace's); the rest of those (filters,+//! three-shader) don't yet.+//!+//! A shader its plugin loaded as it was built (load_shader_library!) is swapped in Assets<Shader> as its first load+//! lands, in the same update, so no frame draws with the binary's (an AssetServer::reload would land some frames later+//! and recompile every pipeline using it mid-render).+use bevy::asset::io::embedded::EmbeddedAssetRegistry;+use bevy::prelude::*;+use bevy::shader::{Shader, Source};+use std::collections::HashMap;+use std::path::{Path, PathBuf};++/// Replaces the embedded shaders a project's engine-shaders folder or RAEA_ENGINE_SHADERS has files for. Call once+/// every plugin is built, before app.finish.+pub fn shadow(app: &mut App, edit_dir: &Path) {+ let mut done: Vec<String> = Vec::new();+ *PROJECT.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = project_dir(edit_dir);+ let mut swaps = Vec::new();+ if let Some(dir) = project_dir(edit_dir) {+ let (mut ours, mut stray, mut filled) = (Vec::new(), Vec::new(), Vec::new());+ let declared = DECLARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();+ for (rel, file) in walk(&dir) {+ if std::fs::metadata(&file).is_ok_and(|m| m.len() == 0) {+ let builtin = declared.iter().find(|(r, _)| *r == rel).map(|(_, t)| t.as_bytes().to_vec());+ match builtin.or_else(|| original(app, &rel)).map(|b| std::fs::write(&file, b)) {+ Some(Ok(())) => filled.push(rel),+ Some(Err(e)) => eprintln!("raea: {}: {e}", file.display()),+ None => stray.push(rel),+ }+ continue;+ }+ let fork = super::bevy_api::swapped(&rel);+ match replace(app, &rel, &file, &mut swaps) {+ Some(_) => ours.push(if fork { format!("{rel} (over raea's fork of Bevy's)") } else { rel }),+ None if declared.iter().any(|(r, _)| *r == rel) => ours.push(format!("{rel} (read as its pass is made)")),+ None => stray.push(rel),+ }+ }+ if !ours.is_empty() {+ eprintln!("raea: {} of the engine's shaders from {} in place of this raea's ({}); each is tied to this raea's version of it (docs/nobuild.feature NB5b)", ours.len(), dir.display(), ours.join(", "));+ }+ let ours: Vec<String> = ours.into_iter().map(|r| r.split(" (").next().unwrap_or_default().to_string()).collect();+ if !stray.is_empty() {+ eprintln!("raea: {} has no engine shader at {} (the path is <crate>/<path under its src>, as Bevy embeds it)", dir.display(), stray.join(", "));+ }+ if !filled.is_empty() {+ eprintln!("raea: filled {} empty file(s) in {} with the shader this raea draws with ({}); this render used them as they were, so change them and render again", filled.len(), dir.display(), filled.join(", "));+ }+ done = ours;+ }+ if let Some(root) = std::env::var_os("RAEA_ENGINE_SHADERS").map(PathBuf::from) {+ from_tree(app, &root, &done, &mut swaps);+ }+ if !swaps.is_empty() {+ app.insert_resource(Swaps(swaps)).add_systems(PreUpdate, swap_loaded.after(bevy::asset::AssetTrackingSystems));+ }+}++/// RAEA_ENGINE_SHADERS: every embedded shader with a source file in `root`'s git tree, but those the project's folder+/// gave (`done`) and raea's forks of Bevy's.+fn from_tree(app: &mut App, root: &Path, done: &[String], swaps: &mut Vec<(String, String)>) {+ let (mut read, mut differ, mut forks) = (0, Vec::new(), 0);+ let files = tree(root);+ TREE.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone_from(&files);+ for (rel, file) in files {+ if done.contains(&rel) {+ continue;+ }+ // raea's forks of Bevy's shaders are made from Bevy's at load; the tree's file is Bevy's original+ if super::bevy_api::swapped(&rel) {+ forks += 1;+ continue;+ }+ if let Some(same) = replace(app, &rel, &file, swaps) {+ read += 1;+ if !same {+ differ.push(rel);+ }+ }+ }+ let list = if differ.is_empty() { String::new() } else { format!(": {}", differ.join(", ")) };+ eprintln!("raea: RAEA_ENGINE_SHADERS: {read} engine shaders read from {}, {} unlike this binary's{list} ({forks} of raea's forks of Bevy's kept as made)", root.display(), differ.len());+}++/// The engine-shaders folder of the edit the last Engine opened (shadow), for `text`.+static PROJECT: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);++/// RAEA_ENGINE_SHADERS' tree as the last Engine opened read it (from_tree): each shader's path and its file, for `text`.+static TREE: std::sync::Mutex<Vec<(String, PathBuf)>> = std::sync::Mutex::new(Vec::new());++/// The shaders crates read through `text` (`declare`), each path and its built-in text: a project's file for one isn't+/// stray, and an empty one is filled with it.+static DECLARED: std::sync::Mutex<Vec<(&'static str, &'static str)>> = std::sync::Mutex::new(Vec::new());++/// Names the shaders a crate reads through `text`: each as `<crate>/<path under its src>` with its built-in text. Call+/// before the Engine's plugins finish (a plugin's build).+pub fn declare(shaders: &[(&'static str, &'static str)]) {+ let mut d = DECLARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ for s in shaders {+ if !d.iter().any(|(r, _)| *r == s.0) {+ d.push(*s);+ }+ }+}++/// The bytes this binary embeds at `rel` (raea's fork, where raea forks Bevy's), left in place.+fn original(app: &App, rel: &str) -> Option<Vec<u8>> {+ let reg = app.world().resource::<EmbeddedAssetRegistry>();+ let old = reg.remove_asset(Path::new(rel))?.value().to_vec();+ reg.insert_asset(PathBuf::from(file!()), Path::new(rel), old.clone());+ Some(old)+}++/// A shader a crate hands to wgpu itself, as `shadow` reads the embedded ones: the project's engine-shaders/ file at+/// `rel` (`<crate>/<path under its src>`, named first with `declare`), else RAEA_ENGINE_SHADERS' file for it, else+/// `builtin`. Says so when what it reads isn't `builtin`.+pub fn text(rel: &str, builtin: &'static str) -> std::borrow::Cow<'static, str> {+ let project = PROJECT.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone().map(|d| d.join(rel)).filter(|f| f.is_file());+ let tree = || TREE.lock().unwrap_or_else(std::sync::PoisonError::into_inner).iter().find(|(r, _)| r == rel).map(|(_, f)| f.clone());+ let Some(file) = project.or_else(tree) else { return builtin.into() };+ match std::fs::read_to_string(&file) {+ Ok(s) if s != builtin => {+ eprintln!("raea: the engine's {rel} from {} in place of this raea's (docs/nobuild.feature NB5b)", file.display());+ s.into()+ }+ Ok(_) => builtin.into(),+ Err(e) => {+ eprintln!("raea: {}: {e}; using this raea's {rel}", file.display());+ builtin.into()+ }+ }+}++/// The engine's embedded shader at `rel` replaced by `file`'s bytes, for every load from now on, and added to `swaps`+/// for a load already started; whether they were the same (then nothing is touched). None when there's no embedded+/// asset at `rel` or the file can't be read.+fn replace(app: &mut App, rel: &str, file: &Path, swaps: &mut Vec<(String, String)>) -> Option<bool> {+ let bytes = std::fs::read(file).ok()?;+ let reg = app.world().resource::<EmbeddedAssetRegistry>();+ let old = reg.remove_asset(Path::new(rel))?;+ let same = old.value() == bytes.as_slice();+ if same {+ reg.insert_asset(PathBuf::from(file!()), Path::new(rel), old.value().to_vec());+ return Some(true);+ }+ if let Ok(text) = std::str::from_utf8(&bytes) {+ swaps.push((rel.to_string(), text.to_string()));+ }+ reg.insert_asset(file.to_path_buf(), Path::new(rel), bytes);+ Some(false)+}++/// The shaders `replace` changed whose plugin loaded them before they were: (path, text), until each is swapped.+#[derive(Resource)]+struct Swaps(Vec<(String, String)>);++/// A replaced shader whose load began before its file was read (load_shader_library! at a plugin's build), swapped in+/// Assets<Shader> as that load lands: right after the asset server hands it over, in the same update, so the events+/// PostUpdate sends carry the file's text to the pipelines' first compile. Its defs and dependencies are the loaded one's.+fn swap_loaded(server: Res<AssetServer>, mut shaders: ResMut<Assets<Shader>>, mut swaps: ResMut<Swaps>) {+ swaps.0.retain(|(rel, text)| {+ let Some(h) = server.get_handle::<Shader>(format!("embedded://{rel}")) else { return true };+ let Some(old) = shaders.get(&h) else { return true };+ let (Source::Wgsl(s) | Source::Wesl(s)) = &old.source else { return false };+ if s == text {+ return false;+ }+ let mut new = if matches!(old.source, Source::Wesl(_)) { Shader::from_wesl(text.clone(), old.path.clone()) } else { Shader::from_wgsl(text.clone(), old.path.clone()) };+ new.shader_defs.clone_from(&old.shader_defs);+ new.file_dependencies.clone_from(&old.file_dependencies);+ let _ = shaders.insert(h.id(), new);+ false+ });+}++/// The nearest engine-shaders folder: beside the edit, or up to three folders above it.+fn project_dir(edit_dir: &Path) -> Option<PathBuf> {+ edit_dir.ancestors().take(4).map(|d| d.join("engine-shaders")).find(|d| d.is_dir())+}++/// Every file under `dir`, with its path relative to it ('/'-separated).+fn walk(dir: &Path) -> Vec<(String, PathBuf)> {+ let mut out = Vec::new();+ let mut stack = vec![dir.to_path_buf()];+ while let Some(d) = stack.pop() {+ let Ok(rd) = std::fs::read_dir(&d) else { continue };+ for e in rd.flatten() {+ let p = e.path();+ if p.is_dir() {+ stack.push(p);+ } else if let Ok(r) = p.strip_prefix(dir) {+ out.push((r.components().map(|c| c.as_os_str().to_string_lossy()).collect::<Vec<_>>().join("/"), p));+ }+ }+ }+ out.sort();+ out+}++/// Every .wgsl and .wesl file in `root`'s git tree under a crate's src, with the path Bevy embeds it at: the crate's+/// name (dashes as underscores), then its path under src.+fn tree(root: &Path) -> Vec<(String, PathBuf)> {+ let Ok(out) = std::process::Command::new("git").arg("-C").arg(root).args(["ls-files", "-z", "--", "*.wgsl", "*.wesl"]).output() else {+ eprintln!("raea: RAEA_ENGINE_SHADERS: git couldn't list {}", root.display());+ return Vec::new();+ };+ let mut crates: HashMap<PathBuf, Option<String>> = HashMap::new();+ let mut found = Vec::new();+ for rel in out.stdout.split(|b| *b == 0).filter(|r| !r.is_empty()) {+ let file = root.join(String::from_utf8_lossy(rel).as_ref());+ // the nearest folder above it with a Cargo.toml is its crate+ let Some((dir, name)) = file.ancestors().skip(1).take_while(|d| d.starts_with(root)).find_map(|d| crate_name(&mut crates, d).map(|n| (d.to_path_buf(), n))) else { continue };+ let Ok(under) = file.strip_prefix(dir.join("src")) else { continue };+ let under = under.components().map(|c| c.as_os_str().to_string_lossy()).collect::<Vec<_>>().join("/");+ found.push((format!("{}/{under}", name.replace('-', "_")), file));+ }+ found+}++fn crate_name(seen: &mut HashMap<PathBuf, Option<String>>, dir: &Path) -> Option<String> {+ seen.entry(dir.to_path_buf())+ .or_insert_with(|| {+ let toml = std::fs::read_to_string(dir.join("Cargo.toml")).ok()?;+ let package = toml.split("[package]").nth(1)?;+ let line = package.lines().find(|l| l.trim_start().starts_with("name"))?;+ Some(line.split('"').nth(1)?.to_string())+ })+ .clone()+}diff --git a/systems/frame/src/lib.rs b/systems/frame/src/lib.rsindex bd7b9277..5dae0cc1 100644--- a/systems/frame/src/lib.rs+++ b/systems/frame/src/lib.rs@@ -10,6 +10,8 @@ use raea_core_program::eval::{self, Tup};use raea_core_program::ir::{Program, V};pub mod bevy_api;+// the engine's shaders read from files at load: a project's engine-shaders/, RAEA_ENGINE_SHADERS (docs/nobuild.feature NB5b)+pub mod engine_shaders;/// a camera row's order, clear and viewport among the cameras on its targetpub mod camera;/// a GPU error as the frame's error (#66), Bevy's RenderErrorHandler in the engine