Skip to main content

viewport_lib/plugin_api/
shared_wgsl.rs

1//! WGSL helper catalog.
2//!
3//! Each helper is a `&'static str` of WGSL that a plugin shader prefixes (or
4//! concatenates into its own shader source) to gain access to the lib's
5//! shared bindings, shading helpers, and target conventions.
6//!
7//! Versioning: each helper carries a `// @viewport-wgsl-version: N`
8//! comment. The version is bumped whenever a function signature, struct
9//! field, or binding number changes. Plugins compare against
10//! [`WGSL_VERSION`] at build time to detect breakage early. Function bodies
11//! and private fields are not part of the contract and may change between
12//! patch releases.
13//!
14//! Composition: plugin shaders typically build their source as:
15//!
16//! ```ignore
17//! let src = format!(
18//!     "{bindings}\n{pbr}\n{this_pipeline_specific_wgsl}",
19//!     bindings = viewport_lib::plugin_api::shared_wgsl::SHARED_BINDINGS_WGSL,
20//!     pbr      = viewport_lib::plugin_api::shared_wgsl::SHARED_PBR_WGSL,
21//!     this_pipeline_specific_wgsl = include_str!("my_shader.wgsl"),
22//! );
23//! ```
24
25/// Catalog version. Bumped on any breaking change to a helper signature,
26/// struct field, or binding number. Plugins should assert against this at
27/// build time:
28///
29/// ```ignore
30/// const _: () = assert!(viewport_lib::plugin_api::shared_wgsl::WGSL_VERSION == 1);
31/// ```
32pub const WGSL_VERSION: u32 = 5;
33
34/// Group-0 bind declarations and shared scene-data structs.
35///
36/// Declares every binding in the lib's camera/lights/shadows/clip/IBL group,
37/// matching the layout exposed via
38/// [`SharedBindings`](super::SharedBindings). Plugin shaders include this
39/// once and must not re-declare these bindings.
40///
41/// Bindings exposed:
42///
43/// | Binding | Resource | WGSL identifier |
44/// |---------|----------|----------------|
45/// | 0  | `Camera` uniform | `camera` |
46/// | 1  | shadow atlas texture | `shadow_atlas_tex` |
47/// | 2  | shadow comparison sampler | `shadow_atlas_sampler` |
48/// | 3  | `Lights` header uniform | `lights` |
49/// | 4  | `ClipPlanes` uniform | `clip_planes` |
50/// | 5  | *(internal: CSM uniform; route through `viewport_sample_csm`)* | *(opaque)* |
51/// | 6  | `ClipVolumes` uniform | `clip_volumes` |
52/// | 7  | IBL irradiance equirect | `ibl_irradiance_tex` |
53/// | 8  | IBL specular equirect | `ibl_specular_tex` |
54/// | 9  | BRDF integration LUT | `ibl_brdf_lut` |
55/// | 10 | IBL sampler | `ibl_sampler` |
56/// | 11 | Skybox equirect | `skybox_tex` |
57/// | 12 | debug fragment storage buffer | `debug_frag` |
58/// | 13 | per-light array | `lights_storage` |
59pub const SHARED_BINDINGS_WGSL: &str = r#"
60// @viewport-wgsl-version: 1
61// Shared group-0 declarations. Do not re-declare these bindings in plugin
62// shaders.
63
64struct Camera {
65    view_proj:     mat4x4<f32>,
66    eye_pos:       vec3<f32>,
67    _pad0:         f32,
68    forward:       vec3<f32>,
69    _pad1:         f32,
70    inv_view_proj: mat4x4<f32>,
71    view:          mat4x4<f32>,
72};
73
74struct SingleLight {
75    light_view_proj: mat4x4<f32>,
76    pos_or_dir:      vec3<f32>,
77    light_type:      u32,
78    colour:          vec3<f32>,
79    intensity:       f32,
80    range:           f32,
81    inner_angle:     f32,
82    outer_angle:     f32,
83    spot_direction:  vec3<f32>,
84    _pad:            vec2<f32>,
85};
86
87struct Lights {
88    count:                u32,
89    shadow_bias:          f32,
90    shadows_enabled:      u32,
91    debug_vis_mode:       u32,
92    sky_colour:           vec3<f32>,
93    hemisphere_intensity: f32,
94    ground_colour:        vec3<f32>,
95    debug_vis_scale:      f32,
96    ibl_enabled:          u32,
97    ibl_intensity:        f32,
98    ibl_rotation:         f32,
99    show_skybox:          u32,
100    debug_vis_split_x:    f32,
101    _pad_dbg_a:           u32,
102    _pad_dbg_b:           u32,
103    _pad_dbg_c:           u32,
104};
105
106struct ClipPlanes {
107    planes:          array<vec4<f32>, 6>,
108    count:           u32,
109    _pad0:           u32,
110    viewport_width:  f32,
111    viewport_height: f32,
112};
113
114struct ClipVolumeEntry {
115    volume_type:  u32,
116    _pad_a:       u32,
117    _pad_b:       u32,
118    _pad_c:       u32,
119    center:       vec3<f32>,
120    radius:       f32,
121    half_extents: vec3<f32>,
122    _pad1:        f32,
123    col0:         vec3<f32>,
124    _pad2:        f32,
125    col1:         vec3<f32>,
126    _pad3:        f32,
127    col2:         vec3<f32>,
128    _pad4:        f32,
129};
130
131struct ClipVolumeUB {
132    count:    u32,
133    _pad_a:   u32,
134    _pad_b:   u32,
135    _pad_c:   u32,
136    volumes:  array<ClipVolumeEntry, 4>,
137};
138
139@group(0) @binding(0)  var<uniform> camera:               Camera;
140@group(0) @binding(1)  var          shadow_atlas_tex:     texture_depth_2d;
141@group(0) @binding(2)  var          shadow_atlas_sampler: sampler_comparison;
142@group(0) @binding(3)  var<uniform> lights:               Lights;
143@group(0) @binding(4)  var<uniform> clip_planes:          ClipPlanes;
144@group(0) @binding(6)  var<uniform> clip_volume:          ClipVolumeUB;
145@group(0) @binding(7)  var          ibl_irradiance_tex:   texture_2d<f32>;
146@group(0) @binding(8)  var          ibl_specular_tex:     texture_2d<f32>;
147@group(0) @binding(9)  var          ibl_brdf_lut:         texture_2d<f32>;
148@group(0) @binding(10) var          ibl_sampler:          sampler;
149@group(0) @binding(11) var          skybox_tex:           texture_2d<f32>;
150@group(0) @binding(13) var<storage, read> lights_storage: array<SingleLight>;
151
152// Section-view clip planes: returns false when `world_pos` is on the
153// clipped side of any active plane. Plugin fragment shaders call this and
154// `discard` when it returns false to match the lib's clipping behaviour.
155fn viewport_pass_clip_planes(world_pos: vec3<f32>) -> bool {
156    for (var i = 0u; i < clip_planes.count; i = i + 1u) {
157        let plane = clip_planes.planes[i];
158        if dot(world_pos, plane.xyz) + plane.w < 0.0 {
159            return false;
160        }
161    }
162    return true;
163}
164
165// Composable clip volumes (box / sphere / cylinder): returns true when
166// `world_pos` is inside every active clip volume. Returns true when no
167// volumes are active.
168fn viewport_pass_clip_volumes(world_pos: vec3<f32>) -> bool {
169    for (var i = 0u; i < clip_volume.count; i = i + 1u) {
170        let e = clip_volume.volumes[i];
171        if e.volume_type == 2u {
172            let d = world_pos - e.center;
173            let local = vec3<f32>(dot(d, e.col0), dot(d, e.col1), dot(d, e.col2));
174            if abs(local.x) > e.half_extents.x
175                || abs(local.y) > e.half_extents.y
176                || abs(local.z) > e.half_extents.z {
177                return false;
178            }
179        } else if e.volume_type == 3u {
180            let ds = world_pos - e.center;
181            if dot(ds, ds) > e.radius * e.radius { return false; }
182        } else if e.volume_type == 4u {
183            let axis = e.col0;
184            let d = world_pos - e.center;
185            let along = dot(d, axis);
186            if abs(along) > e.half_extents.x { return false; }
187            let radial = d - axis * along;
188            if dot(radial, radial) > e.radius * e.radius { return false; }
189        }
190    }
191    return true;
192}
193
194// Combined clip test. Returns true when the fragment should be kept,
195// false when it should be discarded. Plugin fragment shaders typically:
196//
197//   if !viewport_clip_test(in.world_pos) { discard; }
198fn viewport_clip_test(world_pos: vec3<f32>) -> bool {
199    return viewport_pass_clip_planes(world_pos)
200        && viewport_pass_clip_volumes(world_pos);
201}
202
203// The shadow-info uniform (binding 5) is declared inside SHARED_PBR_WGSL
204// for the sole use of `viewport_sample_csm`. Its struct layout and field
205// set are intentionally not part of the published contract and may change
206// between catalog versions. Plugins must not redeclare binding 5 and must
207// not read the uniform directly; route shadow queries through
208// `viewport_sample_csm`.
209"#;
210
211/// Shared PBR shading helper.
212///
213/// Provides:
214///
215/// ```ignore
216/// fn viewport_pbr_shade(inp: PbrInputs) -> vec3<f32>;
217/// fn viewport_sample_csm(world_pos: vec3<f32>, world_normal: vec3<f32>) -> f32;
218/// fn viewport_apply_scene_lighting(N, base_colour, two_sided, world_pos) -> vec3<f32>;
219/// ```
220///
221/// `viewport_pbr_shade` returns the final lit colour for a fragment given a
222/// `PbrInputs` populated with albedo / normal / metallic / roughness / AO /
223/// emissive. It applies the lib's standard hemisphere ambient + light loop
224/// and attenuates the primary light's contribution by the CSM shadow factor
225/// when `lights.shadows_enabled != 0`. Plugins that compose this helper get
226/// shadows automatically; do not multiply by `viewport_sample_csm` again.
227/// Future revisions may add IBL and SSAO sampling inside this function;
228/// consumers should rebuild their shaders when the catalog version bumps to
229/// pick up the upgrade.
230///
231/// `viewport_sample_csm` returns a 0..1 shadow factor for `world_pos`.
232/// Returns 1.0 (fully lit) when shadows are disabled or the position is
233/// outside every cascade. The cascade scheme, filter kernel, and bias
234/// strategy are internal details and may change between catalog versions;
235/// the function signature and return-value semantics are the contract.
236///
237/// `viewport_apply_scene_lighting` is the simpler Lambert helper used by
238/// non-PBR pipelines (glyphs, tubes, ribbons). Use it when a plugin wants
239/// scene-light parity with those built-in items.
240pub const SHARED_PBR_WGSL: &str = r#"
241// @viewport-wgsl-version: 2
242// Shared PBR / lit-shading helpers. Requires SHARED_BINDINGS_WGSL to be
243// included first.
244//
245// Internal binding: the CSM uniform at @group(0) @binding(5) is declared
246// here for `viewport_sample_csm`'s use. Its struct layout is an internal
247// detail of this catalog; plugin shaders must not reference
248// `_viewport_csm` directly or assume the field set is stable.
249
250struct _ViewportCsm {
251    cascade_vp:        array<mat4x4<f32>, 4>,
252    cascade_splits:    vec4<f32>,
253    cascade_count:     u32,
254    atlas_size:        f32,
255    shadow_filter:     u32,
256    pcss_light_radius: f32,
257    atlas_rects:       array<vec4<f32>, 8>,
258};
259
260@group(0) @binding(5) var<uniform> _viewport_csm: _ViewportCsm;
261
262const _VIEWPORT_POISSON_DISK: array<vec2<f32>, 32> = array<vec2<f32>, 32>(
263    vec2<f32>(-0.94201624, -0.39906216), vec2<f32>( 0.94558609, -0.76890725),
264    vec2<f32>(-0.09418410, -0.92938870), vec2<f32>( 0.34495938,  0.29387760),
265    vec2<f32>(-0.91588581,  0.45771432), vec2<f32>(-0.81544232, -0.87912464),
266    vec2<f32>(-0.38277543,  0.27676845), vec2<f32>( 0.97484398,  0.75648379),
267    vec2<f32>( 0.44323325, -0.97511554), vec2<f32>( 0.53742981, -0.47373420),
268    vec2<f32>(-0.26496911, -0.41893023), vec2<f32>( 0.79197514,  0.19090188),
269    vec2<f32>(-0.24188840,  0.99706507), vec2<f32>(-0.81409955,  0.91437590),
270    vec2<f32>( 0.19984126,  0.78641367), vec2<f32>( 0.14383161, -0.14100790),
271    vec2<f32>(-0.44451570,  0.67055830), vec2<f32>( 0.70509040, -0.15854630),
272    vec2<f32>( 0.07130650, -0.64599580), vec2<f32>( 0.39881030,  0.55789810),
273    vec2<f32>(-0.60554040, -0.34964830), vec2<f32>( 0.85095100,  0.47178830),
274    vec2<f32>(-0.47994860,  0.08443340), vec2<f32>(-0.12494190, -0.76098760),
275    vec2<f32>( 0.64839320,  0.74738240), vec2<f32>(-0.96815740, -0.12345680),
276    vec2<f32>( 0.27682050, -0.80927180), vec2<f32>(-0.73016460,  0.18344200),
277    vec2<f32>( 0.54754660,  0.06234570), vec2<f32>(-0.30967360, -0.61021430),
278    vec2<f32>(-0.57774330,  0.80459740), vec2<f32>( 0.18238670, -0.37596540),
279);
280
281struct PbrInputs {
282    world_pos:  vec3<f32>,
283    world_n:    vec3<f32>,
284    view_dir:   vec3<f32>,
285    albedo:     vec3<f32>,
286    metallic:   f32,
287    roughness:  f32,
288    ao:         f32,
289    emissive:   vec3<f32>,
290};
291
292// Forward declaration: defined below; referenced by the lighting helpers.
293// The full definition appears after the lighting helpers for readability.
294// (WGSL allows module-scope identifiers to be used anywhere in the module
295// regardless of source order.)
296
297fn viewport_apply_scene_lighting(
298    normal: vec3<f32>,
299    base_colour: vec3<f32>,
300    two_sided: bool,
301    world_pos: vec3<f32>,
302) -> vec3<f32> {
303    let up_weight = clamp(normal.z * 0.5 + 0.5, 0.0, 1.0);
304    let ambient = mix(lights.ground_colour, lights.sky_colour, up_weight)
305                  * lights.hemisphere_intensity;
306
307    var direct = vec3<f32>(0.0);
308    let n_lights = lights.count;
309    for (var i: u32 = 0u; i < n_lights; i = i + 1u) {
310        let l = lights_storage[i];
311        var L: vec3<f32>;
312        var radiance: vec3<f32>;
313        if l.light_type == 0u {
314            L = normalize(l.pos_or_dir);
315            radiance = l.colour * l.intensity;
316        } else if l.light_type == 1u {
317            let to_light = l.pos_or_dir - world_pos;
318            let dist = length(to_light);
319            L = to_light / max(dist, 0.0001);
320            let falloff = clamp(1.0 - dist / l.range, 0.0, 1.0);
321            radiance = l.colour * l.intensity * falloff * falloff;
322        } else {
323            let to_light = l.pos_or_dir - world_pos;
324            let dist = length(to_light);
325            L = to_light / max(dist, 0.0001);
326            let dist_falloff = clamp(1.0 - dist / l.range, 0.0, 1.0);
327            let spot_dir = normalize(l.spot_direction);
328            let cos_angle = dot(-L, spot_dir);
329            let cos_outer = cos(l.outer_angle);
330            let cos_inner = cos(l.inner_angle);
331            let cone_att = clamp(
332                (cos_angle - cos_outer) / max(cos_inner - cos_outer, 0.0001),
333                0.0, 1.0,
334            );
335            radiance = l.colour * l.intensity * dist_falloff * dist_falloff * cone_att;
336        }
337        let raw = dot(normal, L);
338        let n_dot_l = select(max(raw, 0.0), abs(raw), two_sided);
339        var shadow_factor = 1.0;
340        if i == 0u {
341            shadow_factor = viewport_sample_csm(world_pos, normal);
342        }
343        direct = direct + radiance * n_dot_l * shadow_factor;
344    }
345    return base_colour * (ambient + direct);
346}
347
348// Cascade selection + atlas tap. Mirrors the bias scheme and filter
349// kernel used by the lib's built-in mesh pipeline so plugin items composite
350// consistently in the same scene. Implementation details (cascade count,
351// filter, bias) are internal and may change between catalog versions.
352fn viewport_sample_csm(world_pos: vec3<f32>, world_normal: vec3<f32>) -> f32 {
353    if lights.shadows_enabled == 0u || lights.count == 0u {
354        return 1.0;
355    }
356
357    let primary = lights_storage[0];
358    var light_dir: vec3<f32>;
359    if primary.light_type == 0u {
360        light_dir = normalize(primary.pos_or_dir);
361    } else {
362        let to_light = primary.pos_or_dir - world_pos;
363        light_dir = to_light / max(length(to_light), 0.0001);
364    }
365
366    let eye_pos = camera.eye_pos;
367    let dist = dot(world_pos - eye_pos, camera.forward);
368
369    var cascade_idx = 0u;
370    for (var i = 0u; i < _viewport_csm.cascade_count; i = i + 1u) {
371        if dist > _viewport_csm.cascade_splits[i] {
372            cascade_idx = i + 1u;
373        }
374    }
375    cascade_idx = min(cascade_idx, _viewport_csm.cascade_count - 1u);
376
377    let light_clip = _viewport_csm.cascade_vp[cascade_idx] * vec4<f32>(world_pos, 1.0);
378    let ndc = light_clip.xyz / light_clip.w;
379    let tile_uv = vec2<f32>(ndc.x * 0.5 + 0.5, -ndc.y * 0.5 + 0.5);
380
381    let rect = _viewport_csm.atlas_rects[cascade_idx];
382    let atlas_uv = vec2<f32>(
383        mix(rect.x, rect.z, tile_uv.x),
384        mix(rect.y, rect.w, tile_uv.y),
385    );
386
387    let n_dot_l = dot(world_normal, light_dir);
388    let offset_sign = select(-1.0, 1.0, n_dot_l >= 0.0);
389    let vp = _viewport_csm.cascade_vp[cascade_idx];
390    let vp_row0 = vec3<f32>(vp[0][0], vp[1][0], vp[2][0]);
391    let vp_row1 = vec3<f32>(vp[0][1], vp[1][1], vp[2][1]);
392    let vp_row2 = vec3<f32>(vp[0][2], vp[1][2], vp[2][2]);
393    let texel_world = 2.0 / (length(vp_row0) * _viewport_csm.atlas_size * (rect.z - rect.x));
394
395    let primary_light_type = primary.light_type;
396    var offset_world: vec3<f32>;
397    if primary_light_type == 0u {
398        let normal_bias = texel_world * 1.5;
399        offset_world = world_pos - light_dir * normal_bias;
400    } else {
401        let normal_bias = texel_world * mix(1.5, 0.0, clamp(abs(n_dot_l), 0.0, 1.0));
402        offset_world = world_pos + world_normal * (offset_sign * normal_bias);
403    }
404    let offset_clip = _viewport_csm.cascade_vp[cascade_idx] * vec4<f32>(offset_world, 1.0);
405    let biased_depth = (offset_clip.xyz / offset_clip.w).z - lights.shadow_bias;
406
407    if tile_uv.x < 0.0 || tile_uv.x > 1.0 || tile_uv.y < 0.0 || tile_uv.y > 1.0 ||
408       ndc.z < 0.0 || ndc.z > 1.0 {
409        return 1.0;
410    }
411
412    let n_ndc = vec3<f32>(
413        dot(vp_row0, world_normal) / dot(vp_row0, vp_row0),
414        dot(vp_row1, world_normal) / dot(vp_row1, vp_row1),
415        dot(vp_row2, world_normal) / dot(vp_row2, vp_row2),
416    );
417    let nz_sign = select(-1.0, 1.0, n_ndc.z >= 0.0);
418    let nz = nz_sign * max(abs(n_ndc.z), 1e-4);
419    let rp_gate = select(0.0, 1.0, primary_light_type == 0u);
420    let depth_grad = vec2<f32>(
421        -n_ndc.x / nz * 2.0 / (rect.z - rect.x),
422         n_ndc.y / nz * 2.0 / (rect.w - rect.y),
423    ) * rp_gate;
424
425    let texel_size = 1.0 / _viewport_csm.atlas_size;
426    let noise = fract(52.9829189 * fract(dot(world_pos.xz, vec2<f32>(0.06711056, 0.00583715))));
427    let rot = noise * 6.28318530;
428    let sin_r = sin(rot);
429    let cos_r = cos(rot);
430
431    if _viewport_csm.shadow_filter == 1u {
432        let search_radius = _viewport_csm.pcss_light_radius * 16.0 * texel_size;
433        var blocker_sum = 0.0;
434        var blocker_count = 0.0;
435        for (var i = 0u; i < 16u; i = i + 1u) {
436            let d = _VIEWPORT_POISSON_DISK[i];
437            let rd = vec2<f32>(d.x * cos_r - d.y * sin_r, d.x * sin_r + d.y * cos_r);
438            let sample_uv = atlas_uv + rd * search_radius;
439            let clamped_uv = clamp(sample_uv, rect.xy, rect.zw);
440            let coords = vec2<i32>(clamped_uv * _viewport_csm.atlas_size);
441            let raw_depth = textureLoad(shadow_atlas_tex, coords, 0);
442            if raw_depth < ndc.z {
443                blocker_sum = blocker_sum + raw_depth;
444                blocker_count = blocker_count + 1.0;
445            }
446        }
447        if blocker_count < 1.0 {
448            return 1.0;
449        }
450        let avg_blocker = blocker_sum / blocker_count;
451        let penumbra_width = _viewport_csm.pcss_light_radius * (biased_depth - avg_blocker) / max(avg_blocker, 0.001);
452        let filter_radius = max(penumbra_width * 16.0 * texel_size, texel_size);
453        var shadow = 0.0;
454        for (var i = 0u; i < 32u; i = i + 1u) {
455            let d = _VIEWPORT_POISSON_DISK[i];
456            let rd = vec2<f32>(d.x * cos_r - d.y * sin_r, d.x * sin_r + d.y * cos_r);
457            let sample_uv = atlas_uv + rd * filter_radius;
458            let clamped_uv = clamp(sample_uv, rect.xy, rect.zw);
459            let tap_depth = biased_depth
460                + clamp(dot(depth_grad, clamped_uv - atlas_uv), -0.005, 0.005);
461            shadow = shadow + textureSampleCompare(shadow_atlas_tex, shadow_atlas_sampler, clamped_uv, tap_depth);
462        }
463        return shadow / 32.0;
464    } else {
465        let pcf_radius = select(4.0, 1.5, primary_light_type == 0u) * texel_size;
466        var shadow = 0.0;
467        for (var i = 0u; i < 32u; i = i + 1u) {
468            let d = _VIEWPORT_POISSON_DISK[i];
469            let rd = vec2<f32>(d.x * cos_r - d.y * sin_r, d.x * sin_r + d.y * cos_r);
470            let sample_uv = atlas_uv + rd * pcf_radius;
471            let clamped_uv = clamp(sample_uv, rect.xy, rect.zw);
472            let tap_depth = biased_depth
473                + clamp(dot(depth_grad, clamped_uv - atlas_uv), -0.005, 0.005);
474            shadow = shadow + textureSampleCompare(shadow_atlas_tex, shadow_atlas_sampler, clamped_uv, tap_depth);
475        }
476        return shadow / 32.0;
477    }
478}
479
480// PBR shading. Cook-Torrance specular with GGX NDF + Smith G + Schlick
481// Fresnel, Lambert diffuse weighted by (1 - metallic). Integrates against
482// every active scene light; IBL contribution is added when
483// `lights.ibl_enabled != 0`.
484fn viewport_pbr_shade(inp: PbrInputs) -> vec3<f32> {
485    let N = normalize(inp.world_n);
486    let V = normalize(inp.view_dir);
487    let roughness = max(inp.roughness, 0.04);
488    let alpha = roughness * roughness;
489    let alpha2 = alpha * alpha;
490    let f0 = mix(vec3<f32>(0.04), inp.albedo, inp.metallic);
491
492    // Hemisphere ambient (kept for parity with non-PBR pipelines when IBL
493    // is disabled).
494    let up_weight = clamp(N.z * 0.5 + 0.5, 0.0, 1.0);
495    let ambient = mix(lights.ground_colour, lights.sky_colour, up_weight)
496                  * lights.hemisphere_intensity * inp.albedo * inp.ao;
497
498    var lo = vec3<f32>(0.0);
499    let n_lights = lights.count;
500    for (var i: u32 = 0u; i < n_lights; i = i + 1u) {
501        let l = lights_storage[i];
502        var L: vec3<f32>;
503        var radiance: vec3<f32>;
504        if l.light_type == 0u {
505            L = normalize(l.pos_or_dir);
506            radiance = l.colour * l.intensity;
507        } else if l.light_type == 1u {
508            let to_light = l.pos_or_dir - inp.world_pos;
509            let dist = length(to_light);
510            L = to_light / max(dist, 0.0001);
511            let falloff = clamp(1.0 - dist / l.range, 0.0, 1.0);
512            radiance = l.colour * l.intensity * falloff * falloff;
513        } else {
514            let to_light = l.pos_or_dir - inp.world_pos;
515            let dist = length(to_light);
516            L = to_light / max(dist, 0.0001);
517            let dist_falloff = clamp(1.0 - dist / l.range, 0.0, 1.0);
518            let spot_dir = normalize(l.spot_direction);
519            let cos_angle = dot(-L, spot_dir);
520            let cos_outer = cos(l.outer_angle);
521            let cos_inner = cos(l.inner_angle);
522            let cone_att = clamp(
523                (cos_angle - cos_outer) / max(cos_inner - cos_outer, 0.0001),
524                0.0, 1.0,
525            );
526            radiance = l.colour * l.intensity * dist_falloff * dist_falloff * cone_att;
527        }
528
529        let H = normalize(V + L);
530        let n_dot_l = max(dot(N, L), 0.0);
531        let n_dot_v = max(dot(N, V), 0.0001);
532        let n_dot_h = max(dot(N, H), 0.0);
533        let v_dot_h = max(dot(V, H), 0.0);
534
535        let denom = n_dot_h * n_dot_h * (alpha2 - 1.0) + 1.0;
536        let D = alpha2 / max(3.14159265 * denom * denom, 1e-6);
537        let k = (roughness + 1.0) * (roughness + 1.0) * 0.125;
538        let G1v = n_dot_v / (n_dot_v * (1.0 - k) + k);
539        let G1l = n_dot_l / max(n_dot_l * (1.0 - k) + k, 1e-6);
540        let G = G1v * G1l;
541        let F = f0 + (vec3<f32>(1.0) - f0) * pow(1.0 - v_dot_h, 5.0);
542        let spec = (D * G) * F / max(4.0 * n_dot_v * n_dot_l, 1e-6);
543
544        let kd = (vec3<f32>(1.0) - F) * (1.0 - inp.metallic);
545        let diff = kd * inp.albedo / 3.14159265;
546        var shadow_factor = 1.0;
547        if i == 0u {
548            shadow_factor = viewport_sample_csm(inp.world_pos, N);
549        }
550        lo = lo + (diff + spec) * radiance * n_dot_l * shadow_factor;
551    }
552
553    return ambient + lo + inp.emissive;
554}
555"#;
556
557/// Fragment-output struct and packing helper for the OIT pass.
558///
559/// A transparent plugin fragment shader returns [`OitOutput`] from its
560/// `fs_main`. Use `viewport_oit_pack(color_premul, alpha, view_z)` to
561/// build the struct; the weight function matches the lib's built-in OIT
562/// pipelines so plugin transparents composite consistently with native
563/// transparents in the same pass.
564pub const SHARED_OIT_WGSL: &str = r#"
565// @viewport-wgsl-version: 1
566// OIT MRT output struct and pack helper. Requires SHARED_BINDINGS_WGSL.
567//
568// Use as:
569//   @fragment
570//   fn fs_main(...) -> OitOutput {
571//       return viewport_oit_pack(color_rgb, alpha, in.view_z);
572//   }
573//
574// `view_z` is the view-space Z coordinate (negative in front of the
575// camera). The weight function biases nearer fragments toward higher
576// contribution, matching the weight curve in mesh_oit.wgsl.
577
578struct OitOutput {
579    @location(0) accum:  vec4<f32>,
580    @location(1) reveal: f32,
581};
582
583fn viewport_oit_weight(view_z: f32, alpha: f32) -> f32 {
584    // Weight curve from McGuire & Bavoil 2013, equation 7. Tuned for the
585    // lib's typical scene depth range.
586    let z = abs(view_z);
587    let w = alpha * clamp(10.0 / (1e-5 + pow(z / 5.0, 2.0) + pow(z / 200.0, 6.0)), 1e-2, 3e3);
588    return w;
589}
590
591fn viewport_oit_pack(color: vec3<f32>, alpha: f32, view_z: f32) -> OitOutput {
592    let w = viewport_oit_weight(view_z, alpha);
593    var out: OitOutput;
594    out.accum  = vec4<f32>(color * alpha * w, alpha * w);
595    out.reveal = alpha;
596    return out;
597}
598"#;
599
600/// Fragment helper for the outline mask pass.
601///
602/// A plugin's mask pipeline reuses its scene-pass vertex stage and uses
603/// `fs_mask` (or any function returning `@location(0) f32 = 1.0`). The
604/// composite reads any non-zero value as "this pixel belongs to a selected
605/// item." Depth state must match the mask pass: depth test on, depth write
606/// off.
607pub const SHARED_MASK_WGSL: &str = r#"
608// @viewport-wgsl-version: 1
609// Outline-mask fragment helper. Returns a single R8 value of 1.0 for any
610// covered pixel; the composite reads the mask and draws the outline edge.
611
612@fragment
613fn viewport_mask_fs() -> @location(0) f32 {
614    return 1.0;
615}
616"#;
617
618/// Fragment helper for the pick-id pass.
619///
620/// A plugin's pick pipeline reuses its scene-pass vertex stage (extended to
621/// pass a flat-interpolated `pick_id: u32`) and uses `fs_pick`. The
622/// renderer reads back the R32U pixel under the cursor to resolve which
623/// item was clicked.
624pub const SHARED_PICK_WGSL: &str = r#"
625// @viewport-wgsl-version: 1
626// Pick-id fragment helper. The vertex stage must provide a flat-interpolated
627// pick_id at @location(0) of the fragment input; see your pipeline's vertex
628// shader for the matching declaration.
629
630@fragment
631fn viewport_pick_fs(
632    @location(0) @interpolate(flat) pick_id: u32,
633) -> @location(0) u32 {
634    return pick_id;
635}
636"#;