sgl-3d 0.4.2

Caller-driven 3D rendering for SGL games, native and in the browser (WebGPU)
Documentation
// Scene geometry's camera and probe-capture passes, all over pulled vertices
// (source_vs): the G-buffer (stable_fs and its fallbacks), lit color with
// motion (fs), lit color with its ambient light, motion and exact primitive
// identity (source_fs), the G-buffer and source_fs's outputs at once
// (fused_opaque_fs), blended receivers as the surface (receiver_fs),
// blended surfaces' colour (blended_fs), FSR2's transparency and
// composition mask over moving opaque surfaces (fsr2_composition_fs) and
// the volume layers' depth (volume_entry_fs, volume_exit_fs,
// volume_second_exit_fs). A
// masked material's pipelines discard the texels it cuts out in each opaque
// pass (material_alpha_discard), after the fragment's last derivative.
struct SceneOutput {
 @location(0) color:vec4<f32>,
 @location(1) motion:vec2<f32>,
}
struct StableMaterial {
 normal:vec4<f32>,
 material:vec4<f32>,
 f0:vec4<f32>,
 anisotropy:vec4<f32>,
}
fn stable_material(s:Surface)->StableMaterial {
 // Preserve both lobes: the base follows normal/bump maps, the coat its
 // clearcoat normal map where the record has a coat, else the geometry
 // normal, also where the Surface takes the base normal for want of a coat:
 // the ray-traced shadow trace reaches by this normal, and its texel
 // carries onto neighbours whose own mapped normals may face a light this
 // pixel's does not (traced_visible). The base's F0 and F90 are those its
 // environment lights at the camera's view, beneath its sheen
 // (surface_environment_lobe).
 var o:StableMaterial;
 o.normal=gbuffer_encode_normals(s.normal,select(s.geometry_normal,s.coat_normal,material.coat>0.));
 let lobe=surface_environment_lobe(surface_f0(s),surface_f90(s),surface_sheen_scaling(s));
 o.f0=gbuffer_encode_f0(lobe.f0,!s.unlit,takes_baked_lights(s.baked,s.lightmap_uv,s.moving),s.occlusion);
 o.material=gbuffer_encode_material(s.coat_roughness,s.roughness,s.coat,lobe.f90);
 o.anisotropy=gbuffer_encode_anisotropy(s.anisotropy,s.environment_scale);
 return o;
}
struct StableOutput {
 @location(0) normal:vec4<f32>,
 @location(1) material:vec4<f32>,
 @location(2) motion:vec2<f32>,
 @location(3) f0:vec4<f32>,
 @location(4) anisotropy:vec4<f32>,
}
fn stable_surface(i:Fragment,s:Surface)->StableOutput {
 let m=stable_material(s);
 return StableOutput(m.normal,m.material,gbuffer_encode_motion(i.current_clip,i.previous_clip),m.f0,m.anisotropy);
}
// The G-buffer records no emission.
fn stable_raster_surface(i:Fragment,front:bool)->Surface {
 return raster_surface(i,front,raster_material(i,front),cluster_range(i.world,i.clip.xy));
}
@fragment fn stable_fs(i:Fragment,@builtin(front_facing) raster_front:bool)->StableOutput {
 let front=object_front_face(i,raster_front);
 let s=stable_raster_surface(i,front);
 material_alpha_discard(s.base.a);
 return stable_surface(i,s);
}
// A lit raster fragment: its shading, the surface's alpha and motion.
struct ShadedFragment {
 shaded:Shaded,
 alpha:f32,
 motion:vec2<f32>,
}
// A camera view's lit colour and ambient target texel for `shaded`: its
// ambient light, and the multiple scattering's share of it in lit colour's
// alpha, which source completion reads (shading/gbuffer.wgsl).
fn camera_color(shaded:Shaded)->vec4<f32> {
 return vec4(shaded.color,gbuffer_multiscatter_share(shaded.ambient,shaded.multi));
}
fn camera_ambient(shaded:Shaded)->vec4<f32> {
 return gbuffer_encode_ambient(shaded.ambient,shaded.multi,shaded.sky_visibility);
}
fn shade_surface(i:Fragment,raster_front:bool)->ShadedFragment {
 let front=object_front_face(i,raster_front);
 // Keep split lighting's early unlit exit before normal maps and BRDF
 // sampling: an unlit material reads only its base colour and emission.
 var shaded:Shaded;
 var alpha:f32;
 if (material.flags&MATERIAL_UNLIT)!=0u {
  let m=raster_material(i,front);
  alpha=m.base_color.a;
  material_alpha_discard(alpha);
  shaded=shade_unlit(unlit_surface(m.base_color,raster_emission(i,m.emission)));
 } else {
  let context=raster_context(i);
  let s=raster_surface(i,front,raster_material(i,front),context.clusters);
  alpha=s.base.a;
  material_alpha_discard(alpha);
  shaded=shade_lit(s,context);
 }
 return ShadedFragment(shaded,alpha,gbuffer_encode_motion(i.current_clip,i.previous_clip));
}
// Probe captures, which keep their ambient light, occluded by their
// material's occlusion, in color.
@fragment fn fs(i:Fragment,@builtin(front_facing) front:bool)->SceneOutput {
 let s=shade_surface(i,front);
 return SceneOutput(vec4(s.shaded.color,s.alpha),s.motion);
}

// Devices with the original 32-byte material budget write orientation and
// the environment scale, a material value, in a second depth-equal material
// pass, retaining the complete anisotropic response.
struct LegacyStableOutput {
 @location(0) normal:vec4<f32>,
 @location(1) material:vec4<f32>,
 @location(2) motion:vec2<f32>,
 @location(3) f0:vec4<f32>,
}
@fragment fn stable_legacy_fs(i:Fragment,@builtin(front_facing) raster_front:bool)->LegacyStableOutput {
 let front=object_front_face(i,raster_front);
 let surface=stable_raster_surface(i,front);
 material_alpha_discard(surface.base.a);
 let s=stable_surface(i,surface);
 return LegacyStableOutput(s.normal,s.material,s.motion,s.f0);
}
@fragment fn anisotropy_fs(i:Fragment,@builtin(front_facing) raster_front:bool)->@location(0) vec4<f32> {
 let front=object_front_face(i,raster_front);
 let m=raster_material(i,front);
 var anisotropy=vec4(0.);
 if material.anisotropy_strength>0. {
  anisotropy=surface_anisotropy(i,front,m.normal);
 }
 material_alpha_discard(m.base_color.a);
 return gbuffer_encode_anisotropy(anisotropy,material.environment_scale);
}

// Nonindexed pulled vertices, with source identity carrying the primitive.
// Every camera opaque pass (G-buffer, lighting, fused) draws them, so the
// split and fused forms rasterize one primitive stream: an indexed draw of
// the same triangles changes screen-space derivatives (filtered roughness,
// normal maps, texture LOD) in 2x2 quads spanning two primitives. Godot and
// Wicked likewise share one vertex path between depth prepass and colour pass.
// Each instance of a draw reads its own object record (DrawInstance); a
// GPU-built draw's instance is a section, whose vertices past its triangles
// are dummies.
@vertex fn source_vs(@builtin(vertex_index) draw_vertex:u32,drawn:DrawInstance)->Fragment {
 if drawn_dummy(drawn,draw_vertex) {
  var dummy:Fragment;
  dummy.clip=SCENE_DUMMY_CLIP;
  return dummy;
 }
 let v=scene_source_vertex(drawn.object,drawn.mesh,drawn_index(drawn,draw_vertex));
 let rest=MaterialVertex(v.position,v.normal,v.tangent,v.uv,v.color,v.shader_data,vec4(0.));
 var o=vertex(drawn.object,rest,v.lightmap_uv,v.lightmap_bounds,v.previous_position);
 o.source_id=v.source_id;
 return o;
}
struct SourceOutput {
 @location(0) color:vec4<f32>,
 @location(1) ambient:vec4<f32>,
 @location(2) motion:vec2<f32>,
 @location(3) source_id:vec2<u32>,
}
@fragment fn source_fs(i:Fragment,@builtin(front_facing) front:bool)->SourceOutput {
 let s=shade_surface(i,front);
 return SourceOutput(camera_color(s.shaded),camera_ambient(s.shaded),s.motion,i.source_id);
}

// One depth owner writes both the stable inputs and their primary source.
struct FusedOpaqueOutput {
 @location(0) normal:vec4<f32>,
 @location(1) material:vec4<f32>,
 @location(2) motion:vec2<f32>,
 @location(3) f0:vec4<f32>,
 @location(4) color:vec4<f32>,
 @location(5) ambient:vec4<f32>,
 @location(6) source_id:vec2<u32>,
 @location(7) anisotropy:vec4<f32>,
}
@fragment fn fused_opaque_fs(i:Fragment,@builtin(front_facing) raster_front:bool)->FusedOpaqueOutput {
 let front=object_front_face(i,raster_front);
 let context=raster_context(i);
 let s=raster_surface(i,front,raster_material(i,front),context.clusters);
 material_alpha_discard(s.base.a);
 let stable=stable_surface(i,s);
 var shaded:Shaded;
 if s.unlit {
  shaded=shade_unlit(s);
 } else {
  shaded=shade_lit(s,context);
 }
 return FusedOpaqueOutput(stable.normal,stable.material,stable.motion,stable.f0,camera_color(shaded),camera_ambient(shaded),i.source_id,stable.anisotropy);
}

// The receiver pass (stages/transparent): a blended receiver of screen-space
// reflections as the surface at its pixels, drawn through source_vs as
// blended_fs draws it, over the surface depth it tests strictly nearer and
// writes: its traced lobe into the receiver layer and its unjittered motion
// into the G-buffer's, as HDRP's transparent depth prepass and motion
// vectors draw a material that receives SSR.
struct ReceiverOutput {
 @location(0) receiver:vec4<f32>,
 @location(1) motion:vec2<f32>,
}
@fragment fn receiver_fs(i:Fragment,@builtin(front_facing) raster_front:bool)->ReceiverOutput {
 let front=object_front_face(i,raster_front);
 let recorded=stable_material(stable_raster_surface(i,front));
 let lobe=gbuffer_traced_lobe(recorded.normal,recorded.material,recorded.f0);
 return ReceiverOutput(gbuffer_encode_receiver(lobe),gbuffer_encode_motion(i.current_clip,i.previous_clip));
}

// The volume layers (stages/transparent/volumes.rs): the blended materials
// whose shader reads its volume path, drawn through source_vs as
// blended_fs draws them, with no face culled, over a copy of the opaque
// depth each pass tests strictly nearer and writes, with no colour. Each
// keeps one side, the one the surface function's `front` reports: the
// entry layer the material's front, the exit layer its back, and the
// second exit layer its back behind the exit layer's at the fragment's
// pixel, which it reads (volume_exit_layer); the same triangles rasterised
// through the same @invariant position make that comparison exact, so the
// exit layer's own faces are peeled. Coverage plays no part: a volume's
// boundary is its geometry.
@fragment fn volume_entry_fs(i:Fragment,@builtin(front_facing) raster_front:bool) {
 if !object_front_face(i,raster_front) {
  discard;
 }
}
@fragment fn volume_exit_fs(i:Fragment,@builtin(front_facing) raster_front:bool) {
 if object_front_face(i,raster_front) {
  discard;
 }
}
@fragment fn volume_second_exit_fs(i:Fragment,@builtin(front_facing) raster_front:bool) {
 if object_front_face(i,raster_front) || i.clip.z>=volume_exit_layer(vec2<i32>(i.clip.xy)) {
  discard;
 }
}

// What the frame's screen-space method returned for a blended fragment's
// traced lobe (bind_blended.wgsl): the method's result where the fragment is
// a receiver that is the surface at its pixel, its depth equal to the
// surface depth there, as the receiver pass drew it through the same vertex
// entry (its position @invariant), primitive and depth state; for every
// other fragment, a receiver behind it included, none.
fn blended_traced_reflection(i:Fragment)->TracedReflection {
 let receives=(material.flags&MATERIAL_RECEIVES_SCREEN_SPACE_REFLECTIONS)!=0u;
 if !receives || blended_trace.cutoff<=0. {
  return untraced_reflection();
 }
 let pixel=vec2<i32>(i.clip.xy);
 if textureLoad(blended_surface_depth,pixel,0)!=i.clip.z {
  return untraced_reflection();
 }
 return TracedReflection(textureLoad(blended_reflections,pixel,0),blended_trace.cutoff,blended_trace.fade);
}
// Blended surfaces, which the transparent stage draws back to front over the
// beauty: lit as opaque surfaces are, with the probe and sky specular that
// source completion gives opaque ones (probe_environment), a receiver that
// is the surface composing the screen-space method's result into its traced
// lobe in its place, then fogged from the frame's fog volume where they lie,
// as Bevy 9d12036's forward transparent pass shades and fogs each fragment
// (crates/bevy_pbr/src/render/pbr.wesl) and Godot b130438's samples its
// volumetric fog (scene_forward_clustered.glsl), and blended with their
// alpha, premultiplied, as Filament ef1a133 blends both its transparent
// modes (docs_src/src_markdeep/Filament.md.html, Transparency; Apache-2.0,
// src/LICENSE-filament.txt): with MATERIAL_KEEPS_SPECULAR, Filament's
// transparent mode, its base colour and emission premultiplied before
// shading, so alpha fades its diffuse and emitted light alone, as gltfio
// premultiplies a blended material's base (libs/gltfio/src/
// JitShaderProvider.cpp 177–181) and Filament its emission
// (shaders/src/surface_shading_lit.fs 349–358); else Filament's fade, all
// of its light premultiplied after shading (surface_shading_lit.fs 340–346).
//
// A transmissive material (MATERIAL_TRANSMISSIVE), whatever its alpha mode,
// gives the share of its diffuse light its transmission takes to the light
// transmitted through it from the frame behind it (transmission.wgsl), as
// three.js r185 mixes its total diffuse toward its backdrop
// (src/nodes/lighting/LightsNode.js 399-405, commit 2431a09f, MIT,
// stages/post/smaa/LICENSE-three.txt), under the coat as that diffuse light
// is. Its coverage is its alpha where it is blended, else whole, a masked
// one's cut-out texels discarded. Where the transparent stage's copy holds
// the frame, the transmitted light joins after the surface's fog, the copy
// already fogged to its depth as the blend's destination is, and the
// fragment covers its pixel by its coverage; where none does (the Basic
// binding tier, or the draw into the reflection input), the blend passes
// the light behind it unrefracted: the fragment covers its pixel by its own
// share, its coverage less the share its transmission passes.
struct BlendedColor {
 // Premultiplied colour and the share of the pixel it covers.
 color:vec4<f32>,
 // The share of the pixel's light it gives itself, where the frame behind
 // it is lit alike: its own share and, where it keeps its specular, the
 // reflection its alpha does not fade (FSR2's reactive mask).
 own:f32,
 // Its coverage (FSR2's transparency and composition mask).
 coverage:f32,
}
fn blended_color(i:Fragment,raster_front:bool)->BlendedColor {
 let front=object_front_face(i,raster_front);
 let context=ShadeContext(i.clip.xy,SHADOW_RECEIVER_CAMERA,true,true,cluster_range(i.world,i.clip.xy),blended_traced_reflection(i));
 let m=raster_material(i,front);
 var s=raster_surface(i,front,m,context.clusters);
 let coverage=select(1.,s.base.a,(material.flags&MATERIAL_ALPHA_BLEND)!=0u);
 // The light transmitted through it, times its share of the diffuse light
 // under the sheen and coat, and the share of its pixel it shades itself:
 // compiled in only while the scene holds a transmissive material
 // (transmission_enabled).
 var transmitted=TransmittedLight(vec3(0.),0.);
 var through=0.;
 var own_share=coverage;
 if transmission_enabled && (material.flags&MATERIAL_TRANSMISSIVE)!=0u {
  // A masked material is drawn here only where it is transmissive.
  if material_cut_out(material,s.base.a) {
   discard;
  }
  s.transmission=m.transmission;
  let model=objects[fragment_object(i)].model;
  transmitted=getIBLVolumeRefraction(s.normal,s.view,s.roughness,s.base.rgb*(1.-s.metallic),surface_f0(s),surface_f90(s),s.position,model,m.ior,m.thickness,m.attenuation,m.dispersion);
  through=s.transmission*surface_sheen_scaling(s)*(1.-pbr_coat_fresnel(s.coat_normal,s.view,s.coat));
  own_share=coverage*(1.-through*transmitted.share);
 }
 let keeps_specular=(material.flags&MATERIAL_KEEPS_SPECULAR)!=0u;
 if keeps_specular {
  s.base=vec4(s.base.rgb*coverage,s.base.a);
  s.emission*=coverage;
  // KHR_materials_diffuse_transmission is diffuse light too: its BTDF
  // fades with coverage as the front BRDF does.
  s.diffuse_transmission_color*=coverage;
  // A metal's iridescent F0, which raster_surface refit from its base
  // before the coverage, takes it as the base does: its F0 mixes the two by
  // the film's strength, linearly (surface_f0s).
  s.film.metal*=coverage;
 }
 var shaded:Shaded;
 var own=own_share;
 if s.unlit {
  shaded=shade_unlit(s);
 } else {
  shaded=shade_lit(s,context);
  if keeps_specular {
   own=1.-(1.-own_share)*(1.-blended_reflectance(s));
  }
 }
 let premultiplied=select(shaded.color*coverage,shaded.color,keeps_specular);
 let held=transmission_frame_held();
 // A fragment's position w is one over its view depth.
 let color=frame_fog_premultiplied(premultiplied,own_share,i.clip.xy,1./i.clip.w)+transmitted.light*through*coverage;
 return BlendedColor(vec4(color,select(own_share,coverage,held)),own,coverage);
}
// The mean share of the light along its view a surface reflects, its coat
// over its base, as their split-sum Fresnel gives it: what a blended
// surface that keeps its specular gives the pixel whatever its alpha.
fn blended_reflectance(s:Surface)->f32 {
 let base=pbr_split_sum(surface_f0(s),surface_f90(s),surface_dfg(specular_nv(s.normal,s.view),s.roughness));
 let coat=pbr_coat_fresnel(s.coat_normal,s.view,s.coat);
 return coat+(1.-coat)*(base.r+base.g+base.b)/3.;
}
@fragment fn blended_fs(i:Fragment,@builtin(front_facing) front:bool)->@location(0) vec4<f32> {
 return blended_color(i,front).color;
}
// FSR2's masks (view::targets::mask_targets): AMD's FSR documentation
// (FidelityFX SDK 1.1.4, MIT, see LICENSE-amd-fidelityfx.txt,
// docs/techniques/super-resolution-upscaler.md 131-132, 172, "Reactive
// mask") asks that alpha-blended surfaces, which write no motion, write
// their alpha as reactivity, clamped to 0.9: the share of the pixel's light
// their motion vectors do not describe. A blended surface writes the share
// of the pixel's light it gives itself (BlendedColor.own), its alpha
// unless it is transmissive or keeps its specular. AMD's FSR sample writes
// a translucent surface's alpha as its transparency and composition
// (framework/rendermodules/translucency/shaders/translucencyps.hlsl); a
// blended surface writes its coverage, the whole of a transmissive one's
// pixel, whose refracted light follows no motion vector.
struct BlendedFsr2Masked {
 @location(0) color:vec4<f32>,
 @location(1) reactive:f32,
 @location(2) composition:f32,
}
@fragment fn blended_fsr2_masked_fs(i:Fragment,@builtin(front_facing) front:bool)->BlendedFsr2Masked {
 let blended=blended_color(i,front);
 return BlendedFsr2Masked(blended.color,min(blended.own,.9),blended.coverage);
}
// FSR2's transparency and composition mask over an opaque or masked
// surface whose shading moves where its geometry stands still (its
// material's normal layers; stages/transparent), drawn at the G-buffer's
// depth: 1, as AMD's FSR sample's animated textures write it, its depth and
// motion a static surface's but its contents changing
// (framework/rendermodules/animatedtextures/shaders/AnimatedTexture.hlsl;
// FidelityFX SDK 1.1.4, MIT, see LICENSE-amd-fidelityfx.txt). The reactive
// mask at location 0 is kept (view::targets::composition_targets). A masked
// material's cut-out texels are not its surface.
@fragment fn fsr2_composition_fs(i:Fragment,@builtin(front_facing) raster_front:bool)->@location(1) f32 {
 material_alpha_discard(raster_material(i,object_front_face(i,raster_front)).base_color.a);
 return 1.;
}