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
A constant in any engine shader is set from TypeScript: <ShaderConstants>, and <SolariLighting constants> for Solari's
shinyobjectzb3c2394cb7b7
diff --git a/Cargo.lock b/Cargo.lockindex d45dfea7..a79ce9eb 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -15963,6 +15963,7 @@ dependencies = ["raea-core-program","raea-core-scene","raea-io-media",+ "raea-io-trace","raea-sys-layers","raea-sys-shots","serde_json",diff --git a/docs/manual/reference/sdk/index.md b/docs/manual/reference/sdk/index.mdindex 4c479dc0..cb7a2ba9 100644--- a/docs/manual/reference/sdk/index.md+++ b/docs/manual/reference/sdk/index.md@@ -72,7 +72,7 @@ Bevy's 3D: cameras, lights, materials, meshes and the frame after it's drawn.| [`raea/3d`](3d.md) | raea's scene layer: models, physics, splats, matchmoves, instancing, custom shader passes and 3D text. | 70 components, 4 hooks, 26 functions, 3 classes, 12 values, 126 types || [`raea/camera`](camera.md) | Cameras and the views they make: Camera3d, the Canvas3D a 2D scene draws in, HDR and matchmoved cameras. | 6 components, 1 hook, 4 functions, 1 value, 15 types || [`raea/light`](light.md) | Bevy's lights in Bevy's units, environments, skies and daylight. | 15 components, 9 functions, 2 values, 15 types |-| [`raea/pbr`](pbr.md) | Materials and volumes: StandardMaterial, extended and toon materials, custom shaders, decals, fog and fire. | 22 components, 1 function, 1 value, 35 types |+| [`raea/pbr`](pbr.md) | Materials and volumes: StandardMaterial, extended and toon materials, custom shaders, decals, fog and fire. | 23 components, 1 function, 1 value, 37 types || [`raea/mesh`](mesh.md) | Shapes and solids: Mesh3d and Mesh2d, Bevy's primitives, buffer meshes, instancing and exact solids. | 16 components, 1 function, 2 classes, 10 values, 26 types || [`raea/transform`](transform.md) | Where things are: Bevy's Transform and Quat, and nesting. | 2 functions, 2 values, 4 types || [`raea/post_process`](post_process.md) | What's done to the frame after it's drawn: tone mapping, bloom, depth of field, motion blur, grading and outlines. | 12 components, 14 types |diff --git a/docs/manual/reference/sdk/light.md b/docs/manual/reference/sdk/light.mdindex 3104e83d..002ef4ff 100644--- a/docs/manual/reference/sdk/light.md+++ b/docs/manual/reference/sdk/light.md@@ -193,14 +193,30 @@ Used in: [3d/rotate_environment_map](https://github.com/shinyobjectz/raea/blob/mRay-traced direct and indirect light for the <Camera3d> it's inside (Bevy's SolariLighting): shadows, bouncelight and reflections traced against the scene, in place of shadow maps. Needs a GPU with ray queries (Applesilicon on Metal, RTX on Vulkan); elsewhere the scene draws raster-lit and raea says so. On the Mac MetalFX's-temporal denoiser cleans it up (RT4; RAEA_SOLARI_DENOISE=0 shows the raw noise). A <Character> (skinned, morphed) stays raster-lit: Bevy 0.20's-Solari can't trace it.+temporal denoiser cleans it up (RT4; denoise={false} shows the raw noise). A <Character> (skinned, morphed) stays+raster-lit: Bevy 0.20's Solari can't trace it.| Prop | Type | What it does || --- | --- | --- || `restir` | `boolean` | ReSTIR: reuse light samples between pixels and frames (finer shadows, steadier in hard light; slower). Off by default, as Bevy has it || `bounces` | `number` | how many times light bounces (Bevy's default when left out) || `reset` | `boolean` | start the lighting's history again (a cut) |+| `confidenceCap` | `number` | with ReSTIR, the most frames a pixel's reused samples may count for: higher is steadier and slower to follow a change in the light (Bevy's 8) |+| `primarySamples` | `number` | direct light samples at the camera's first hit, a pixel a frame (Bevy's 8). After MetalFX's denoiser 4 bought the window scene nothing over 8 and saved 1.5 ms at 1080p's pixels |+| `secondarySamples` | `number` | direct light samples at each bounce (Bevy's 4) |+| `firstBounce` | `number` | the chance a pixel traces its first bounce this frame, its light divided by it (Russian roulette): 0.5 halves the bounce's tracing, most of a dense forest's (1, every pixel every frame) |+| `cache` | `{ /** frames a cell's light is gathered over: steadier and slower to follow a change (B…` | Solari's world cache, the bounce light it keeps in cells across the scene |+| `scale` | `number` | draw the view at this fraction of its size a side (a third to 1) and let MetalFX's temporal scaler bring it up to the full size, so a game traces fewer pixels: 0.67 traces 45% of them. On the Mac; elsewhere it draws at the full size and raea says so. 1 (or left out): the full size; RAEA_SOLARI_SCALE overrides it |+| `denoise` | `boolean` | MetalFX's temporal denoiser on the lighting. false shows Solari's raw noise. Default true; RAEA_SOLARI_DENOISE=0 overrides it |+| `guides` | `boolean` | the denoiser guided by Solari's own guides, where a mirror's pixel takes what it reflects; false guides it by the G-buffer. Default true; RAEA_SOLARI_PSR=0 overrides it |+| `reflectionDepth` | `boolean` | a glossy surface's pixel as far off as what it reflects in the denoiser's depth, so a reflection doesn't trail what it shows. Default true; RAEA_SOLARI_PSR_DEPTH=0 overrides it |+| `emissive` | `"taa" \| "split" \| "mask"` | an emissive surface's own light: "taa" taken out before the denoiser and gathered over frames (RT11, RT32), "split" each frame's alone, "mask" left in for the denoiser. Default "taa"; RAEA_SOLARI_EMISSIVE overrides it |+| `upscale` | `"one" \| "two"` | a view drawn small (scale below 1): denoised and brought up in "one" pass, or denoised small and scaled in "two". Default "one"; RAEA_SOLARI_UPSCALE overrides it |+| `preexposure` | `number` | what MetalFX divides the light by before it denoises and multiplies it by after. Higher keeps more of a rare bright sample (a lamp found by one path in many) and lets more fireflies through: 1 kept 0.74 of the desk's light, 16 0.86, 64 0.91. Default 16; RAEA_METALFX_PREEXPOSURE overrides it |+| `aa` | `boolean` | jitter a full-size view too, so the denoiser anti-aliases its edges as it gathers frames. Default true; RAEA_SOLARI_AA=0 overrides it |+| `jitter` | `"denoiser" \| "scaler" \| "both" \| "flip" \| "none"` | which of MetalFX's passes is told the camera's jitter: "denoiser", "scaler", "both", "flip" (the denoiser, negated), "none" (and the view isn't jittered). For A/Bs of RT9; default "denoiser"; RAEA_SOLARI_JITTER ("" the denoiser, "0" none) overrides it |+| `emissiveSharpness` | `number` | how fast a sample's weight falls with its distance from a pixel's centre in the emission's history, exp(-k d²) in output pixels: lower is softer. Default 6; RAEA_EMIT_TAA_SHARP overrides it |+| `constants` | `{ /** how far ReSTIR looks for a neighbour's light samples, pixels (30): smaller keeps …` | constants in Solari's and the denoiser's shaders, compiled in when the scene loads (a value changed later in the composition isn't drawn); each left out keeps the shader's own, given in brackets. <ShaderConstants> reaches the rest |### `SpotLight`@@ -392,6 +408,7 @@ The props of [`DirectionalLight`](#directionallight), tabled there.| `rotation` | `number` | a turn about the vertical axis, in radians, for both the light and the sky: puts the sun where the shot wants it || `background` | `boolean` | draw the panorama as the sky behind everything (off by default: light only) || `backgroundIntensity` | `number` | the sky's brightness, when it should differ from the light's (`intensity` by default) |+| `portals` | `[number, number, number][][]` | the openings the sky lights a room through (a skylight, a window), each its four corners in order round it, in metres (a rectangle or any parallelogram). Traced lighting (Solari, the path tracer) samples the sky through each as it samples a lamp, so a room lit through a small opening gets that light smooth and whole, where rays bounced at random find it too rarely for the denoiser to keep (photo 5's hall: half its floor's sky light). Light passes both ways; up to 8; the first frame's hold. Raster lighting doesn't read them |### `PathtracerProps`diff --git a/docs/manual/reference/sdk/pbr.md b/docs/manual/reference/sdk/pbr.mdindex 3509e9fe..21bfbd27 100644--- a/docs/manual/reference/sdk/pbr.md+++ b/docs/manual/reference/sdk/pbr.md@@ -29,7 +29,7 @@ const Ball = () => (import { AmbientOcclusion, Decal, ExtendedMaterial, Fire } from "raea/pbr"```-`raea/pbr` exports 22 components, 1 function, 1 value, 35 types. Bevy's counterpart: `bevy_pbr, bevy_material`. Source: [sdk/raea/src/pbr.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/pbr.ts).+`raea/pbr` exports 23 components, 1 function, 1 value, 37 types. Bevy's counterpart: `bevy_pbr, bevy_material`. Source: [sdk/raea/src/pbr.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/pbr.ts).## Components@@ -179,6 +179,19 @@ colour, texture or finish each gives, the rest of it kept (a run of cabinets pai| `materials` (required) | `MeshStandardMaterialProps[]` | the finishes, each a <MeshStandardMaterial>'s props, over every glTF material or the one its `material` names || `children` | `ReactNode` | the models refinished |+### `ShaderConstants`++Sets constants in one of the engine's own shaders (raea's, Bevy's, Solari's) for this scene. Each `const NAME =...;`+named is rewritten when the scene loads, before anything compiles, so a value is tried in a composition instead of a+build; the shader's own value is the default. Compiled in once: a value that changes later in the composition isn't+drawn, and raea says so. A name the shader doesn't declare is reported and left. One per shader. The common ones have+typed props (<SolariLighting constants>); this reaches the rest.++| Prop | Type | What it does |+| --- | --- | --- |+| `shader` (required) | `string` | the shader as the engine embeds it, `<crate>/<path under its src>`: "bevy_solari/realtime/restir.wesl", "raea_render_raytrace/emit_taa.wgsl". To read its constants, put an empty file of that name in the project's engine-shaders/ folder and render once: raea fills it with the shader |+| `values` (required) | `Record<string, ShaderConstantValue>` | each `const NAME` to set, and its value; the const keeps its type |+### `ShaderExtension`Also takes the props of [`SurfaceShaderSpec`](3d.md#surfaceshaderspec).@@ -442,6 +455,18 @@ ImageSamplerDescriptor ({ path: "checker.png", sampler: { filter: "nearest" } }| `path` (required) | `string` | the picture, in the media folder || `sampler` (required) | `SamplerSpec` | how it's sampled: filter, address modes |+### `ShaderConstantsProps`++The props of [`ShaderConstants`](#shaderconstants), tabled there.++### `ShaderConstantValue`++A shader constant's value: a number (a float or a whole number, as the const is) or a boolean++```ts+type ShaderConstantValue = number | boolean+```+### `ShaderExtensionProps`raea's extension of StandardMaterial written in WESL: itsdiff --git a/engine/render/src/engine/open.rs b/engine/render/src/engine/open.rsindex d5717c74..881ccb60 100644--- a/engine/render/src/engine/open.rs+++ b/engine/render/src/engine/open.rs@@ -199,7 +199,7 @@ impl Engine {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);+ raea_sys_frame::engine_shaders::shadow(&mut app, dir, prog);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 966dc39f..a26a0d80 100644--- a/sdk/guides/craft/bevy/limits.md+++ b/sdk/guides/craft/bevy/limits.md@@ -58,6 +58,12 @@ used and warns that each is tied to this raea's version. It calls a file that mathat fails to compile shows Bevy's validation error, and the parts drawn with it go missing. Use this to find what tochange. A look you keep belongs in a prop or a hook of the engine's: ask for one with `raea bug`.+To change only a constant, you don't need a copy. `<ShaderConstants shader="bevy_solari/realtime/restir.wesl"+values={{ SPATIAL_REUSE_RADIUS_PIXELS: 24 }} />` (`raea/pbr`) anywhere in the scene rewrites that `const` when the+scene loads, and keeps its type. It draws exactly what the same edit in `engine-shaders/` draws. A constant is compiled+in once, so set it from the first frame. A name the shader doesn't declare, an array or a vector is reported and left.+The common ones have typed props, such as `<SolariLighting constants>`.+## 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/sdk/guides/craft/bevy/solari.md b/sdk/guides/craft/bevy/solari.mdindex 4711b113..ec348190 100644--- a/sdk/guides/craft/bevy/solari.md+++ b/sdk/guides/craft/bevy/solari.md@@ -26,6 +26,10 @@defaults are the measured best, so leave them unless a test scene shows otherwise. A developer's environmentvariable of the same setting (`RAEA_SOLARI_DENOISE=0`, `RAEA_METALFX_PREEXPOSURE=4`) overrides the prop on everycamera, for an A/B across many scenes at once.+- The numbers inside Solari's and the denoiser's shaders are props too: `constants` (`spatialReuse`,+ `mirrorRoughness`, `cacheEnd`, `cacheLifetime`, `cacheSearch`, the `reconnect...` three, `mirror`'s four rules,+ `emissiveHistory`). They're compiled into the shaders when the scene loads, so set them from the first frame; a value+ that changes later isn't drawn. `<ShaderConstants>` sets a constant in any other engine shader (`bevy/limits`).- Keep a look's settings as a TypeScript object and spread it: `const LIVE = { primarySamples: 4, scale: 0.67 }`,then `<SolariLighting {...LIVE} />` or `<SolariLighting {...LIVE} preexposure={32} />`.- For a still to judge the look against, use `<Pathtracer />` in its place: exact and slow, accumulating while thediff --git a/sdk/raea/src/pbr.ts b/sdk/raea/src/pbr.tsindex 2797a62d..af11d65a 100644--- a/sdk/raea/src/pbr.ts+++ b/sdk/raea/src/pbr.ts@@ -9,3 +9,5 @@ export { StandardMaterial, ExtendedMaterial, ToonMaterial, type ToonMaterialPropexport { FogFalloff } from "@raea/render/bevy3d";// Lightmap (bevy_pbr::lightmap): a bake on a <Model>'s glTF meshes, by the mesh's nameexport { Lightmap, type LightmapProps } from "@raea/render/bevy3d";+// ShaderConstants: a `const` in one of the engine's own shaders (raea's, Bevy's, Solari's) set when the scene loads+export { ShaderConstants, type ShaderConstantsProps, type ShaderConstantValue } from "@raea/render/bevy3d";diff --git a/sdk/render/src/bevy3d.tsx b/sdk/render/src/bevy3d.tsxindex 1aed2bac..7c3f029a 100644--- a/sdk/render/src/bevy3d.tsx+++ b/sdk/render/src/bevy3d.tsx@@ -14,6 +14,8 @@ export type { EulerRot, TransformValue, TransformBuilt, Mesh3dProps, Projection,export { eulerOf };// ray-traced lighting: Bevy's Solari (docs/raytracing.feature RT3)export { SolariLighting, Pathtracer, type SolariLightingProps, type PathtracerProps } from "./bevy3d/raytracing";+// constants in the engine's own shaders, set when the scene loads (docs/nobuild.feature NB1a)+export { ShaderConstants, type ShaderConstantsProps, type ShaderConstantValue } from "./bevy3d/shaders";export { ConicalFrustum, type ConicalFrustumProps } from "./3d/shapes";// a Bevy texture (a camera's target) drawn in an element (B3 H7)export { TextureView } from "./layers";diff --git a/sdk/render/src/bevy3d/raytracing.tsx b/sdk/render/src/bevy3d/raytracing.tsxindex 2b3b32b4..b3a6d219 100644--- a/sdk/render/src/bevy3d/raytracing.tsx+++ b/sdk/render/src/bevy3d/raytracing.tsx@@ -1,5 +1,6 @@// Ray-traced lighting: Bevy's Solari (docs/raytracing.feature RT3), on the camera it's inside.import { BevyComponent } from "../3d";+import { shaderConstants } from "./shaders";export interface SolariLightingProps {/** ReSTIR: reuse light samples between pixels and frames (finer shadows, steadier in hard light; slower). Off by@@ -68,6 +69,73 @@ export interface SolariLightingProps {/** how fast a sample's weight falls with its distance from a pixel's centre in the emission's history, exp(-k d²) in* output pixels: lower is softer. Default 6; RAEA_EMIT_TAA_SHARP overrides it */emissiveSharpness?: number;+ /** constants in Solari's and the denoiser's shaders, compiled in when the scene loads (a value changed later in the+ * composition isn't drawn); each left out keeps the shader's own, given in brackets. <ShaderConstants> reaches the+ * rest */+ constants?: {+ /** how far ReSTIR looks for a neighbour's light samples, pixels (30): smaller keeps a shadow's edge, larger evens+ * out noise */+ spatialReuse?: number;+ /** a surface smoother than this roughness is traced as a perfect mirror (0.001) */+ mirrorRoughness?: number;+ /** a bounce whose lobe is at least this wide, steradians, ends its path in the world cache (π): smaller ends paths+ * sooner, cheaper and blotchier */+ cacheEnd?: number;+ /** frames a world-cache cell lives without being read (10) */+ cacheLifetime?: number;+ /** tries to find a world-cache cell after a hash collision (3) */+ cacheSearch?: number;+ /** ReSTIR's reconnection of a path to a neighbour's: only at a surface at least this rough (0.6) */+ reconnectRoughness?: number;+ /** past this distance, metres, the far surface's roughness floor falls with the ray's length (1) */+ reconnectRelax?: number;+ /** only when the bounce's footprint is at least this percent of the pixel's (0.02) */+ reconnectFootprint?: number;+ /** the mirror guides' rules (RT17): when a surface is drawn as what it reflects */+ mirror?: {+ /** the share of its reflectance that must leave through the mirror lobe (0.9) */+ replaceFraction?: number;+ /** how far its reflection's depth may shift between neighbouring pixels, as a share of that depth, before it+ * counts as too curved (0.002) */+ depthJitter?: number;+ /** the normal change a flat surface still measures, the G-buffer's rounding (0.002) */+ normalFloor?: number;+ /** metres standing in for "infinitely far" when a mirror ray finds nothing (10000) */+ skyDistance?: number;+ };+ /** the most frames an emissive surface's own light is gathered over (emissive "taa", 16): higher is smoother and+ * slower to follow a change */+ emissiveHistory?: number;+ };+}++/** <SolariLighting constants> as the engine's shader constants (docs/nobuild.feature NB1a), or undefined. */+export function solariConstants(c: SolariLightingProps["constants"]) {+ if (!c) return undefined;+ const at = (v: number | undefined, prop: string, whole = false) => {+ if (v !== undefined && (!(Number.isFinite(v) && v >= 0) || (whole && !Number.isInteger(v)))) throw new RangeError(`SolariLighting: constants.${prop} is ${whole ? "a whole number" : "a number"} of 0 or more, got ${v}`);+ return v;+ };+ const restir = "bevy_solari/realtime/restir.wesl";+ const path = "bevy_solari/realtime/initial_path.wesl";+ const cache = "bevy_solari/realtime/world_cache_query.wesl";+ const mirror = "bevy_solari/realtime/resolve_dlss_rr_textures.wesl";+ const m = c.mirror ?? {};+ return shaderConstants([+ [restir, "SPATIAL_REUSE_RADIUS_PIXELS", at(c.spatialReuse, "spatialReuse")],+ ["bevy_solari/scene/bindings.wesl", "MIRROR_ROUGHNESS_THRESHOLD", at(c.mirrorRoughness, "mirrorRoughness")],+ [path, "CACHE_TERMINATION_MIN_SOLID_ANGLE", at(c.cacheEnd, "cacheEnd")],+ [cache, "WORLD_CACHE_CELL_LIFETIME", at(c.cacheLifetime, "cacheLifetime", true)],+ [cache, "WORLD_CACHE_MAX_SEARCH_STEPS", at(c.cacheSearch, "cacheSearch", true)],+ [path, "RECONNECTION_ROUGHNESS_MIN", at(c.reconnectRoughness, "reconnectRoughness")],+ [path, "RECONNECTION_RELAX_DISTANCE", at(c.reconnectRelax, "reconnectRelax")],+ [path, "RECONNECTION_FOOTPRINT_KAPPA", at(c.reconnectFootprint, "reconnectFootprint")],+ [mirror, "FULL_REPLACEMENT_FRACTION", at(m.replaceFraction, "mirror.replaceFraction")],+ [mirror, "MAX_VIRTUAL_DEPTH_JITTER", at(m.depthJitter, "mirror.depthJitter")],+ [mirror, "NORMAL_QUANTIZATION_FLOOR", at(m.normalFloor, "mirror.normalFloor")],+ [mirror, "ENVIRONMENT_VIRTUAL_DISTANCE", at(m.skyDistance, "mirror.skyDistance")],+ ["raea_render_raytrace/emit_taa.wgsl", "HISTORY_CAP", at(c.emissiveHistory, "emissiveHistory")],+ ]);}/** <SolariLighting>'s denoiser, guide, emission and jitter props as raea_render_raytrace::SolariSettings' fields (only@@ -129,14 +197,16 @@ export function SolariLighting(p: SolariLightingProps = {}) {field("cache.cellSize", "world_cache_position_base_cell_size", c.cellSize);field("cache.lodScale", "world_cache_position_lod_scale", c.lodScale);const settings = solariSettings(p);+ const constants = solariConstants(p.constants);const lighting = <BevyComponent type="bevy_solari::realtime::SolariLighting" value={value} />;const scaled = p.scale !== undefined && p.scale !== 1;- if (!scaled && !settings) return lighting;+ if (!scaled && !settings && !constants) return lighting;return (<>{lighting}{scaled && <BevyComponent type="raea_render_raytrace::RenderScale" value={{ scale: p.scale }} />}{settings && <BevyComponent type="raea_render_raytrace::SolariSettings" value={settings} />}+ {constants}</>);}diff --git a/sdk/render/src/bevy3d/shaders.tsx b/sdk/render/src/bevy3d/shaders.tsxnew file mode 100644index 00000000..1d16d99a--- /dev/null+++ b/sdk/render/src/bevy3d/shaders.tsx@@ -0,0 +1,38 @@+// Constants in the engine's own shaders, set from TypeScript when the scene loads (docs/nobuild.feature NB1a).+import { BevyComponent, Entity } from "../3d";++/** A shader constant's value: a number (a float or a whole number, as the const is) or a boolean */+export type ShaderConstantValue = number | boolean;++export interface ShaderConstantsProps {+ /** the shader as the engine embeds it, `<crate>/<path under its src>`: "bevy_solari/realtime/restir.wesl",+ * "raea_render_raytrace/emit_taa.wgsl". To read its constants, put an empty file of that name in the project's+ * engine-shaders/ folder and render once: raea fills it with the shader */+ shader: string;+ /** each `const NAME` to set, and its value; the const keeps its type */+ values: Record<string, ShaderConstantValue>;+}++/** The engine's component for a list of [shader, const, value] (those whose value is given), or undefined when it sets+ * nothing: the typed props built on <ShaderConstants> (<SolariLighting constants>) put it inside their part. */+export function shaderConstants(list: ReadonlyArray<readonly [string, string, ShaderConstantValue | undefined]>) {+ const values = list+ .filter(([, , v]) => v !== undefined)+ .map(([shader, name, v]) => {+ const value = typeof v === "boolean" ? (v ? 1 : 0) : (v as number);+ if (!Number.isFinite(value)) throw new RangeError(`ShaderConstants: ${name} in ${shader} is a number or a boolean, got ${v}`);+ return { shader, name, value };+ });+ return values.length ? <BevyComponent type="raea_sys_frame::engine_shaders::consts::ShaderConstants" value={{ values }} /> : undefined;+}++/** Sets constants in one of the engine's own shaders (raea's, Bevy's, Solari's) for this scene. Each `const NAME = ...;`+ * named is rewritten when the scene loads, before anything compiles, so a value is tried in a composition instead of a+ * build; the shader's own value is the default. Compiled in once: a value that changes later in the composition isn't+ * drawn, and raea says so. A name the shader doesn't declare is reported and left. One per shader. The common ones have+ * typed props (<SolariLighting constants>); this reaches the rest. */+export function ShaderConstants({ shader, values }: ShaderConstantsProps) {+ if (!/^[a-z0-9_]+\/\S+\.(wgsl|wesl)$/.test(shader)) throw new RangeError(`ShaderConstants: shader is <crate>/<path under its src>, a .wgsl or .wesl file, got ${shader}`);+ const c = shaderConstants(Object.entries(values).map(([n, v]) => [shader, n, v] as const));+ return c ? <Entity name={`shader-constants:${shader}`}>{c}</Entity> : null;+}diff --git a/systems/frame/Cargo.toml b/systems/frame/Cargo.tomlindex 74e77ac0..27563e2d 100644--- a/systems/frame/Cargo.toml+++ b/systems/frame/Cargo.toml@@ -20,6 +20,8 @@ raea-core-scene = { path = "../../core/scene" }# the layer key (key_of), shared with the page's half of the layer passraea-sys-layers = { path = "../layers" }serde_json = "1"+# what each engine shader was compiled from, in the run's trace (engine_shaders.rs)+raea-io-trace = { path = "../../io/trace" }raea-io-media = { path = "../../io/media", default-features = false, optional = true }# the Vulkan device's own memory, for the shadow maps' default size (shadow.rs)diff --git a/systems/frame/src/bevy_api.rs b/systems/frame/src/bevy_api.rsindex 748c34e3..09aaedd7 100644--- a/systems/frame/src/bevy_api.rs+++ b/systems/frame/src/bevy_api.rs@@ -45,7 +45,7 @@ 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 {+pub(crate) 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.rsindex b201715f..55db642c 100644--- a/systems/frame/src/engine_shaders.rs+++ b/systems/frame/src/engine_shaders.rs@@ -17,12 +17,16 @@use bevy::asset::io::embedded::EmbeddedAssetRegistry;use bevy::prelude::*;use bevy::shader::{Shader, Source};+use raea_core_program::ir::Program;++// <ShaderConstants>: a const in an engine shader set from TypeScript when the Engine opens (NB1a)+pub mod consts;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) {+/// Replaces the embedded shaders a project's engine-shaders folder or RAEA_ENGINE_SHADERS has files for, then sets the+/// constants the program's first frame asks for (consts.rs). Call once every plugin is built, before app.finish.+pub fn shadow(app: &mut App, edit_dir: &Path, prog: &Program) {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();@@ -61,6 +65,20 @@ pub fn shadow(app: &mut App, edit_dir: &Path) {if let Some(root) = std::env::var_os("RAEA_ENGINE_SHADERS").map(PathBuf::from) {from_tree(app, &root, &done, &mut swaps);}+ app.register_type::<consts::ShaderConstants>();+ let set = consts::gather(prog);+ let constants = with_constants(app, &set, &mut swaps);+ CONSTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone_from(&set);+ app.insert_resource(consts::Loaded(set)).add_systems(PostUpdate, consts::changed_later);+ // what each shader unlike the binary's was compiled from, by its text's hash: two runs drew with the same shaders+ // when these agree (a TS constant against the same edit in engine-shaders/), whatever their pixels' noise+ if !swaps.is_empty() {+ let list: Vec<_> = swaps+ .iter()+ .map(|(rel, t)| serde_json::json!({ "shader": rel, "fnv": format!("{:#x}", super::bevy_api::fnv1a(t.as_bytes())), "project": done.contains(rel), "constants": constants.contains(rel) }))+ .collect();+ raea_io_trace::event("engine_shaders", serde_json::json!({ "shaders": list }));+ }if !swaps.is_empty() {app.insert_resource(Swaps(swaps)).add_systems(PreUpdate, swap_loaded.after(bevy::asset::AssetTrackingSystems));}@@ -98,6 +116,55 @@ 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 constants the last Engine opened with (shadow), for `text`.+static CONSTS: std::sync::Mutex<Vec<consts::ShaderConstant>> = std::sync::Mutex::new(Vec::new());++/// The program's shader constants written into the text each shader will compile from: an embedded one's in the+/// registry and `swaps`, a declared one's checked here and applied by `text`. Says what it set, and what it couldn't;+/// the embedded shaders it changed.+fn with_constants(app: &mut App, set: &[consts::ShaderConstant], swaps: &mut Vec<(String, String)>) -> Vec<String> {+ let mut shaders: Vec<&str> = set.iter().map(|c| c.shader.as_str()).collect();+ shaders.sort_unstable();+ shaders.dedup();+ let declared = DECLARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();+ let (mut said, mut changed) = (Vec::new(), Vec::new());+ for shader in shaders {+ let builtin = declared.iter().find(|(r, _)| *r == shader).map(|(_, t)| *t);+ let base = match builtin {+ Some(b) => Some(source(shader, b).into_owned()),+ None => original(app, shader).and_then(|b| String::from_utf8(b).ok()),+ };+ let Some(mut s) = base else {+ eprintln!("raea: <ShaderConstants>: no engine shader at {shader} (<crate>/<path under its src>, as Bevy embeds it)");+ continue;+ };+ let before = s.clone();+ for c in set.iter().filter(|c| c.shader == shader) {+ match consts::rewrite(&s, &c.name, c.value) {+ Ok((t, old)) => {+ said.push(format!("{shader} {} {old} -> {}", c.name, c.value));+ s = t;+ }+ Err(e) => eprintln!("raea: <ShaderConstants> {shader}: {e}; left as the shader has it"),+ }+ }+ if builtin.is_none() && s != before {+ let reg = app.world().resource::<EmbeddedAssetRegistry>();+ reg.remove_asset(Path::new(shader));+ reg.insert_asset(PathBuf::from(file!()), Path::new(shader), s.clone().into_bytes());+ match swaps.iter_mut().find(|(r, _)| r == shader) {+ Some(w) => w.1 = s,+ None => swaps.push((shader.to_string(), s)),+ }+ changed.push(shader.to_string());+ }+ }+ if !said.is_empty() {+ eprintln!("raea: shader constants from the scene, compiled in at load: {}", said.join(", "));+ }+ changed+}+/// 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());@@ -125,6 +192,20 @@ fn original(app: &App, rel: &str) -> Option<Vec<u8>> {/// `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 mut s = source(rel, builtin);+ for c in CONSTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).iter().filter(|c| c.shader == rel) {+ if let Ok((t, _)) = consts::rewrite(&s, &c.name, c.value) {+ s = t.into();+ }+ }+ if s != builtin {+ raea_io_trace::event("engine_shader_text", serde_json::json!({ "shader": rel, "fnv": format!("{:#x}", super::bevy_api::fnv1a(s.as_bytes())) }));+ }+ s+}++/// The text `text` starts from: a project's or the tree's file, else `builtin`.+fn source(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() };diff --git a/systems/frame/src/engine_shaders/consts.rs b/systems/frame/src/engine_shaders/consts.rsnew file mode 100644index 00000000..91e26914--- /dev/null+++ b/systems/frame/src/engine_shaders/consts.rs@@ -0,0 +1,143 @@+//! Constants in the engine's shaders set from TypeScript (docs/nobuild.feature NB1a): <ShaderConstants> and the typed+//! props built on it (<SolariLighting constants>) put a ShaderConstants component in the scene, and when an Engine opens+//! each named `const NAME = value;` in that shader's text is rewritten before anything compiles, its type kept (a+//! float, a u32, an i32, a bool). The shader's own value is the default. They are compiled in once, at load: a value+//! changed later in the composition draws nothing new, and raea says so once.+use bevy::prelude::*;+use raea_core_program::ir::{Program, V};+use serde_json::Value;++/// One constant: its shader as Bevy embeds it (`<crate>/<path under its src>`), the const's name, its value (a bool as+/// 1 or 0).+#[derive(Reflect, Clone, Debug, Default, PartialEq)]+#[reflect(Default)]+pub struct ShaderConstant {+ pub shader: String,+ pub name: String,+ pub value: f64,+}++/// The constants a part sets in the engine's shaders, read from the first frame's rows when the Engine opens.+#[derive(Component, Reflect, Clone, Debug, Default, PartialEq)]+#[reflect(Component, Default)]+pub struct ShaderConstants {+ pub values: Vec<ShaderConstant>,+}++const TYPE: &str = "raea_sys_frame::engine_shaders::consts::ShaderConstants";++/// Every ShaderConstants value the program's first frame has, the last one for a shader and name. A part's components+/// are `component` rows (runtime/look `components`: its `type`, its `value` as JSON, and `from` when a later frame+/// brings it, which is left for `changed_later`); a column that holds components inline as JSON is read too.+pub(super) fn gather(prog: &Program) -> Vec<ShaderConstant> {+ let mut out: Vec<ShaderConstant> = Vec::new();+ for (_, rows) in &prog.spawns {+ for r in rows {+ if matches!(r.get("type"), Some(V::S(t)) if t == TYPE) {+ let first = r.get("from").is_none_or(|f| f.num() <= 0.0);+ if let (true, Some(V::S(v))) = (first, r.get("value")) {+ if let Ok(j) = serde_json::from_str::<Value>(v) {+ take(&j, &mut out);+ }+ }+ continue;+ }+ for v in r.values() {+ let V::S(s) = v else { continue };+ if s.contains(TYPE) {+ if let Ok(j) = serde_json::from_str::<Value>(s) {+ walk(&j, &mut out);+ }+ }+ }+ }+ }+ out+}++fn walk(j: &Value, out: &mut Vec<ShaderConstant>) {+ match j {+ Value::Object(o) if o.get("type").and_then(Value::as_str) == Some(TYPE) => take(o.get("value").unwrap_or(&Value::Null), out),+ Value::Object(o) => o.values().for_each(|v| walk(v, out)),+ Value::Array(a) => a.iter().for_each(|v| walk(v, out)),+ _ => {}+ }+}++/// A ShaderConstants value's list, each replacing an earlier one of its shader and name.+fn take(value: &Value, out: &mut Vec<ShaderConstant>) {+ for c in value.get("values").and_then(Value::as_array).into_iter().flatten() {+ let (Some(shader), Some(name)) = (c.get("shader").and_then(Value::as_str), c.get("name").and_then(Value::as_str)) else { continue };+ let value = c.get("value").and_then(|v| v.as_f64().or_else(|| v.as_bool().map(f64::from))).unwrap_or(f64::NAN);+ out.retain(|k| !(k.shader == shader && k.name == name));+ out.push(ShaderConstant { shader: shader.into(), name: name.into(), value });+ }+}++/// `text` with `const NAME ... = EXPR;` given `value` in the const's type: the new text and the expression it had.+pub(super) fn rewrite(text: &str, name: &str, value: f64) -> Result<(String, String), String> {+ let mut found = None;+ let mut at = 0;+ for line in text.split_inclusive('\n') {+ let t = line.trim_start();+ if let Some(rest) = t.strip_prefix("const ").map(str::trim_start).and_then(|r| r.strip_prefix(name)) {+ if rest.starts_with([' ', '\t', ':', '=']) {+ if found.is_some() {+ return Err(format!("{name} is declared more than once"));+ }+ found = Some((at + line.len() - rest.len(), rest));+ }+ }+ at += line.len();+ }+ let Some((start, rest)) = found else { return Err(format!("no `const {name}`")) };+ let eq = rest.find('=').ok_or_else(|| format!("{name} has no value"))?;+ let end = rest.find(';').filter(|e| *e > eq).ok_or_else(|| format!("{name}'s value doesn't end on its line"))?;+ let ty = rest[..eq].trim().trim_start_matches(':').trim();+ let old = rest[eq + 1..end].trim();+ if !value.is_finite() {+ return Err(format!("{name} needs a number or a boolean"));+ }+ let int = |suffix: &str, min: f64| {+ if value.fract() != 0.0 || value < min {+ Err(format!("{name} is a whole number{}, not {value}", if min >= 0.0 { " from 0" } else { "" }))+ } else {+ Ok(format!("{value:.0}{suffix}"))+ }+ };+ let new = match ty {+ "bool" => (if value != 0.0 { "true" } else { "false" }).to_string(),+ "u32" => int("u", 0.0)?,+ "i32" => int("i", f64::MIN)?,+ "f32" | "f16" => float(value),+ "" if old == "true" || old == "false" => (if value != 0.0 { "true" } else { "false" }).to_string(),+ "" if old.strip_suffix('u').is_some_and(|n| n.parse::<u64>().is_ok()) => int("u", 0.0)?,+ "" if old.strip_suffix('i').is_some_and(|n| n.parse::<i64>().is_ok()) => int("i", f64::MIN)?,+ "" if old.parse::<i64>().is_ok() => int("", f64::MIN)?,+ // a float literal, or an expression of floats (PI, 1.0 / 16.0); not an array, a vector or a matrix+ "" if !old.contains('<') && !["array", "vec", "mat"].iter().any(|t| old.starts_with(t)) => float(value),+ _ => return Err(format!("{name} is {}, not a number", if ty.is_empty() { old } else { ty })),+ };+ let e0 = start + eq + 1;+ let s = format!("{} {new}{}", &text[..e0], &text[start + end..]);+ Ok((s, old.to_string()))+}++/// A float literal WGSL reads as one: 24 as 24.0.+fn float(v: f64) -> String {+ if v.fract() == 0.0 && v.abs() < 1e15 { format!("{v:.1}") } else { format!("{v}") }+}++/// The constants the Engine opened with, to say once that a later change isn't drawn.+#[derive(Resource)]+pub(super) struct Loaded(pub Vec<ShaderConstant>);++pub(super) fn changed_later(q: Query<&ShaderConstants, Changed<ShaderConstants>>, loaded: Res<Loaded>, mut said: Local<bool>) {+ if *said {+ return;+ }+ if let Some(c) = q.iter().flat_map(|c| &c.values).find(|c| !loaded.0.contains(c)) {+ *said = true;+ eprintln!("raea: the engine's shader constants are compiled in when the scene loads; {} {} = {} came later and isn't drawn (set it from the first frame)", c.shader, c.name, c.value);+ }+}