// Instanced mesh shader for the 3D viewport.
//
// Same lighting model as mesh.wgsl but reads per-instance data from a
// storage buffer indexed by @builtin(instance_index) instead of a uniform.
//
// Group 0: Camera + shadow atlas + lights + clip planes + shadow info (unchanged from mesh.wgsl).
// Group 1: Storage buffer containing array<InstanceData> (binding 0)
// + Albedo texture (binding 1) + sampler (binding 2)
// + normal map (binding 3) + AO map (binding 4).
struct Camera {
view_proj: mat4x4<f32>,
eye_pos: vec3<f32>,
_pad: f32,
forward: vec3<f32>,
_pad1: f32,
inv_view_proj: mat4x4<f32>,
};
// Shared light struct definitions and `lights_storage` binding 13 of group 0.
// #include "scene_lighting.wgsl"
// Per-vertex deformation hook contract.
// #include "deform.wgsl"
struct ClipPlanes {
planes: array<vec4<f32>, 6>,
count: u32,
_pad0: u32,
viewport_width: f32,
viewport_height: f32,
};
struct ShadowAtlas {
cascade_vp: array<mat4x4<f32>, 4>,
cascade_splits: vec4<f32>,
cascade_count: u32,
atlas_size: f32,
shadow_filter: u32,
pcss_light_radius: f32,
atlas_rects: array<vec4<f32>, 8>,
};
struct InstanceData {
model: mat4x4<f32>,
colour: vec4<f32>,
selected: u32,
wireframe: u32,
ambient: f32,
diffuse: f32,
specular: f32,
shininess: f32,
has_texture: u32,
use_pbr: u32,
metallic: f32,
roughness: f32,
has_normal_map: u32,
has_ao_map: u32,
unlit: u32,
receive_shadows: u32,
use_flat: u32,
_pad_inst1: u32,
uv_transform: vec4<f32>,
ao_range: vec2<f32>, // (min, max) remap of AO map R sample
_pad_ao_range: vec2<f32>,
};
struct ClipVolumeEntry {
volume_type: u32,
_pad_a: u32,
_pad_b: u32,
_pad_c: u32,
center: vec3<f32>,
radius: f32,
half_extents: vec3<f32>,
_pad1: f32,
col0: vec3<f32>,
_pad2: f32,
col1: vec3<f32>,
_pad3: f32,
col2: vec3<f32>,
_pad4: f32,
}
struct ClipVolumeUB {
count: u32,
_pad_a: u32,
_pad_b: u32,
_pad_c: u32,
volumes: array<ClipVolumeEntry, 4>,
};
@group(0) @binding(0) var<uniform> camera: Camera;
@group(0) @binding(1) var shadow_map: texture_depth_2d;
@group(0) @binding(2) var shadow_sampler: sampler_comparison;
@group(0) @binding(3) var<uniform> lights_uniform: Lights;
@group(0) @binding(4) var<uniform> clip_planes: ClipPlanes;
@group(0) @binding(5) var<uniform> shadow_atlas: ShadowAtlas;
@group(0) @binding(6) var<uniform> clip_volume: ClipVolumeUB;
@group(0) @binding(7) var ibl_irradiance: texture_2d<f32>;
@group(0) @binding(8) var ibl_prefiltered: texture_2d<f32>;
@group(0) @binding(9) var ibl_brdf_lut: texture_2d<f32>;
@group(0) @binding(10) var ibl_sampler: sampler;
@group(0) @binding(11) var ibl_skybox: texture_2d<f32>;
@group(0) @binding(12) var<storage, read_write> debug_frag_buf: array<vec4<f32>>;
// #include "clip_volume_test.wgsl"
@group(1) @binding(0) var<storage, read> instances: array<InstanceData>;
@group(1) @binding(1) var obj_texture: texture_2d<f32>;
@group(1) @binding(2) var obj_sampler: sampler;
@group(1) @binding(3) var normal_map: texture_2d<f32>;
@group(1) @binding(4) var ao_map: texture_2d<f32>;
@group(1) @binding(5) var<storage, read> visibility_indices: array<u32>;
struct VertexIn {
@location(0) position: vec3<f32>,
@location(1) normal: vec3<f32>,
@location(2) colour: vec4<f32>,
@location(3) uv: vec2<f32>,
@location(4) tangent: vec4<f32>,
@builtin(vertex_index) vertex_index: u32,
};
struct VertexOut {
@builtin(position) clip_pos: vec4<f32>,
@location(0) colour: vec4<f32>,
@location(1) world_normal: vec3<f32>,
@location(2) world_pos: vec3<f32>,
@location(3) uv: vec2<f32>,
@location(4) world_tangent: vec4<f32>,
@location(5) @interpolate(flat) instance_idx: u32,
};
@vertex
fn vs_main(in: VertexIn, @builtin(instance_index) idx: u32) -> VertexOut {
let inst = instances[idx];
var out: VertexOut;
var dv = DeformVertex(in.position, in.normal, in.vertex_index);
let dctx = DeformContext(inst.model, inst.model[3].xyz, 0.0, 0u, 0u);
dv = viewport_deform_object_space(dv, dctx);
let model3 = mat3x3<f32>(
inst.model[0].xyz,
inst.model[1].xyz,
inst.model[2].xyz,
);
let world_pos4 = inst.model * vec4<f32>(dv.position, 1.0);
dv.position = world_pos4.xyz;
dv.normal = normalize(model3 * dv.normal);
dv = viewport_deform_world_space(dv, dctx);
let world_pos = vec4<f32>(dv.position, 1.0);
out.clip_pos = camera.view_proj * world_pos;
out.colour = in.colour;
out.world_pos = world_pos.xyz;
out.world_normal = dv.normal;
out.world_tangent = vec4<f32>(normalize(model3 * in.tangent.xyz), in.tangent.w);
out.uv = in.uv;
out.instance_idx = idx;
return out;
}
// GPU-driven cull variant: `idx` is the visible-slot index written by the
// compute cull pass. Look up the actual instance index via visibility_indices,
// then run the same transform as vs_main.
@vertex
fn vs_main_cull(in: VertexIn, @builtin(instance_index) idx: u32) -> VertexOut {
let actual_idx = visibility_indices[idx];
let inst = instances[actual_idx];
var out: VertexOut;
var dv = DeformVertex(in.position, in.normal, in.vertex_index);
let dctx = DeformContext(inst.model, inst.model[3].xyz, 0.0, 0u, 0u);
dv = viewport_deform_object_space(dv, dctx);
let model3 = mat3x3<f32>(
inst.model[0].xyz,
inst.model[1].xyz,
inst.model[2].xyz,
);
let world_pos4 = inst.model * vec4<f32>(dv.position, 1.0);
dv.position = world_pos4.xyz;
dv.normal = normalize(model3 * dv.normal);
dv = viewport_deform_world_space(dv, dctx);
let world_pos = vec4<f32>(dv.position, 1.0);
out.clip_pos = camera.view_proj * world_pos;
out.colour = in.colour;
out.world_pos = world_pos.xyz;
out.world_normal = dv.normal;
out.world_tangent = vec4<f32>(normalize(model3 * in.tangent.xyz), in.tangent.w);
out.uv = in.uv;
out.instance_idx = actual_idx;
return out;
}
// ---------------------------------------------------------------------------
// Poisson disk + CSM shadow sampling (mirrors mesh.wgsl)
// ---------------------------------------------------------------------------
const POISSON_DISK: array<vec2<f32>, 32> = array<vec2<f32>, 32>(
vec2<f32>(-0.94201624, -0.39906216), vec2<f32>( 0.94558609, -0.76890725),
vec2<f32>(-0.09418410, -0.92938870), vec2<f32>( 0.34495938, 0.29387760),
vec2<f32>(-0.91588581, 0.45771432), vec2<f32>(-0.81544232, -0.87912464),
vec2<f32>(-0.38277543, 0.27676845), vec2<f32>( 0.97484398, 0.75648379),
vec2<f32>( 0.44323325, -0.97511554), vec2<f32>( 0.53742981, -0.47373420),
vec2<f32>(-0.26496911, -0.41893023), vec2<f32>( 0.79197514, 0.19090188),
vec2<f32>(-0.24188840, 0.99706507), vec2<f32>(-0.81409955, 0.91437590),
vec2<f32>( 0.19984126, 0.78641367), vec2<f32>( 0.14383161, -0.14100790),
vec2<f32>(-0.44451570, 0.67055830), vec2<f32>( 0.70509040, -0.15854630),
vec2<f32>( 0.07130650, -0.64599580), vec2<f32>( 0.39881030, 0.55789810),
vec2<f32>(-0.60554040, -0.34964830), vec2<f32>( 0.85095100, 0.47178830),
vec2<f32>(-0.47994860, 0.08443340), vec2<f32>(-0.12494190, -0.76098760),
vec2<f32>( 0.64839320, 0.74738240), vec2<f32>(-0.96815740, -0.12345680),
vec2<f32>( 0.27682050, -0.80927180), vec2<f32>(-0.73016460, 0.18344200),
vec2<f32>( 0.54754660, 0.06234570), vec2<f32>(-0.30967360, -0.61021430),
vec2<f32>(-0.57774330, 0.80459740), vec2<f32>( 0.18238670, -0.37596540),
);
struct ShadowSample {
factor: f32,
cascade_idx: u32,
atlas_uv: vec2<f32>,
tile_uv: vec2<f32>,
biased_depth: f32,
surface_depth: f32,
normal_bias_world: f32,
}
fn sample_point_shadow(light: SingleLight, world_pos: vec3<f32>) -> f32 {
if light.point_shadow_slot < 0 {
return 1.0;
}
let to_frag = world_pos - light.pos_or_dir;
let dist = length(to_frag);
let dir = to_frag / max(dist, 1e-5);
let normalised = clamp(dist / max(light.range, 1e-5), 0.0, 1.0);
let bias = 0.0015;
return textureSampleCompare(
point_shadow_cube_tex,
shadow_sampler,
dir,
light.point_shadow_slot,
normalised - bias,
);
}
fn sample_shadow_csm(
world_pos: vec3<f32>,
eye_pos: vec3<f32>,
surface_normal: vec3<f32>,
light_dir: vec3<f32>,
) -> ShadowSample {
let dist = dot(world_pos - eye_pos, camera.forward);
var cascade_idx = 0u;
for (var i = 0u; i < shadow_atlas.cascade_count; i++) {
if dist > shadow_atlas.cascade_splits[i] {
cascade_idx = i + 1u;
}
}
cascade_idx = min(cascade_idx, shadow_atlas.cascade_count - 1u);
let light_clip = shadow_atlas.cascade_vp[cascade_idx] * vec4<f32>(world_pos, 1.0);
let ndc = light_clip.xyz / light_clip.w;
let tile_uv = vec2<f32>(ndc.x * 0.5 + 0.5, -ndc.y * 0.5 + 0.5);
// Remap before range check so atlas_uv is always filled in the returned struct.
let rect = shadow_atlas.atlas_rects[cascade_idx];
let atlas_uv = vec2<f32>(
mix(rect.x, rect.z, tile_uv.x),
mix(rect.y, rect.w, tile_uv.y),
);
let n_dot_l = dot(surface_normal, light_dir);
let offset_sign = select(-1.0, 1.0, n_dot_l >= 0.0);
// World-space texel size of this cascade.
let vp = shadow_atlas.cascade_vp[cascade_idx];
let vp_row0 = vec3<f32>(vp[0][0], vp[1][0], vp[2][0]);
let vp_row1 = vec3<f32>(vp[0][1], vp[1][1], vp[2][1]);
let vp_row2 = vec3<f32>(vp[0][2], vp[1][2], vp[2][2]);
let texel_world = 2.0 / (length(vp_row0) * shadow_atlas.atlas_size * (rect.z - rect.x));
// Branch on primary-light type. See mesh.wgsl for rationale.
let primary_light_type = lights_storage[0].light_type;
var offset_world: vec3<f32>;
var normal_bias: f32;
if primary_light_type == 0u {
// See mesh.wgsl for the n_dot_l scaling rationale.
let bias_floor = 0.001;
normal_bias = mix(texel_world * 1.5, bias_floor, clamp(abs(n_dot_l), 0.0, 1.0));
offset_world = world_pos - light_dir * normal_bias;
} else {
normal_bias = texel_world * mix(1.5, 0.0, clamp(abs(n_dot_l), 0.0, 1.0));
offset_world = world_pos + surface_normal * (offset_sign * normal_bias);
}
let offset_clip = shadow_atlas.cascade_vp[cascade_idx] * vec4<f32>(offset_world, 1.0);
let biased_depth = (offset_clip.xyz / offset_clip.w).z - lights_uniform.shadow_bias;
let surface_depth = ndc.z;
if tile_uv.x < 0.0 || tile_uv.x > 1.0 || tile_uv.y < 0.0 || tile_uv.y > 1.0 ||
ndc.z < 0.0 || ndc.z > 1.0 {
return ShadowSample(1.0, cascade_idx, atlas_uv, tile_uv, biased_depth, surface_depth, normal_bias);
}
// Receiver-plane depth bias: tilt the comparison reference for each filter
// tap to follow the receiver surface's depth gradient in light space. With
// a flat reference, taps on the up-slope side of a tilted receiver read as
// lit whenever the depth margin to the caster is thin (e.g. objects
// resting on a surface), producing speckled self-shadowing. The ortho
// light map is affine (ndc = A * world + b), so the plane normal in NDC is
// m_i = dot(row_i(A), n) / |row_i(A)|^2.
let n_ndc = vec3<f32>(
dot(vp_row0, surface_normal) / dot(vp_row0, vp_row0),
dot(vp_row1, surface_normal) / dot(vp_row1, vp_row1),
dot(vp_row2, surface_normal) / dot(vp_row2, vp_row2),
);
let nz_sign = select(-1.0, 1.0, n_ndc.z >= 0.0);
let nz = nz_sign * max(abs(n_ndc.z), 1e-4);
// Depth change per atlas-UV step. Tile V runs opposite to NDC Y, which
// flips the sign of the Y term.
// Gate receiver-plane bias to directional lights only; see mesh.wgsl.
let rp_gate = select(0.0, 1.0, primary_light_type == 0u);
let depth_grad = vec2<f32>(
-n_ndc.x / nz * 2.0 / (rect.z - rect.x),
n_ndc.y / nz * 2.0 / (rect.w - rect.y),
) * rp_gate;
let texel_size = 1.0 / shadow_atlas.atlas_size;
let noise = fract(52.9829189 * fract(dot(world_pos.xz, vec2<f32>(0.06711056, 0.00583715))));
let rot = noise * 6.28318530;
let sin_r = sin(rot);
let cos_r = cos(rot);
if shadow_atlas.shadow_filter == 1u {
let search_radius = shadow_atlas.pcss_light_radius * 16.0 * texel_size;
var blocker_sum = 0.0;
var blocker_count = 0.0;
for (var i = 0u; i < 16u; i++) {
let d = POISSON_DISK[i];
let rd = vec2<f32>(d.x * cos_r - d.y * sin_r, d.x * sin_r + d.y * cos_r);
let sample_uv = atlas_uv + rd * search_radius;
let clamped_uv = clamp(sample_uv, rect.xy, rect.zw);
let coords = vec2<i32>(clamped_uv * shadow_atlas.atlas_size);
let raw_depth = textureLoad(shadow_map, coords, 0);
if raw_depth < surface_depth {
blocker_sum += raw_depth;
blocker_count += 1.0;
}
}
if blocker_count < 1.0 {
return ShadowSample(1.0, cascade_idx, atlas_uv, tile_uv, biased_depth, surface_depth, normal_bias);
}
let avg_blocker = blocker_sum / blocker_count;
let penumbra_width = shadow_atlas.pcss_light_radius * (biased_depth - avg_blocker) / max(avg_blocker, 0.001);
let filter_radius = max(penumbra_width * 16.0 * texel_size, texel_size);
var shadow = 0.0;
for (var i = 0u; i < 32u; i++) {
let d = POISSON_DISK[i];
let rd = vec2<f32>(d.x * cos_r - d.y * sin_r, d.x * sin_r + d.y * cos_r);
let sample_uv = atlas_uv + rd * filter_radius;
let clamped_uv = clamp(sample_uv, rect.xy, rect.zw);
let tap_depth = biased_depth
+ clamp(dot(depth_grad, clamped_uv - atlas_uv), -0.005, 0.005);
shadow += textureSampleCompare(shadow_map, shadow_sampler, clamped_uv, tap_depth);
}
return ShadowSample(shadow / 32.0, cascade_idx, atlas_uv, tile_uv, biased_depth, surface_depth, normal_bias);
} else {
let pcf_radius = select(4.0, 1.5, primary_light_type == 0u) * texel_size;
var shadow = 0.0;
for (var i = 0u; i < 32u; i++) {
let d = POISSON_DISK[i];
let rd = vec2<f32>(d.x * cos_r - d.y * sin_r, d.x * sin_r + d.y * cos_r);
let sample_uv = atlas_uv + rd * pcf_radius;
let clamped_uv = clamp(sample_uv, rect.xy, rect.zw);
let tap_depth = biased_depth
+ clamp(dot(depth_grad, clamped_uv - atlas_uv), -0.005, 0.005);
shadow += textureSampleCompare(shadow_map, shadow_sampler, clamped_uv, tap_depth);
}
return ShadowSample(shadow / 32.0, cascade_idx, atlas_uv, tile_uv, biased_depth, surface_depth, normal_bias);
}
}
// ---------------------------------------------------------------------------
// PBR BRDF helpers (Cook-Torrance) : mirrors mesh.wgsl
// ---------------------------------------------------------------------------
fn D_GGX(NdotH: f32, roughness: f32) -> f32 {
let a = roughness * roughness;
let a2 = a * a;
let denom = NdotH * NdotH * (a2 - 1.0) + 1.0;
return a2 / (3.14159265 * denom * denom);
}
fn G1_Smith(NdotV: f32, roughness: f32) -> f32 {
let r = roughness + 1.0;
let k = (r * r) / 8.0;
return NdotV / (NdotV * (1.0 - k) + k);
}
fn G_Smith(NdotV: f32, NdotL: f32, roughness: f32) -> f32 {
return G1_Smith(NdotV, roughness) * G1_Smith(NdotL, roughness);
}
fn F_Schlick(cos_theta: f32, F0: vec3<f32>) -> vec3<f32> {
return F0 + (vec3<f32>(1.0) - F0) * pow(clamp(1.0 - cos_theta, 0.0, 1.0), 5.0);
}
// IBL helpers : canonical source: mesh.wgsl
// Keep in sync with: mesh.wgsl, mesh_oit.wgsl, mesh_instanced_oit.wgsl
const IBL_PI: f32 = 3.14159265;
fn dir_to_equirect_uv(dir: vec3<f32>, rotation: f32) -> vec2<f32> {
let s = sin(rotation); let c = cos(rotation);
let d = vec3<f32>(c * dir.x - s * dir.y, s * dir.x + c * dir.y, dir.z);
return vec2<f32>(0.5 + atan2(d.y, d.x) / (2.0 * IBL_PI), 0.5 - asin(clamp(d.z, -1.0, 1.0)) / IBL_PI);
}
fn sample_ibl_irradiance(N: vec3<f32>, rotation: f32) -> vec3<f32> {
return textureSampleLevel(ibl_irradiance, ibl_sampler, dir_to_equirect_uv(N, rotation), 0.0).rgb;
}
fn sample_ibl_prefiltered(R: vec3<f32>, roughness: f32, rotation: f32) -> vec3<f32> {
return textureSampleLevel(ibl_prefiltered, ibl_sampler, dir_to_equirect_uv(R, rotation), roughness * 4.0).rgb;
}
fn sample_brdf_lut(NdotV: f32, roughness: f32) -> vec2<f32> {
return textureSampleLevel(ibl_brdf_lut, ibl_sampler, vec2<f32>(NdotV, roughness), 0.0).rg;
}
fn F_Schlick_roughness(cos_theta: f32, F0: vec3<f32>, roughness: f32) -> vec3<f32> {
return F0 + (max(vec3<f32>(1.0 - roughness), F0) - F0) * pow(clamp(1.0 - cos_theta, 0.0, 1.0), 5.0);
}
struct IblContrib {
diffuse: vec3<f32>,
specular: vec3<f32>,
}
fn ibl_ambient(N: vec3<f32>, V: vec3<f32>, base_colour: vec3<f32>, metallic: f32,
roughness: f32, F0: vec3<f32>, ao: f32, intensity: f32, rotation: f32) -> IblContrib {
let NdotV = max(dot(N, V), 0.001);
let F = F_Schlick_roughness(NdotV, F0, roughness);
let kD = (vec3<f32>(1.0) - F) * (1.0 - metallic);
let irradiance = sample_ibl_irradiance(N, rotation);
let R = reflect(-V, N);
let prefiltered = sample_ibl_prefiltered(R, roughness, rotation);
let brdf = sample_brdf_lut(NdotV, roughness);
let diffuse_ibl = kD * irradiance * base_colour * ao * intensity;
let specular_ibl = prefiltered * (F * brdf.x + brdf.y) * ao * intensity;
return IblContrib(diffuse_ibl, specular_ibl);
}
fn pbr_light_contrib(
N: vec3<f32>, V: vec3<f32>, L: vec3<f32>, radiance: vec3<f32>,
base_colour: vec3<f32>, metallic: f32, roughness: f32, F0: vec3<f32>,
) -> vec3<f32> {
let H = normalize(L + V);
let NdotL = max(dot(N, L), 0.0);
if NdotL <= 0.0 { return vec3<f32>(0.0); }
let NdotV = max(dot(N, V), 0.001);
let NdotH = max(dot(N, H), 0.0);
let HdotV = max(dot(H, V), 0.0);
let D = D_GGX(NdotH, roughness);
let G = G_Smith(NdotV, NdotL, roughness);
let F = F_Schlick(HdotV, F0);
let kS = F;
let kD = (vec3<f32>(1.0) - kS) * (1.0 - metallic);
let specular = (D * G * F) / (4.0 * NdotV * NdotL + 0.001);
return (kD * base_colour / 3.14159265 + specular) * radiance * NdotL;
}
@fragment
fn fs_main(in: VertexOut) -> @location(0) vec4<f32> {
let inst = instances[in.instance_idx];
for (var i = 0u; i < clip_planes.count; i++) {
let plane = clip_planes.planes[i];
if dot(in.world_pos, plane.xyz) + plane.w < 0.0 { discard; }
}
if !clip_volume_test(in.world_pos) { discard; }
if inst.wireframe != 0u { return vec4<f32>(0.75, 0.75, 0.75, 1.0); }
let mat_uv = in.uv * inst.uv_transform.zw + inst.uv_transform.xy;
var tex_colour = vec4<f32>(1.0);
if inst.has_texture == 1u { tex_colour = textureSample(obj_texture, obj_sampler, mat_uv); }
let obj_colour = vec4<f32>(inst.colour.rgb * in.colour.rgb * tex_colour.rgb,
inst.colour.a * in.colour.a * tex_colour.a);
let base_colour = obj_colour.rgb;
// Unlit: skip all lighting, return raw colour directly.
if inst.unlit != 0u {
return vec4<f32>(base_colour, obj_colour.a);
}
var N: vec3<f32>;
if inst.use_flat != 0u {
let dpx = dpdx(in.world_pos);
let dpy = dpdy(in.world_pos);
var Nf = normalize(cross(dpx, dpy));
if dot(Nf, in.world_normal) < 0.0 { Nf = -Nf; }
N = Nf;
} else if inst.has_normal_map != 0u {
let nm_sample = textureSample(normal_map, obj_sampler, mat_uv).rgb;
let ts_normal = normalize(nm_sample * 2.0 - vec3<f32>(1.0));
let T = normalize(in.world_tangent.xyz);
let Ng = normalize(in.world_normal);
let T_orth = normalize(T - dot(T, Ng) * Ng);
let B = cross(Ng, T_orth) * in.world_tangent.w;
let TBN = mat3x3<f32>(T_orth, B, Ng);
N = normalize(TBN * ts_normal);
} else {
N = normalize(in.world_normal);
}
var ao_factor = 1.0;
if inst.has_ao_map != 0u {
let raw_ao = textureSample(ao_map, obj_sampler, mat_uv).r;
ao_factor = mix(inst.ao_range.x, inst.ao_range.y, raw_ao);
}
// Use the geometric fragment normal for shadowing so the receiver test
// matches the faceted mesh that was rasterized into the shadow atlas.
// Use smooth vertex normal for shadow bias (see mesh.wgsl for rationale).
let shadow_normal = N;
let V = normalize(camera.eye_pos - in.world_pos);
let tint = vec4<f32>(1.0, 1.0, 1.0, 1.0);
var last_shadow_sample = ShadowSample(1.0, 0u, vec2<f32>(0.0), vec2<f32>(0.0), 0.0, 0.0, 0.0);
var final_rgb: vec3<f32>;
var dbg_direct_lum = 0.0;
var dbg_ambient_lum = 0.0;
var dbg_ibl_diff_lum = 0.0;
var dbg_ibl_spec_lum = 0.0;
var dbg_emissive_lum = 0.0;
var dbg_roughness = 0.5;
var dbg_metallic = 0.0;
let lum_weights = vec3<f32>(0.2126, 0.7152, 0.0722);
if inst.use_pbr != 0u {
let metallic = clamp(inst.metallic, 0.0, 1.0);
let roughness = max(inst.roughness, 0.04);
let F0 = mix(vec3<f32>(0.04), base_colour, metallic);
var Lo = vec3<f32>(0.0);
for (var i = 0u; i < lights_uniform.count; i++) {
let l = lights_storage[i];
var L: vec3<f32>; var radiance: vec3<f32>;
if l.light_type == 0u {
L = normalize(l.pos_or_dir); radiance = l.colour * l.intensity;
} else if l.light_type == 1u {
let to_light = l.pos_or_dir - in.world_pos; let dist = length(to_light);
L = to_light / max(dist, 0.0001);
let falloff = clamp(1.0 - dist / l.range, 0.0, 1.0);
radiance = l.colour * l.intensity * falloff * falloff;
} else {
let to_light = l.pos_or_dir - in.world_pos; let dist = length(to_light);
L = to_light / max(dist, 0.0001);
let dist_falloff = clamp(1.0 - dist / l.range, 0.0, 1.0);
let spot_dir = normalize(l.spot_direction);
let cos_angle = dot(-L, spot_dir);
let cos_outer = cos(l.outer_angle); let cos_inner = cos(l.inner_angle);
let cone_att = clamp((cos_angle - cos_outer) / max(cos_inner - cos_outer, 0.0001), 0.0, 1.0);
radiance = l.colour * l.intensity * dist_falloff * dist_falloff * cone_att;
}
var shadow_factor = 1.0;
if lights_uniform.shadows_enabled != 0u && inst.receive_shadows != 0u {
if i == 0u && lights_storage[0].light_type != 1u {
last_shadow_sample = sample_shadow_csm(in.world_pos, camera.eye_pos, shadow_normal, L);
shadow_factor = last_shadow_sample.factor;
} else if l.light_type == 1u && l.point_shadow_slot >= 0 {
shadow_factor = sample_point_shadow(l, in.world_pos);
}
}
radiance *= shadow_factor;
Lo += pbr_light_contrib(N, V, L, radiance, base_colour, metallic, roughness, F0);
}
dbg_direct_lum = dot(Lo, lum_weights);
dbg_roughness = roughness;
dbg_metallic = metallic;
var ambient: vec3<f32>;
if lights_uniform.ibl_enabled != 0u {
let ibl = ibl_ambient(N, V, base_colour, metallic, roughness, F0,
ao_factor, lights_uniform.ibl_intensity,
lights_uniform.ibl_rotation);
ambient = ibl.diffuse + ibl.specular;
dbg_ibl_diff_lum = dot(ibl.diffuse, lum_weights);
dbg_ibl_spec_lum = dot(ibl.specular, lum_weights);
dbg_ambient_lum = dbg_ibl_diff_lum + dbg_ibl_spec_lum;
} else {
let hemi_t = clamp(in.world_normal.z * 0.5 + 0.5, 0.0, 1.0);
let hemi_colour = mix(lights_uniform.ground_colour, lights_uniform.sky_colour, hemi_t);
let ambient_scale = vec3<f32>(inst.ambient) + hemi_colour * lights_uniform.hemisphere_intensity;
ambient = ambient_scale * (base_colour * (1.0 - metallic) + F0 * metallic) * ao_factor;
dbg_ambient_lum = dot(ambient, lum_weights);
}
final_rgb = clamp((Lo + ambient) * tint.rgb, vec3<f32>(0.0), vec3<f32>(1.0));
} else {
var total_colour_contrib = vec3<f32>(0.0);
for (var i = 0u; i < lights_uniform.count; i++) {
let l = lights_storage[i];
var light_dir: vec3<f32>; var attenuation = 1.0;
if l.light_type == 0u {
light_dir = normalize(l.pos_or_dir);
} else if l.light_type == 1u {
let to_light = l.pos_or_dir - in.world_pos; let dist = length(to_light);
light_dir = to_light / max(dist, 0.0001);
let falloff = clamp(1.0 - dist / l.range, 0.0, 1.0);
attenuation = falloff * falloff;
} else {
let to_light = l.pos_or_dir - in.world_pos; let dist = length(to_light);
light_dir = to_light / max(dist, 0.0001);
let dist_falloff = clamp(1.0 - dist / l.range, 0.0, 1.0);
let spot_dir = normalize(l.spot_direction);
let cos_angle = dot(-light_dir, spot_dir);
let cos_outer = cos(l.outer_angle); let cos_inner = cos(l.inner_angle);
let cone_att = clamp((cos_angle - cos_outer) / max(cos_inner - cos_outer, 0.0001), 0.0, 1.0);
attenuation = dist_falloff * dist_falloff * cone_att;
}
var shadow = 1.0;
if lights_uniform.shadows_enabled != 0u && inst.receive_shadows != 0u {
if i == 0u && lights_storage[0].light_type != 1u {
last_shadow_sample = sample_shadow_csm(in.world_pos, camera.eye_pos, shadow_normal, light_dir);
shadow = last_shadow_sample.factor;
} else if l.light_type == 1u && l.point_shadow_slot >= 0 {
shadow = sample_point_shadow(l, in.world_pos);
}
}
let H = normalize(light_dir + V);
let n_dot_l = max(dot(N, light_dir), 0.0);
let n_dot_h = max(dot(N, H), 0.0);
let diffuse_contrib = inst.diffuse * n_dot_l * l.intensity * attenuation * shadow;
let specular_contrib = inst.specular * pow(n_dot_h, inst.shininess)
* l.intensity * attenuation * shadow;
total_colour_contrib += (diffuse_contrib + specular_contrib) * l.colour;
}
let ambient_contrib = inst.ambient;
let hemi_t = clamp(in.world_normal.z * 0.5 + 0.5, 0.0, 1.0);
let hemi_colour = mix(lights_uniform.ground_colour, lights_uniform.sky_colour, hemi_t);
let hemi_ambient = hemi_colour * lights_uniform.hemisphere_intensity;
let direct_rgb = base_colour * total_colour_contrib;
dbg_direct_lum = dot(direct_rgb, lum_weights);
let hemi_rgb = base_colour * (ambient_contrib + hemi_ambient) * ao_factor;
dbg_ambient_lum = dot(hemi_rgb, lum_weights);
let lit_rgb = hemi_rgb + direct_rgb;
final_rgb = clamp(lit_rgb * tint.rgb, vec3<f32>(0.0), vec3<f32>(1.0));
}
// #include "debug_vis.wgsl"
return vec4<f32>(final_rgb, obj_colour.a);
}