diff --git a/systems/three-shader/src/glsl.rs b/systems/three-shader/src/glsl.rs index e5e4777d..5d66f9ba 100644 --- a/systems/three-shader/src/glsl.rs +++ b/systems/three-shader/src/glsl.rs @@ -51,6 +51,9 @@ pub struct Source<'a> { pub vertex_colors: bool, /// it draws three.js Points: each point a quad whose corners come as `uv` (0..1), sized by gl_PointSize pub points: bool, + /// its fragment stage writes a surface Bevy lights (surface.rs), not a colour: four outputs in turn, base, normal, + /// emissive and world (a patched built-in material's program, R3F24) + pub lit: bool, } /// Both stages translated: each the WGSL that goes after module.rs's prelude, the uniforms they declare (laid out by @@ -157,8 +160,8 @@ fn naga_wgsl(glsl: &str, vertex: bool) -> Result<(String, BTreeMap Result { +/// its order (location i); a lit stage's carry the instance after them (surface.rs). +fn varyings_struct(vs: &[Var], points: bool, lit: bool) -> Result { let mut m = String::from("struct ThreeVaryings {\n @builtin(position) clip: vec4,\n"); if points { m += &format!(" @location({}) corner: vec2,\n", vs.len()); @@ -174,6 +177,9 @@ fn varyings_struct(vs: &[Var], points: bool) -> Result { } m += &format!(" @location({i}){} v{i}: {},\n", if flat { " @interpolate(flat)" } else { "" }, ty.wgsl()); } + if lit { + m += &format!(" @location({}) @interpolate(flat) three_instance: u32,\n", vs.len() + usize::from(points)); + } Ok(m + "};\n") } @@ -212,6 +218,9 @@ fn set_builtins(names: &BTreeMap, model: bool) -> String { const NORMAL_MATRIX: &str = "fn three_normal_matrix(mv: mat4x4) -> mat3x3 {\n let a = mat3x3(mv[0].xyz, mv[1].xyz, mv[2].xyz);\n let c0 = cross(a[1], a[2]);\n let c1 = cross(a[2], a[0]);\n let c2 = cross(a[0], a[1]);\n return mat3x3(c0, c1, c2) * (1.0 / dot(a[0], c0));\n}\n"; +/// A lit stage's surface (surface.rs) and the entry that returns it +const SURFACE: &str = "struct ThreeSurface { base: vec4, normal: vec4, emissive: vec4, world: vec4 }\n\nfn three_surface(in: ThreeVaryings, front: bool) -> ThreeSurface {\n"; + /// A ShaderMaterial's two stages as a three shader's (module.rs's contract). pub fn translate(src: &Source, textures: &[String]) -> Result { let vs = scan(src.vertex, true)?; @@ -279,7 +288,7 @@ pub fn translate(src: &Source, textures: &[String]) -> Result Result vec4 {\n" }; f += &set_builtins(&fn_, false); f += &set_uniforms(&user_uniforms, &fn_); for (i, x) in vary.iter().enumerate() { @@ -335,6 +344,14 @@ pub fn translate(src: &Source, textures: &[String]) -> Result = fs.outputs.iter().filter_map(|o| fn_.get(&o.name).cloned()).collect(); + if outs.len() != 4 { + return Err(format!("fragment: a lit shader writes 4 outputs (base, normal, emissive, world), got {}", outs.len())); + } + f += &format!(" return ThreeSurface({});\n}}\n", outs.join(", ")); + return Ok(Translated { vertex: v, fragment: f, uniforms, samplers, attributes }); + } let colour = match fs.outputs.first() { Some(o) => fn_.get(&o.name).cloned(), None if src.fragment.contains("gl_FragData") => fn_.get("rg_fragdata").map(|g| format!("{g}[0]")), @@ -367,7 +384,7 @@ mod tests { #[test] fn a_shader_material_translates_to_the_contract() { - let t = translate(&Source { vertex: VERT, fragment: FRAG, raw: false, vertex_colors: false, points: false }, &["map".into()]).unwrap(); + let t = translate(&Source { vertex: VERT, fragment: FRAG, raw: false, vertex_colors: false, points: false, lit: false }, &["map".into()]).unwrap(); assert_eq!(t.uniforms.iter().map(|u| u.0.as_str()).collect::>(), vec!["uTime", "uColor"]); assert_eq!(t.samplers, vec!["map".to_string()]); assert_eq!(t.attributes, vec![("aRandom".to_string(), 1)]); @@ -384,15 +401,27 @@ mod tests { fn a_raw_shader_material_declares_its_own_built_ins() { let vert = "#version 300 es\nprecision highp float;\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nin vec3 position;\nin vec4 color;\nout vec4 vColor;\nvoid main(){ vColor = color; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }"; let frag = "#version 300 es\nprecision highp float;\nin vec4 vColor;\nout vec4 fragColor;\nvoid main(){ fragColor = vColor; }"; - let t = translate(&Source { vertex: vert, fragment: frag, raw: true, vertex_colors: false, points: false }, &[]).unwrap(); + let t = translate(&Source { vertex: vert, fragment: frag, raw: true, vertex_colors: false, points: false, lit: false }, &[]).unwrap(); assert!(t.uniforms.is_empty()); assert!(t.attributes.is_empty()); assert!(t.vertex.contains("= v.color;"), "{}", t.vertex); } + #[test] + fn a_lit_stage_returns_its_surface() { + let frag = "varying vec3 vViewPosition;\nlayout(location = 0) out highp vec4 raeaBase;\nlayout(location = 1) out highp vec4 raeaNormal;\nlayout(location = 2) out highp vec4 raeaEmissive;\nlayout(location = 3) out highp vec4 raeaWorld;\nvoid main(){ raeaBase = vec4(1.0); raeaNormal = vec4(0.0, 0.0, 1.0, 0.5); raeaEmissive = vec4(0.0); raeaWorld = vec4(-vViewPosition, 1.0); }"; + let vert = "varying vec3 vViewPosition;\nvoid main(){ vec4 p = modelViewMatrix * vec4(position, 1.0); vViewPosition = -p.xyz; gl_Position = projectionMatrix * p; }"; + let t = translate(&Source { vertex: vert, fragment: frag, raw: false, vertex_colors: false, points: false, lit: true }, &[]).unwrap(); + assert!(t.fragment.contains("fn three_surface(in: ThreeVaryings, front: bool) -> ThreeSurface {"), "{}", t.fragment); + assert!(t.fragment.contains("return ThreeSurface("), "{}", t.fragment); + assert!(t.vertex.contains("@location(1) @interpolate(flat) three_instance: u32,"), "{}", t.vertex); + let e = translate(&Source { vertex: vert, fragment: "void main(){ gl_FragColor = vec4(1.0); }", raw: false, vertex_colors: false, points: false, lit: true }, &[]).unwrap_err(); + assert!(e.contains("4 outputs"), "{e}"); + } + #[test] fn errors_name_the_stage() { - let e = translate(&Source { vertex: VERT, fragment: "void main(){ gl_FragColor = nope; }", raw: false, vertex_colors: false, points: false }, &["map".into()]).unwrap_err(); + let e = translate(&Source { vertex: VERT, fragment: "void main(){ gl_FragColor = nope; }", raw: false, vertex_colors: false, points: false, lit: false }, &["map".into()]).unwrap_err(); assert!(e.contains("fragment"), "{e}"); } } diff --git a/systems/three-shader/src/lib.rs b/systems/three-shader/src/lib.rs index 4ecf8af7..b9e7513d 100644 --- a/systems/three-shader/src/lib.rs +++ b/systems/three-shader/src/lib.rs @@ -176,7 +176,8 @@ pub fn modules(vertex: &str, fragment: &str, layout: &[Uniform], textures: Optio } /// A three shader's spec, as the SDK's ThreeShaderMaterial gives it: -/// glsl: {vertex, fragment, raw?, vertexColors?} a ShaderMaterial's (includes expanded, defines in front) +/// glsl: {vertex, fragment, raw?, vertexColors?, lit?} a ShaderMaterial's (includes expanded, defines in front); +/// `lit`: its fragment writes a surface Bevy lights (glsl.rs Source) /// wgsl: {vertex, fragment, uniforms: [{name, type, array?}], attributes?: [name], lit?} the contract's, written /// already; `lit`: its fragment stage returns a surface Bevy lights (surface.rs) /// uniforms: {name: number | [numbers]} each one's value (a matrix column-major, an array's elements in turn) @@ -214,11 +215,11 @@ pub fn build(world: &mut World, v: &Value, mut image: impl FnMut(&mut World, &Va } } let names: Vec = tex.iter().map(|t| t.0.clone()).collect(); - let lit = o.get("wgsl").and_then(|w| w.get("lit")) == Some(&Value::Bool(true)); + let lit = [o.get("wgsl"), o.get("glsl")].into_iter().flatten().any(|s| s.get("lit") == Some(&Value::Bool(true))); let (vsrc, fsrc, list, bound, attrs, own_textures) = if let Some(g) = o.get("glsl") { let s = |k: &str| g.get(k).and_then(Value::as_str).ok_or_else(|| format!("a three shader's glsl needs {k}")); let flag = |k: &str| g.get(k) == Some(&Value::Bool(true)); - let src = glsl::Source { vertex: s("vertex")?, fragment: s("fragment")?, raw: flag("raw"), vertex_colors: flag("vertexColors"), points: flag("points") }; + let src = glsl::Source { vertex: s("vertex")?, fragment: s("fragment")?, raw: flag("raw"), vertex_colors: flag("vertexColors"), points: flag("points"), lit }; let t = glsl::translate(&src, &names)?; (t.vertex, t.fragment, t.uniforms, t.samplers, t.attributes.into_iter().map(|a| a.0).collect::>(), false) } else if let Some(w) = o.get("wgsl") {