Skip to main content

strata_render/
gpu_wgpu.rs

1//! Hardware-accelerated `wgpu` 3D renderer with double-single RTE precision and
2//! single-draw-call programmable vertex pulling for planetary/terrain tile pyramids.
3
4use crate::scene3d::{
5    Background3D, Camera3D, Geometry3D, Light3D, Material3D, Mesh3D, RetainedCameraUniforms,
6    RetainedDynamicMesh, RetainedEnvironmentAssets, RetainedOceanSurface,
7    RetainedParticleBillboard, RetainedParticleLayer, RetainedParticleSprite, RetainedStar,
8    RetainedTerrainFrame, RetainedTileMesh, RetainedTileTexture, RteTileVertex, Scene3D, TileKeyId,
9};
10use bytemuck::{Pod, Zeroable};
11use std::collections::{BTreeMap, HashMap, HashSet};
12use std::sync::Arc;
13
14#[inline]
15fn gpu_perf_logging_enabled() -> bool {
16    static PERF_ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
17    *PERF_ENABLED.get_or_init(|| std::env::var_os("STRATA_PERF_LOG").is_some())
18}
19
20/// Default maximum new tile textures uploaded to the GPU atlas per frame during continuous flight.
21pub const DEFAULT_TEXTURE_UPLOAD_BUDGET: usize = 512;
22/// Default maximum new tile meshes copied to the GPU storage slab per frame.
23pub const DEFAULT_MESH_UPLOAD_BUDGET: usize = 512;
24/// Standard terrain imagery tile dimension in the GPU `Texture2DArray` atlas.
25pub const ATLAS_TILE_SIZE: u32 = 256;
26/// Maximum imagery layers pre-allocated in the GPU `Texture2DArray` atlas.
27pub const MAX_ATLAS_LAYERS: u32 = 1024;
28
29/// Splits a 64-bit float into `(hi, lo)` 32-bit floats for GPU double-single emulation.
30#[inline]
31pub fn split_f64_to_f32(v: f64) -> (f32, f32) {
32    let hi = v as f32;
33    let lo = (v - hi as f64) as f32;
34    (hi, lo)
35}
36
37fn transpose_mat4(m: [[f32; 4]; 4]) -> [[f32; 4]; 4] {
38    [
39        [m[0][0], m[1][0], m[2][0], m[3][0]],
40        [m[0][1], m[1][1], m[2][1], m[3][1]],
41        [m[0][2], m[1][2], m[2][2], m[3][2]],
42        [m[0][3], m[1][3], m[2][3], m[3][3]],
43    ]
44}
45
46fn invert_mat4(m: [[f32; 4]; 4]) -> [[f32; 4]; 4] {
47    let a = [
48        m[0][0] as f64,
49        m[0][1] as f64,
50        m[0][2] as f64,
51        m[0][3] as f64,
52        m[1][0] as f64,
53        m[1][1] as f64,
54        m[1][2] as f64,
55        m[1][3] as f64,
56        m[2][0] as f64,
57        m[2][1] as f64,
58        m[2][2] as f64,
59        m[2][3] as f64,
60        m[3][0] as f64,
61        m[3][1] as f64,
62        m[3][2] as f64,
63        m[3][3] as f64,
64    ];
65    let mut inv = [0.0f64; 16];
66    inv[0] = a[5] * a[10] * a[15] - a[5] * a[11] * a[14] - a[9] * a[6] * a[15]
67        + a[9] * a[7] * a[14]
68        + a[13] * a[6] * a[11]
69        - a[13] * a[7] * a[10];
70    inv[4] = -a[4] * a[10] * a[15] + a[4] * a[11] * a[14] + a[8] * a[6] * a[15]
71        - a[8] * a[7] * a[14]
72        - a[12] * a[6] * a[11]
73        + a[12] * a[7] * a[10];
74    inv[8] = a[4] * a[9] * a[15] - a[4] * a[11] * a[13] - a[8] * a[5] * a[15]
75        + a[8] * a[7] * a[13]
76        + a[12] * a[5] * a[11]
77        - a[12] * a[7] * a[9];
78    inv[12] = -a[4] * a[9] * a[14] + a[4] * a[10] * a[13] + a[8] * a[5] * a[14]
79        - a[8] * a[6] * a[13]
80        - a[12] * a[5] * a[10]
81        + a[12] * a[6] * a[9];
82    inv[1] = -a[1] * a[10] * a[15] + a[1] * a[11] * a[14] + a[9] * a[2] * a[15]
83        - a[9] * a[3] * a[14]
84        - a[13] * a[2] * a[11]
85        + a[13] * a[3] * a[10];
86    inv[5] = a[0] * a[10] * a[15] - a[0] * a[11] * a[14] - a[8] * a[2] * a[15]
87        + a[8] * a[3] * a[14]
88        + a[12] * a[2] * a[11]
89        - a[12] * a[3] * a[10];
90    inv[9] = -a[0] * a[9] * a[15] + a[0] * a[11] * a[13] + a[8] * a[1] * a[15]
91        - a[8] * a[3] * a[13]
92        - a[12] * a[1] * a[11]
93        + a[12] * a[3] * a[9];
94    inv[13] = a[0] * a[9] * a[14] - a[0] * a[10] * a[13] - a[8] * a[1] * a[14]
95        + a[8] * a[2] * a[13]
96        + a[12] * a[1] * a[10]
97        - a[12] * a[2] * a[9];
98    inv[2] = a[1] * a[6] * a[15] - a[1] * a[7] * a[14] - a[5] * a[2] * a[15]
99        + a[5] * a[3] * a[14]
100        + a[13] * a[2] * a[7]
101        - a[13] * a[3] * a[6];
102    inv[6] = -a[0] * a[6] * a[15] + a[0] * a[7] * a[14] + a[4] * a[2] * a[15]
103        - a[4] * a[3] * a[14]
104        - a[12] * a[2] * a[7]
105        + a[12] * a[3] * a[6];
106    inv[10] = a[0] * a[5] * a[15] - a[0] * a[7] * a[13] - a[4] * a[1] * a[15]
107        + a[4] * a[3] * a[13]
108        + a[12] * a[1] * a[7]
109        - a[12] * a[3] * a[5];
110    inv[14] = -a[0] * a[5] * a[14] + a[0] * a[6] * a[13] + a[4] * a[1] * a[14]
111        - a[4] * a[2] * a[13]
112        - a[12] * a[1] * a[6]
113        + a[12] * a[2] * a[5];
114    inv[3] = -a[1] * a[6] * a[11] + a[1] * a[7] * a[10] + a[5] * a[2] * a[11]
115        - a[5] * a[3] * a[10]
116        - a[9] * a[2] * a[7]
117        + a[9] * a[3] * a[6];
118    inv[7] = a[0] * a[6] * a[11] - a[0] * a[7] * a[10] - a[4] * a[2] * a[11]
119        + a[4] * a[3] * a[10]
120        + a[8] * a[2] * a[7]
121        - a[8] * a[3] * a[6];
122    inv[11] = -a[0] * a[5] * a[11] + a[0] * a[7] * a[9] + a[4] * a[1] * a[11]
123        - a[4] * a[3] * a[9]
124        - a[8] * a[1] * a[7]
125        + a[8] * a[3] * a[5];
126    inv[15] = a[0] * a[5] * a[10] - a[0] * a[6] * a[9] - a[4] * a[1] * a[10]
127        + a[4] * a[2] * a[9]
128        + a[8] * a[1] * a[6]
129        - a[8] * a[2] * a[5];
130
131    let det = a[0] * inv[0] + a[1] * inv[4] + a[2] * inv[8] + a[3] * inv[12];
132    if det.abs() < 1e-24 {
133        return [
134            [1.0, 0.0, 0.0, 0.0],
135            [0.0, 1.0, 0.0, 0.0],
136            [0.0, 0.0, 1.0, 0.0],
137            [0.0, 0.0, 0.0, 1.0],
138        ];
139    }
140    let inv_det = 1.0 / det;
141    let mut out = [[0.0f32; 4]; 4];
142    for c in 0..4 {
143        for r in 0..4 {
144            out[c][r] = (inv[c * 4 + r] * inv_det) as f32;
145        }
146    }
147    out
148}
149
150#[repr(C)]
151#[derive(Clone, Copy, Pod, Zeroable)]
152struct GpuCameraUniforms {
153    view_proj_rte: [[f32; 4]; 4],
154    inv_view_proj_rte: [[f32; 4]; 4],
155    ecef_from_icrf: [[f32; 4]; 4],
156    icrf_from_ecef: [[f32; 4]; 4],
157    light_view_proj_rte: [[f32; 4]; 4],
158    eye_high: [f32; 4],
159    eye_low: [f32; 4],
160    sun_dir: [f32; 4],            // xyz = sun dir, w = sun_visible (0/1)
161    sun_color: [f32; 4],          // rgb = color, w = sun_angular_radius_rad
162    ambient_color: [f32; 4],      // rgb = ambient, w = stars_intensity (0 when off)
163    sky_top: [f32; 4],
164    sky_bottom: [f32; 4],
165    moon_dir: [f32; 4],           // xyz = moon dir, w = moon_visible (0/1)
166    env_params: [f32; 4],         // x = day_night_strength, y = city_lights_intensity, z = local_25d_blend, w = moon_angular_radius_rad
167    cloud_params: [f32; 4],       // x = cloud_layer_opacity, y = cloud_lon_offset_rad, z = time_s, w = space_sky_enabled (0/1)
168    viewport_wh: [f32; 4],        // x = w, y = h, z = skybox_intensity, w = local_cloud_opacity
169    atmo_25d_params: [f32; 4],    // x = realistic_25d_sky, y = night_stars_25d, z = terrain_25d_lighting, w = terrain_25d_shadows
170    weather_opt_params: [f32; 4], // x = weather_darkness, y = weather_cloud_cover, z = weather_haze, w = shadow_radius_m
171    cloud_tint_params: [f32; 4],  // xyz = cloud_tint_rgb, w = cloud_25d_cover_boost
172    view_flags: [f32; 4],         // x = map_2d_morph (0..1), yzw = reserved
173}
174
175fn dot3_f64(a: [f64; 3], b: [f64; 3]) -> f64 {
176    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
177}
178
179fn cross3_f64(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
180    [
181        a[1] * b[2] - a[2] * b[1],
182        a[2] * b[0] - a[0] * b[2],
183        a[0] * b[1] - a[1] * b[0],
184    ]
185}
186
187fn norm3_f64(a: [f64; 3], fallback: [f64; 3]) -> [f64; 3] {
188    let l = dot3_f64(a, a).sqrt();
189    if l > 1e-9 {
190        [a[0] / l, a[1] / l, a[2] / l]
191    } else {
192        fallback
193    }
194}
195
196/// Computes a texel-snapped RTE orthographic directional shadow matrix (`light_view_proj_rte`)
197/// framing visible mountains and 3D objects around the camera. Returns `(matrix, shadow_radius_m, active)`.
198fn compute_shadow_light_vp_rte(
199    cam: &RetainedCameraUniforms,
200    shadow_map_size: u32,
201) -> ([[f32; 4]; 4], f32, bool) {
202    let ident = [
203        [1.0, 0.0, 0.0, 0.0],
204        [0.0, 1.0, 0.0, 0.0],
205        [0.0, 0.0, 1.0, 0.0],
206        [0.0, 0.0, 0.0, 1.0],
207    ];
208    if cam.terrain_25d_shadows <= 0.001 || cam.local_25d_blend <= 0.02 {
209        return (ident, 0.0, false);
210    }
211
212    let sun = norm3_f64(
213        [cam.sun_dir[0] as f64, cam.sun_dir[1] as f64, cam.sun_dir[2] as f64],
214        [0.0, 0.0, 1.0],
215    );
216    let eye = cam.eye_ecef;
217    let eye_r = dot3_f64(eye, eye).sqrt();
218    let (eye_up, eye_alt, is_planet) = if eye_r > 1_000_000.0 {
219        (
220            [eye[0] / eye_r, eye[1] / eye_r, eye[2] / eye_r],
221            (eye_r - 6_378_137.0).max(30.0),
222            true,
223        )
224    } else {
225        ([0.0, 1.0, 0.0], eye[1].abs().max(eye_r * 0.5).max(15.0), false)
226    };
227
228    let sun_elev = dot3_f64(sun, eye_up);
229    if sun_elev <= 0.025 {
230        return (ident, 0.0, false);
231    }
232
233    // Clamp grazing light angle slightly when constructing the shadow ortho box so distant peaks still fit cleanly.
234    let radius = if is_planet {
235        (eye_alt * 3.8).clamp(380.0, 28_000.0)
236    } else {
237        (eye_alt * 3.0).clamp(40.0, 1_000.0)
238    };
239    let depth_half = (radius * 2.4).max(if is_planet { 14_000.0 } else { 200.0 });
240
241    // Camera forward vector in world space is `-row2(view_rot)` (column-major: row 2 = [view_rot[0][2], view_rot[1][2], view_rot[2][2]]).
242    let cam_fwd = norm3_f64(
243        [
244            -(cam.view_rot[0][2] as f64),
245            -(cam.view_rot[1][2] as f64),
246            -(cam.view_rot[2][2] as f64),
247        ],
248        [0.0, 0.0, -1.0],
249    );
250    let fwd_dot_up = dot3_f64(cam_fwd, eye_up);
251    let fwd_horiz = norm3_f64(
252        [
253            cam_fwd[0] - eye_up[0] * fwd_dot_up,
254            cam_fwd[1] - eye_up[1] * fwd_dot_up,
255            cam_fwd[2] - eye_up[2] * fwd_dot_up,
256        ],
257        [1.0, 0.0, 0.0],
258    );
259
260    // Center shadow frustum slightly ahead of camera and down toward ground relief.
261    let fwd_shift = radius * 0.36;
262    let down_shift = if is_planet {
263        eye_alt.min(radius * 0.65)
264    } else {
265        eye_alt * 0.5
266    };
267    let center_rel = [
268        fwd_horiz[0] * fwd_shift - eye_up[0] * down_shift,
269        fwd_horiz[1] * fwd_shift - eye_up[1] * down_shift,
270        fwd_horiz[2] * fwd_shift - eye_up[2] * down_shift,
271    ];
272
273    // Orthonormal light basis: l_right, l_up perpendicular to sun direction.
274    let ref_up = if dot3_f64(sun, eye_up).abs() > 0.96 {
275        fwd_horiz
276    } else {
277        eye_up
278    };
279    let l_right = norm3_f64(cross3_f64(ref_up, sun), [1.0, 0.0, 0.0]);
280    let l_up = norm3_f64(cross3_f64(sun, l_right), [0.0, 1.0, 0.0]);
281
282    // Snap world shadow center in light space to texel increments to prevent shimmer while panning.
283    let world_center = [
284        eye[0] + center_rel[0],
285        eye[1] + center_rel[1],
286        eye[2] + center_rel[2],
287    ];
288    let texel_size = (2.0 * radius) / (shadow_map_size.clamp(512, 4096) as f64);
289    let cx_l = (dot3_f64(world_center, l_right) / texel_size).floor() * texel_size;
290    let cy_l = (dot3_f64(world_center, l_up) / texel_size).floor() * texel_size;
291    let cz_l = dot3_f64(world_center, sun);
292
293    let eye_x_l = dot3_f64(eye, l_right);
294    let eye_y_l = dot3_f64(eye, l_up);
295    let eye_z_l = dot3_f64(eye, sun);
296
297    let dx = eye_x_l - cx_l;
298    let dy = eye_y_l - cy_l;
299    let dz = eye_z_l - cz_l;
300
301    // Map world_rel -> light NDC:
302    // ndc_x = (dot(world_rel, l_right) + dx) / radius
303    // ndc_y = (dot(world_rel, l_up) + dy) / radius
304    // ndc_z = 0.5 - (dot(world_rel, sun) + dz) / (2 * depth_half)  (closer to sun = smaller depth in [0, 1])
305    let sx = 1.0 / radius;
306    let sy = 1.0 / radius;
307    let sz = -0.5 / depth_half;
308
309    let mat = [
310        [
311            (l_right[0] * sx) as f32,
312            (l_up[0] * sy) as f32,
313            (sun[0] * sz) as f32,
314            0.0,
315        ],
316        [
317            (l_right[1] * sx) as f32,
318            (l_up[1] * sy) as f32,
319            (sun[1] * sz) as f32,
320            0.0,
321        ],
322        [
323            (l_right[2] * sx) as f32,
324            (l_up[2] * sy) as f32,
325            (sun[2] * sz) as f32,
326            0.0,
327        ],
328        [
329            (dx * sx) as f32,
330            (dy * sy) as f32,
331            (0.5 + dz * sz) as f32,
332            1.0,
333        ],
334    ];
335    (mat, radius as f32, true)
336}
337
338impl GpuCameraUniforms {
339    fn from_retained(
340        cam: &RetainedCameraUniforms,
341        viewport_w: f32,
342        viewport_h: f32,
343        light_view_proj_rte: [[f32; 4]; 4],
344        shadow_radius_m: f32,
345        shadows_active: bool,
346    ) -> Self {
347        let (ex_hi, ex_lo) = split_f64_to_f32(cam.eye_ecef[0]);
348        let (ey_hi, ey_lo) = split_f64_to_f32(cam.eye_ecef[1]);
349        let (ez_hi, ez_lo) = split_f64_to_f32(cam.eye_ecef[2]);
350        let (sky_top, sky_bottom) = match cam.background {
351            Background3D::Transparent => ([0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]),
352            Background3D::Solid(c) => {
353                let rgba = [c.r(), c.g(), c.b(), c.a()];
354                (rgba, rgba)
355            }
356            Background3D::VerticalGradient { top, bottom } => (
357                [top.r(), top.g(), top.b(), top.a()],
358                [bottom.r(), bottom.g(), bottom.b(), bottom.a()],
359            ),
360        };
361        let inv_vp = invert_mat4(cam.view_proj_rte);
362        let icrf_from_ecef = transpose_mat4(cam.ecef_from_icrf);
363        let space_sky = if cam.stars_visible
364            || cam.sun_visible
365            || cam.moon_visible
366            || cam.realistic_25d_sky > 0.001
367            || (cam.map_2d_morph > 0.001 && !matches!(cam.background, Background3D::Solid(_)))
368        {
369            1.0
370        } else if matches!(cam.background, Background3D::Solid(_)) {
371            2.0
372        } else {
373            0.0
374        };
375        let stars_eff = if cam.stars_visible {
376            cam.stars_intensity.max(0.0)
377        } else {
378            0.0
379        };
380        let shadow_strength = if shadows_active {
381            cam.terrain_25d_shadows.clamp(0.0, 1.0)
382        } else {
383            0.0
384        };
385        Self {
386            view_proj_rte: cam.view_proj_rte,
387            inv_view_proj_rte: inv_vp,
388            ecef_from_icrf: cam.ecef_from_icrf,
389            icrf_from_ecef,
390            light_view_proj_rte,
391            eye_high: [ex_hi, ey_hi, ez_hi, 0.0],
392            eye_low: [ex_lo, ey_lo, ez_lo, 0.0],
393            sun_dir: [
394                cam.sun_dir[0],
395                cam.sun_dir[1],
396                cam.sun_dir[2],
397                if cam.sun_visible { 1.0 } else { 0.0 },
398            ],
399            sun_color: [
400                cam.sun_color[0],
401                cam.sun_color[1],
402                cam.sun_color[2],
403                cam.sun_angular_radius_rad,
404            ],
405            ambient_color: [
406                cam.ambient_color[0],
407                cam.ambient_color[1],
408                cam.ambient_color[2],
409                stars_eff,
410            ],
411            sky_top,
412            sky_bottom,
413            moon_dir: [
414                cam.moon_dir[0],
415                cam.moon_dir[1],
416                cam.moon_dir[2],
417                if cam.moon_visible { 1.0 } else { 0.0 },
418            ],
419            env_params: [
420                cam.day_night_strength,
421                cam.city_lights_intensity,
422                cam.local_25d_blend,
423                cam.moon_angular_radius_rad,
424            ],
425            cloud_params: [
426                cam.cloud_layer_opacity,
427                cam.cloud_lon_offset_rad,
428                cam.time_s,
429                space_sky,
430            ],
431            viewport_wh: [
432                viewport_w.max(1.0),
433                viewport_h.max(1.0),
434                cam.skybox_intensity.max(0.0),
435                cam.local_cloud_opacity.max(0.0),
436            ],
437            atmo_25d_params: [
438                cam.realistic_25d_sky.clamp(0.0, 1.0),
439                cam.night_stars_25d.clamp(0.0, 1.0),
440                cam.terrain_25d_lighting.clamp(0.0, 1.0),
441                shadow_strength,
442            ],
443            weather_opt_params: [
444                cam.weather_darkness.clamp(0.0, 1.0),
445                cam.weather_cloud_cover.clamp(0.0, 1.0),
446                cam.weather_haze.clamp(0.0, 1.0),
447                shadow_radius_m.max(0.0),
448            ],
449            cloud_tint_params: [
450                cam.cloud_tint_rgb[0].clamp(0.0, 2.0),
451                cam.cloud_tint_rgb[1].clamp(0.0, 2.0),
452                cam.cloud_tint_rgb[2].clamp(0.0, 2.0),
453                cam.cloud_25d_cover_boost.clamp(0.0, 1.0),
454            ],
455            view_flags: [cam.map_2d_morph.clamp(0.0, 1.0), 0.0, 0.0, 0.0],
456        }
457    }
458}
459
460const OCEAN_WORLD_NOISE_PERIOD_M: f64 = 32_768.0;
461const OCEAN_OCTAVE_ANGS: [f64; 8] = [0.04, -0.26, 0.42, -0.58, 0.77, -0.86, 0.21, -0.41];
462const OCEAN_OCTAVE_WLS: [f64; 8] = [151.0, 97.0, 61.0, 38.0, 23.5, 13.7, 7.9, 4.3];
463const OCEAN_OCTAVE_PHASES: [f64; 8] = [0.37, 2.18, 4.91, 1.09, 3.64, 5.47, 2.71, 0.83];
464
465#[repr(C)]
466#[derive(Clone, Copy, Pod, Zeroable)]
467struct GpuOceanUniforms {
468    origin_high: [f32; 4],     // xyz = split high f32 of ocean origin_ecef, w = enabled (0/1)
469    origin_low: [f32; 4],      // xyz = split low f32 of ocean origin_ecef, w = alt_fade
470    basis_east: [f32; 4],      // xyz = local ENU east, w = wave_strength
471    basis_north: [f32; 4],     // xyz = local ENU north, w = wave_scale
472    basis_up: [f32; 4],        // xyz = local ENU up, w = glint_intensity
473    train_a: [f32; 4],         // x = dir_e, y = dir_n, z = wind_speed_mps, w = phase_time_s
474    train_b: [f32; 4],         // x = dir_e, y = dir_n, z = wind_speed_mps, w = phase_time_s
475    blend_params: [f32; 4],    // x = weight_a, y = weight_b, z = opacity, w = coastal_shoaling (0/1)
476    coastal_params: [f32; 4],  // x = shoaling_range_m, y = sdf_half_span_m, z = sdf_center_e, w = sdf_center_n
477    world_meta: [f32; 4],      // x = wx mod P, y = wy mod P, z = origin_lat_rad, w = east_scale_25d (<0 => disabled)
478    train_a_phases0: [f32; 4], // f64-reduced base phases for train_a octaves 0..4 in [0, TAU)
479    train_a_phases1: [f32; 4], // f64-reduced base phases for train_a octaves 4..8 in [0, TAU)
480    train_b_phases0: [f32; 4], // f64-reduced base phases for train_b octaves 0..4 in [0, TAU)
481    train_b_phases1: [f32; 4], // f64-reduced base phases for train_b octaves 4..8 in [0, TAU)
482}
483
484impl GpuOceanUniforms {
485    fn compute_train_base_phases(
486        dir_en: [f64; 2],
487        wind_speed_mps: f64,
488        phase_time_s: f64,
489        wave_scale: f64,
490        world_origin_merc_m: [f64; 2],
491    ) -> ([f32; 4], [f32; 4]) {
492        let len_wind = 0.48 + (1.72 - 0.48) * (wind_speed_mps / 18.0).clamp(0.0, 1.3);
493        let ws = wave_scale.max(0.15);
494        let perp0 = [-dir_en[1], dir_en[0]];
495        let wx = world_origin_merc_m[0];
496        let wy = world_origin_merc_m[1];
497        let mut p = [0.0f32; 8];
498        for i in 0..8 {
499            let wl = ((OCEAN_OCTAVE_WLS[i] * len_wind) / ws).max(1.4);
500            let k = std::f64::consts::TAU / wl;
501            let omega = (9.81 * k).sqrt();
502            let (sa, ca) = OCEAN_OCTAVE_ANGS[i].sin_cos();
503            let dx = dir_en[0] * ca + perp0[0] * sa;
504            let dy = dir_en[1] * ca + perp0[1] * sa;
505            let base = (dx * wx + dy * wy) * k - omega * phase_time_s + OCEAN_OCTAVE_PHASES[i];
506            p[i] = base.rem_euclid(std::f64::consts::TAU) as f32;
507        }
508        ([p[0], p[1], p[2], p[3]], [p[4], p[5], p[6], p[7]])
509    }
510
511    fn disabled() -> Self {
512        Self {
513            origin_high: [0.0; 4],
514            origin_low: [0.0; 4],
515            basis_east: [1.0, 0.0, 0.0, 0.0],
516            basis_north: [0.0, 1.0, 0.0, 1.0],
517            basis_up: [0.0, 0.0, 1.0, 1.0],
518            train_a: [1.0, 0.0, 8.0, 0.0],
519            train_b: [1.0, 0.0, 8.0, 0.0],
520            blend_params: [1.0, 0.0, 0.0, 0.0],
521            coastal_params: [360.0, 1_500.0, 0.0, 0.0],
522            world_meta: [0.0, 0.0, 0.0, -1.0],
523            train_a_phases0: [0.0; 4],
524            train_a_phases1: [0.0; 4],
525            train_b_phases0: [0.0; 4],
526            train_b_phases1: [0.0; 4],
527        }
528    }
529
530    fn from_retained(ocean: &RetainedOceanSurface, has_sdf_tex: bool) -> Self {
531        if !ocean.enabled || ocean.alt_fade <= 0.002 || ocean.opacity <= 0.002 {
532            return Self::disabled();
533        }
534        let (ox_hi, ox_lo) = split_f64_to_f32(ocean.origin_ecef[0]);
535        let (oy_hi, oy_lo) = split_f64_to_f32(ocean.origin_ecef[1]);
536        let (oz_hi, oz_lo) = split_f64_to_f32(ocean.origin_ecef[2]);
537        let norm2_f64 = |v: [f32; 2]| -> [f64; 2] {
538            let vx = v[0] as f64;
539            let vy = v[1] as f64;
540            let l = (vx * vx + vy * vy).sqrt();
541            if l > 1e-6 {
542                [vx / l, vy / l]
543            } else {
544                [1.0, 0.0]
545            }
546        };
547        let da64 = norm2_f64(ocean.train_a.dir_en);
548        let db64 = norm2_f64(ocean.train_b.dir_en);
549        let da = [da64[0] as f32, da64[1] as f32];
550        let db = [db64[0] as f32, db64[1] as f32];
551        let wave_scale = ocean.wave_scale.clamp(0.15, 6.0);
552        let speed_a = ocean.train_a.wind_speed_mps.clamp(0.2, 60.0);
553        let speed_b = ocean.train_b.wind_speed_mps.clamp(0.2, 60.0);
554
555        let has_world = ocean.world_origin_merc_m[0].abs() > 1e-3
556            || ocean.world_origin_merc_m[1].abs() > 1e-3
557            || ocean.origin_lat_rad.abs() > 1e-5
558            || ocean.origin_ecef.iter().any(|v| v.abs() > 100.0);
559        let wx_mod = ocean.world_origin_merc_m[0].rem_euclid(OCEAN_WORLD_NOISE_PERIOD_M) as f32;
560        let wy_mod = ocean.world_origin_merc_m[1].rem_euclid(OCEAN_WORLD_NOISE_PERIOD_M) as f32;
561        let east_scale_meta = if has_world {
562            ocean.east_scale.clamp(0.15, 1.0)
563        } else {
564            -1.0
565        };
566        let (ta_p0, ta_p1) = Self::compute_train_base_phases(
567            da64,
568            speed_a as f64,
569            ocean.train_a.phase_time_s as f64,
570            wave_scale as f64,
571            ocean.world_origin_merc_m,
572        );
573        let (tb_p0, tb_p1) = Self::compute_train_base_phases(
574            db64,
575            speed_b as f64,
576            ocean.train_b.phase_time_s as f64,
577            wave_scale as f64,
578            ocean.world_origin_merc_m,
579        );
580
581        Self {
582            origin_high: [ox_hi, oy_hi, oz_hi, 1.0],
583            origin_low: [ox_lo, oy_lo, oz_lo, ocean.alt_fade.clamp(0.0, 1.0)],
584            basis_east: [
585                ocean.basis_east[0],
586                ocean.basis_east[1],
587                ocean.basis_east[2],
588                ocean.wave_strength.clamp(0.0, 4.0),
589            ],
590            basis_north: [
591                ocean.basis_north[0],
592                ocean.basis_north[1],
593                ocean.basis_north[2],
594                wave_scale,
595            ],
596            basis_up: [
597                ocean.basis_up[0],
598                ocean.basis_up[1],
599                ocean.basis_up[2],
600                ocean.glint_intensity.clamp(0.0, 4.0),
601            ],
602            train_a: [da[0], da[1], speed_a, ocean.train_a.phase_time_s],
603            train_b: [db[0], db[1], speed_b, ocean.train_b.phase_time_s],
604            blend_params: [
605                ocean.train_a.weight.clamp(0.0, 1.0),
606                ocean.train_b.weight.clamp(0.0, 1.0),
607                ocean.opacity.clamp(0.0, 1.0),
608                if ocean.coastal_shoaling && has_sdf_tex {
609                    1.0
610                } else {
611                    0.0
612                },
613            ],
614            coastal_params: [
615                ocean.shoaling_range_m.max(20.0),
616                ocean.sdf_half_span_m.max(50.0),
617                ocean.sdf_center_en_m[0],
618                ocean.sdf_center_en_m[1],
619            ],
620            world_meta: [wx_mod, wy_mod, ocean.origin_lat_rad, east_scale_meta],
621            train_a_phases0: ta_p0,
622            train_a_phases1: ta_p1,
623            train_b_phases0: tb_p0,
624            train_b_phases1: tb_p1,
625        }
626    }
627}
628
629#[repr(C)]
630#[derive(Clone, Copy, Pod, Zeroable)]
631struct GpuStar {
632    icrf_dir_mag: [f32; 4], // xyz = J2000 ICRF unit dir, w = vmag
633    color: [f32; 4],        // rgba
634}
635
636#[repr(C)]
637#[derive(Clone, Copy, Pod, Zeroable)]
638struct GpuTileInstance {
639    center_high: [f32; 4],
640    center_low: [f32; 4],
641    uv_rect: [f32; 4],
642    night_uv_rect: [f32; 4],
643    tint: [f32; 4],
644    tile_meta: [u32; 4], // x = base_vertex, y = atlas_layer, z = unlit (0/1), w = night_atlas_layer
645}
646
647#[repr(C)]
648#[derive(Clone, Copy, Pod, Zeroable)]
649struct GpuDynamicUniforms {
650    anchor_high: [f32; 4],
651    anchor_low: [f32; 4],
652    color: [f32; 4],
653    dyn_meta: [u32; 4], // x = unlit, y = use_vertex_color, z = use_texture, w = atlas_layer
654}
655
656#[repr(C)]
657#[derive(Clone, Copy, Pod, Zeroable)]
658struct GpuGeoInstance {
659    anchor_high: [f32; 4], // xyz = split high f32 of anchor_ecef
660    anchor_low: [f32; 4],  // xyz = split low f32 of anchor_ecef
661    col0: [f32; 4],        // xyz = model col 0 (+X East -> world m), w = roughness
662    col1: [f32; 4],        // xyz = model col 1 (+Y North -> world m), w = metalness
663    col2: [f32; 4],        // xyz = model col 2 (+Z Up -> world m), w = unlit (1.0 or 0.0)
664    base_color: [f32; 4],  // rgba
665    emissive: [f32; 4],    // xyz = emissive rgb, w = accent_mix
666}
667
668#[repr(C)]
669#[derive(Clone, Copy, Pod, Zeroable)]
670struct GpuParticleLayerUniforms {
671    basis_east: [f32; 4],      // xyz = local ENU east, w = wrapped_phase.x
672    basis_north: [f32; 4],     // xyz = local ENU north, w = wrapped_phase.y
673    basis_up: [f32; 4],        // xyz = local ENU up, w = wrapped_phase.z
674    forward_bias: [f32; 4],    // xyz = world-space forward cone center offset, w = 0.0
675    cam_right_mpx: [f32; 4],   // xyz = camera right world vec, w = meters_per_px_at_1m
676    cam_up_pad: [f32; 4],      // xyz = camera up world vec, w = 0.0
677    altitude_bounds: [f32; 4], // x = eye_alt_msl, y = ground_alt_msl, z = ceiling_alt_msl, w = ceiling_fade_m
678    volume_params: [f32; 4],   // x = extent_xy, y = extent_z, z = edge_fade_frac, w = near_fade_m
679    motion_params: [f32; 4],   // x = fall_speed_mps, y = wind_e, z = wind_n, w = wrapped_time_s
680    size_params: [f32; 4],     // x = width_m, y = height_m, z = velocity_stretch, w = spin_rad_s
681    flutter_clamp: [f32; 4],   // x = flutter_amp_m, y = flutter_freq_hz, z = min_px, w = max_px
682    color: [f32; 4],           // rgba
683    meta: [u32; 4],            // x = sprite_mode, y = billboard_mode, z = seed, w = particle_count
684}
685
686/// Builds a shared triangle index buffer for a terrain grid `(grid_res x grid_res)` with optional skirts.
687pub fn build_terrain_grid_indices(grid_res: u32, has_skirts: bool) -> Vec<u32> {
688    let n = grid_res.max(2);
689    let cells = n - 1;
690    let skirt_quads = if has_skirts { cells * 4 } else { 0 };
691    let mut indices = Vec::with_capacity(((cells * cells + skirt_quads) * 6) as usize);
692
693    for r in 0..cells {
694        for c in 0..cells {
695            let i00 = r * n + c;
696            let i10 = i00 + 1;
697            let i01 = (r + 1) * n + c;
698            let i11 = i01 + 1;
699            indices.extend_from_slice(&[i00, i10, i11, i00, i11, i01]);
700        }
701    }
702
703    if has_skirts {
704        let base = n * n;
705        // South edge (row = 0, facing -North): s1 -> s0 -> k0 -> k1
706        for c in 0..cells {
707            let s0 = c;
708            let s1 = c + 1;
709            let k0 = base + c;
710            let k1 = base + c + 1;
711            indices.extend_from_slice(&[s1, s0, k0, s1, k0, k1]);
712        }
713        // East edge (col = n-1, facing +East): s1 -> s0 -> k0 -> k1
714        let r_base = base + n;
715        for r in 0..cells {
716            let s0 = r * n + (n - 1);
717            let s1 = (r + 1) * n + (n - 1);
718            let k0 = r_base + r;
719            let k1 = r_base + r + 1;
720            indices.extend_from_slice(&[s1, s0, k0, s1, k0, k1]);
721        }
722        // North edge (row = n-1, facing +North): s0 -> s1 -> k1 -> k0
723        let b_base = base + n * 2;
724        for c in 0..cells {
725            let s0 = (n - 1) * n + c;
726            let s1 = s0 + 1;
727            let k0 = b_base + c;
728            let k1 = b_base + c + 1;
729            indices.extend_from_slice(&[s0, s1, k1, s0, k1, k0]);
730        }
731        // West edge (col = 0, facing -East): s0 -> s1 -> k1 -> k0
732        let l_base = base + n * 3;
733        for r in 0..cells {
734            let s0 = r * n;
735            let s1 = (r + 1) * n;
736            let k0 = l_base + r;
737            let k1 = l_base + r + 1;
738            indices.extend_from_slice(&[s0, s1, k1, s0, k1, k0]);
739        }
740    }
741
742    indices
743}
744
745const SKY_WGSL: &str = r#"
746struct GpuCameraUniforms {
747    view_proj_rte: mat4x4<f32>,
748    inv_view_proj_rte: mat4x4<f32>,
749    ecef_from_icrf: mat4x4<f32>,
750    icrf_from_ecef: mat4x4<f32>,
751    light_view_proj_rte: mat4x4<f32>,
752    eye_high: vec4<f32>,
753    eye_low: vec4<f32>,
754    sun_dir: vec4<f32>,
755    sun_color: vec4<f32>,
756    ambient_color: vec4<f32>,
757    sky_top: vec4<f32>,
758    sky_bottom: vec4<f32>,
759    moon_dir: vec4<f32>,
760    env_params: vec4<f32>,
761    cloud_params: vec4<f32>,
762    viewport_wh: vec4<f32>,
763    atmo_25d_params: vec4<f32>,
764    weather_opt_params: vec4<f32>,
765    cloud_tint_params: vec4<f32>,
766    view_flags: vec4<f32>,
767}
768
769@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
770@group(0) @binding(1) var moon_tex: texture_2d<f32>;
771@group(0) @binding(2) var env_sampler: sampler;
772@group(0) @binding(3) var skybox_cube: texture_cube<f32>;
773
774struct SkyOut {
775    @builtin(position) pos: vec4<f32>,
776    @location(0) uv_y: f32,
777    @location(1) ndc: vec2<f32>,
778    @location(2) ray_dir: vec3<f32>,
779}
780
781@vertex
782fn vs_sky(@builtin(vertex_index) vid: u32) -> SkyOut {
783    var positions = array<vec2<f32>, 3>(
784        vec2<f32>(-1.0, -3.0),
785        vec2<f32>(3.0, 1.0),
786        vec2<f32>(-1.0, 1.0),
787    );
788    let p = positions[vid];
789    let p4 = cam.inv_view_proj_rte * vec4<f32>(p, 0.5, 1.0);
790    let w_safe = select(p4.w, select(-1e-6, 1e-6, p4.w >= 0.0), abs(p4.w) < 1e-6);
791    var out: SkyOut;
792    out.pos = vec4<f32>(p, 0.9999, 1.0);
793    out.uv_y = clamp((1.0 - p.y) * 0.5, 0.0, 1.0);
794    out.ndc = p;
795    out.ray_dir = p4.xyz / w_safe;
796    return out;
797}
798
799fn hash31(p: vec3<f32>) -> f32 {
800    let q = fract(p * 0.1031);
801    let r = q + vec3<f32>(dot(q, q.yzx + vec3<f32>(33.33)));
802    return fract((r.x + r.y) * r.z);
803}
804
805fn noise3(p: vec3<f32>) -> f32 {
806    let i = floor(p);
807    let f = fract(p);
808    let u = f * f * (vec3<f32>(3.0) - 2.0 * f);
809    let a = hash31(i);
810    let b = hash31(i + vec3<f32>(1.0, 0.0, 0.0));
811    let c = hash31(i + vec3<f32>(0.0, 1.0, 0.0));
812    let d = hash31(i + vec3<f32>(1.0, 1.0, 0.0));
813    let e = hash31(i + vec3<f32>(0.0, 0.0, 1.0));
814    let f1 = hash31(i + vec3<f32>(1.0, 0.0, 1.0));
815    let g = hash31(i + vec3<f32>(0.0, 1.0, 1.0));
816    let h = hash31(i + vec3<f32>(1.0, 1.0, 1.0));
817    return mix(
818        mix(mix(a, b, u.x), mix(c, d, u.x), u.y),
819        mix(mix(e, f1, u.x), mix(g, h, u.x), u.y),
820        u.z,
821    );
822}
823
824fn eval_physical_sky_25d(
825    rd: vec3<f32>,
826    eye_up: vec3<f32>,
827    horiz_sin: f32,
828    sun_dir: vec3<f32>,
829    weather_dark: f32,
830    cloud_cov: f32,
831    haze: f32,
832) -> vec3<f32> {
833    let mu = dot(rd, eye_up);
834    let elev = mu - horiz_sin;
835    let h_elev = clamp(max(elev, 0.0), 0.0, 1.0);
836    let sun_elev = dot(sun_dir, eye_up);
837
838    // Kasten-Young optical air mass approximation for solar transmittance & Rayleigh scattering.
839    let sun_deg = max(sun_elev * 57.29578, -2.0);
840    let m_sun = 1.0 / (max(sun_elev, 0.008) + 0.15 * pow(max(sun_deg + 3.885, 0.45), -1.253));
841    let sun_trans = exp(-vec3<f32>(0.085, 0.195, 0.46) * clamp(m_sun * 0.48, 0.0, 18.0));
842
843    let day_t = smoothstep(-0.08, 0.24, sun_elev);
844    let twilight_t = smoothstep(-0.22, -0.02, sun_elev) * (1.0 - smoothstep(0.02, 0.22, sun_elev));
845    let golden_t = exp(-pow((sun_elev - 0.03) * 7.8, 2.0));
846
847    // Noon zenith/mid/horizon -> Golden sunset/sunrise -> Twilight -> Deep midnight indigo.
848    let noon_zenith = vec3<f32>(0.08, 0.23, 0.56);
849    let noon_mid = vec3<f32>(0.24, 0.50, 0.86);
850    let noon_horiz = vec3<f32>(0.72, 0.85, 0.96);
851
852    let sunset_zenith = vec3<f32>(0.09, 0.13, 0.30);
853    let sunset_mid = vec3<f32>(0.36, 0.26, 0.36);
854    let sunset_horiz = vec3<f32>(0.96, 0.48, 0.19);
855
856    let night_zenith = vec3<f32>(0.006, 0.011, 0.026);
857    let night_mid = vec3<f32>(0.012, 0.020, 0.044);
858    let night_horiz = vec3<f32>(0.024, 0.038, 0.068);
859
860    let day_zen = mix(sunset_zenith, noon_zenith, smoothstep(0.02, 0.35, sun_elev));
861    let day_mid_c = mix(sunset_mid, noon_mid, smoothstep(0.02, 0.35, sun_elev));
862    let day_hor = mix(sunset_horiz, noon_horiz, smoothstep(0.02, 0.32, sun_elev));
863
864    let zenith_c = mix(night_zenith, day_zen, day_t) + vec3<f32>(0.03, 0.04, 0.09) * twilight_t;
865    let mid_c = mix(night_mid, day_mid_c, day_t) + vec3<f32>(0.10, 0.07, 0.12) * twilight_t;
866    let horiz_c = mix(night_horiz, day_hor, day_t) + vec3<f32>(0.34, 0.16, 0.10) * twilight_t;
867
868    let zenith_t = pow(clamp(h_elev * 1.85, 0.0, 1.0), 0.58);
869    let dome = mix(mid_c, zenith_c, zenith_t);
870    let optical_haze = exp(-h_elev * mix(10.0, 5.2, clamp(haze * 0.7 + weather_dark * 0.4, 0.0, 1.0)));
871
872    // Henyey-Greenstein forward Mie scattering around the sun direction.
873    let cos_theta = clamp(dot(rd, sun_dir), -1.0, 1.0);
874    let g_mie = 0.76;
875    let hg = (1.0 - g_mie * g_mie) / pow(max(1.0 + g_mie * g_mie - 2.0 * g_mie * cos_theta, 0.04), 1.5);
876    let sun_above = smoothstep(-0.08, 0.06, sun_elev);
877    let cloud_atten = 1.0 - clamp(weather_dark * 0.78 + cloud_cov * 0.35, 0.0, 0.92);
878    let mie_glow = (vec3<f32>(0.98, 0.84, 0.62) * sun_trans + vec3<f32>(0.55, 0.24, 0.06) * golden_t)
879        * clamp(hg * 0.048, 0.0, 1.35)
880        * sun_above
881        * cloud_atten
882        * (0.35 + 0.65 * exp(-h_elev * 2.2));
883
884    // Anti-solar / azimuth sunset band along the horizon toward the sun.
885    let sun_az_glow = pow(max(cos_theta, 0.0), 3.0) * (golden_t * 0.75 + twilight_t * 0.55)
886        * exp(-h_elev * 4.5) * cloud_atten;
887    let sunset_band = vec3<f32>(1.0, 0.46, 0.16) * sun_az_glow * 0.65;
888
889    var sky = mix(dome, horiz_c, clamp(optical_haze * 0.92, 0.0, 1.0)) + mie_glow + sunset_band;
890
891    // Weather / overcast cloud darkening & slate desaturation.
892    let storm_w = clamp(weather_dark * 0.82 + cloud_cov * 0.22, 0.0, 0.92);
893    if (storm_w > 0.002) {
894        let luma = dot(sky, vec3<f32>(0.299, 0.587, 0.114));
895        let overcast_day = mix(vec3<f32>(0.20, 0.24, 0.29), vec3<f32>(0.42, 0.47, 0.54), optical_haze);
896        let overcast_night = vec3<f32>(0.015, 0.020, 0.030);
897        let overcast_col = mix(overcast_night, overcast_day, clamp(day_t + twilight_t * 0.35, 0.0, 1.0));
898        let desaturated = mix(sky, vec3<f32>(luma) * vec3<f32>(0.88, 0.94, 1.02), storm_w * 0.65);
899        sky = mix(desaturated, overcast_col, storm_w * 0.68);
900    }
901
902    let below_t = smoothstep(0.0, 0.06, -elev);
903    let ground_mist = mix(
904        mix(night_horiz, horiz_c * 0.88, clamp(day_t + twilight_t * 0.5, 0.0, 1.0)),
905        vec3<f32>(0.26, 0.30, 0.36) * max(day_t, 0.08),
906        storm_w * 0.70,
907    );
908    return mix(sky, ground_mist, below_t);
909}
910
911@fragment
912fn fs_sky(in: SkyOut) -> @location(0) vec4<f32> {
913    let rd = normalize(in.ray_dir);
914    let rd_icrf = normalize((cam.icrf_from_ecef * vec4<f32>(rd, 0.0)).xyz);
915    // Derivatives must remain in uniform control flow for WGSL validation.
916    let dx_icrf = dpdx(rd_icrf);
917    let dy_icrf = dpdy(rd_icrf);
918    if (cam.cloud_params.w > 1.5) {
919        return cam.sky_top;
920    }
921
922    let space_t = 1.0 - smoothstep(0.0, 0.85, cam.env_params.z);
923    let map_2d = clamp(cam.view_flags.x, 0.0, 1.0);
924    let morph_clear = 1.0 - smoothstep(0.0, 0.85, map_2d);
925    let sun_dir = normalize(cam.sun_dir.xyz);
926    let real_sky_w = clamp(cam.atmo_25d_params.x, 0.0, 1.0);
927    let night_star_w = clamp(cam.atmo_25d_params.y, 0.0, 1.0);
928    let weather_dark = clamp(cam.weather_opt_params.x, 0.0, 1.0);
929    let cloud_cov = clamp(cam.weather_opt_params.y, 0.0, 1.0);
930    let weather_haze = clamp(cam.weather_opt_params.z, 0.0, 1.0);
931
932    let eye_pos = cam.eye_high.xyz + cam.eye_low.xyz;
933    let eye_r = length(eye_pos);
934    let eye_up = select(vec3<f32>(0.0, 1.0, 0.0), eye_pos / max(eye_r, 1.0), eye_r > 1000000.0);
935    let r_earth = 6378137.0;
936    let horiz_sin = select(
937        0.0,
938        -sqrt(max(eye_r * eye_r - r_earth * r_earth, 0.0)) / max(eye_r, r_earth),
939        eye_r > 1000000.0,
940    );
941    let elev = dot(rd, eye_up) - horiz_sin;
942    let sun_elev = dot(sun_dir, eye_up);
943
944    var atmo_sky = vec3<f32>(0.0);
945    if (cam.cloud_params.w < 0.5 || space_t < 0.999) {
946        let sky_grad_2d = mix(cam.sky_top, cam.sky_bottom, clamp(in.uv_y, 0.0, 1.0));
947        var classic_sky = sky_grad_2d.rgb;
948        if (eye_r > 1000000.0) {
949            let h_elev = clamp(max(elev, 0.0), 0.0, 1.0);
950            let day_scale = clamp(max(cam.sky_bottom.b, max(cam.sky_bottom.r, cam.sky_bottom.g)), 0.0, 1.0);
951            let zenith_col = vec3<f32>(0.10, 0.25, 0.55) * day_scale;
952            let mid_col = vec3<f32>(0.27, 0.53, 0.86) * day_scale;
953            let horizon_mist = vec3<f32>(0.75, 0.86, 0.96) * day_scale;
954
955            let zenith_t = pow(clamp(h_elev * 1.85, 0.0, 1.0), 0.58);
956            let base_dome = mix(mid_col, zenith_col, zenith_t);
957            let optical_haze = exp(-h_elev * 10.5);
958            let mie_sun = pow(max(dot(rd, sun_dir), 0.0), 5.0) * (1.0 - smoothstep(0.0, 0.45, h_elev));
959            let warm_mist = horizon_mist + vec3<f32>(0.12, 0.09, 0.04) * mie_sun * day_scale;
960            let above_sky = mix(base_dome, warm_mist, clamp(optical_haze * 0.90, 0.0, 1.0));
961            let below_t = smoothstep(0.0, 0.06, -elev);
962            let ground_mist = vec3<f32>(0.64, 0.77, 0.90) * day_scale;
963            classic_sky = mix(above_sky, ground_mist, below_t);
964        }
965        // Subtle weather darkening even in classic mode if base weather API explicitly supplies storm_darkness.
966        if (weather_dark > 0.002 && real_sky_w < 0.999) {
967            let classic_storm = vec3<f32>(0.24, 0.29, 0.36);
968            classic_sky = mix(classic_sky, classic_storm, weather_dark * 0.62);
969        }
970        if (real_sky_w > 0.001) {
971            let phys_sky = eval_physical_sky_25d(rd, eye_up, horiz_sin, sun_dir, weather_dark, cloud_cov, weather_haze);
972            atmo_sky = mix(classic_sky, phys_sky, real_sky_w);
973        } else {
974            atmo_sky = classic_sky;
975        }
976        atmo_sky = mix(sky_grad_2d.rgb, atmo_sky, morph_clear);
977        if (cam.cloud_params.w < 0.5 && map_2d <= 0.001) {
978            return vec4<f32>(atmo_sky, sky_grad_2d.a);
979        }
980    }
981
982    // Effective skybox visibility: full in orbital space, plus smooth night-sky emergence in 2.5D when synced!
983    let sky_clear_factor = 1.0 - clamp(cloud_cov * 0.85 + weather_dark * 0.55, 0.0, 0.98);
984    let night_sun_t = 1.0 - smoothstep(-0.14, 0.04, sun_elev);
985    let night_vis_25d = night_sun_t
986        * night_star_w
987        * sky_clear_factor
988        * smoothstep(-0.005, 0.08, elev);
989    let skybox_vis = max(space_t, night_vis_25d * (1.0 - space_t)) * morph_clear;
990
991    // 1. Pitch-black deep space + J2000 ICRF telescope skybox cubemap (or procedural Milky Way fallback)
992    var space_col = vec3<f32>(0.0);
993    if (cam.ambient_color.w > 0.001 && skybox_vis > 0.001) {
994        let cube_dim = max(f32(textureDimensions(skybox_cube, 0).x), 1.0);
995        let texel_sq = (cube_dim * cube_dim * 0.25) * max(dot(dx_icrf, dx_icrf), dot(dy_icrf, dy_icrf));
996        let sky_lod = max(0.5 * log2(max(texel_sq, 1.0)), 0.0);
997        let cube_s = textureSampleLevel(skybox_cube, env_sampler, rd_icrf, sky_lod);
998        let sky_gain = cam.viewport_wh.z;
999        if (cube_s.a > 0.01 && sky_gain > 0.001) {
1000            space_col += cube_s.rgb * sky_gain * skybox_vis;
1001        } else {
1002            let gnp = vec3<f32>(-0.867666, -0.198076, 0.455984);
1003            let sin_b = dot(rd_icrf, gnp);
1004            if (abs(sin_b) < 0.35) {
1005                let gc = vec3<f32>(-0.054876, -0.873437, -0.483835);
1006                let core_w = 0.35 + 0.65 * max(dot(rd_icrf, gc), 0.0);
1007                let dust_n = noise3(rd_icrf * 7.5) * 0.65 + noise3(rd_icrf * 17.0) * 0.35;
1008                let rift = smoothstep(0.015, 0.14, abs(sin_b) + (dust_n - 0.5) * 0.09);
1009                let mw = exp(-pow(abs(sin_b) * 8.0, 1.5)) * core_w * (0.45 + 0.55 * dust_n) * mix(0.45, 1.0, rift);
1010                space_col += vec3<f32>(0.075, 0.095, 0.165) * mw * min(cam.ambient_color.w, 1.8) * skybox_vis;
1011            }
1012        }
1013    }
1014
1015    // Blend pitch-black space to 3D horizon-anchored atmospheric sky when morphing down into 2.5D,
1016    // keeping night Milky Way cubemap cleanly additive over the dark 2.5D night sky!
1017    var col = space_col;
1018    if (space_t < 0.999) {
1019        col = mix(atmo_sky + space_col * 1.15, space_col, space_t);
1020    }
1021
1022    // 2. Realistic Sun (photosphere limb darkening + solar corona + atmospheric aureole in 2.5D)
1023    if (cam.sun_dir.w > 0.5) {
1024        let sun_cos = clamp(dot(rd, sun_dir), -1.0, 1.0);
1025        if (sun_cos > 0.80) {
1026            let sun_ang = acos(sun_cos);
1027            let r_sun = max(cam.sun_color.w, 0.004);
1028            let above_horiz = mix(smoothstep(-0.025, 0.015, elev), 1.0, space_t);
1029            let atmo_sun_atten = mix(1.0 - clamp(weather_dark * 0.82 + cloud_cov * 0.45, 0.0, 0.95), 1.0, space_t);
1030            let sunset_warm = mix(
1031                mix(vec3<f32>(1.0, 0.56, 0.24), vec3<f32>(1.0, 0.98, 0.92), smoothstep(-0.02, 0.28, sun_elev)),
1032                vec3<f32>(1.0, 0.98, 0.95),
1033                space_t,
1034            );
1035            let sun_vis = above_horiz * atmo_sun_atten;
1036            if (sun_vis > 0.002) {
1037                if (sun_ang < r_sun * 1.08) {
1038                    let mu_s = sqrt(max(1.0 - (sun_ang / r_sun) * (sun_ang / r_sun), 0.0));
1039                    let aa = (1.0 - smoothstep(r_sun * 0.94, r_sun * 1.06, sun_ang)) * sun_vis;
1040                    let limb = mix(0.48, 1.0, pow(mu_s, 0.45));
1041                    col = mix(col, cam.sun_color.rgb * sunset_warm * (3.6 * limb), aa);
1042                }
1043                let corona = exp(-sun_ang / (r_sun * 2.4)) * 0.85 + exp(-sun_ang / (r_sun * 12.0)) * 0.14;
1044                col += cam.sun_color.rgb * sunset_warm * corona * mix(0.62, 1.0, space_t) * sun_vis;
1045            }
1046        }
1047    }
1048
1049    // 3. Realistic Moon (NASA LRO albedo + Lommel-Seeliger phase from Sun vector + Earthshine)
1050    if (cam.moon_dir.w > 0.5) {
1051        let m_dir = normalize(cam.moon_dir.xyz);
1052        let b_cos = dot(rd, m_dir);
1053        let r_moon = max(cam.env_params.w, 0.004);
1054        let above_horiz_m = mix(smoothstep(-0.02, 0.02, elev), 1.0, space_t);
1055        if (above_horiz_m > 0.005 && b_cos > 1.0 - 0.501 * r_moon * r_moon) {
1056            let sin_r = sin(r_moon);
1057            let r2 = sin_r * sin_r;
1058            let d2 = max(1.0 - b_cos * b_cos, 0.0);
1059            if (d2 < r2) {
1060                let z_m = sqrt(max(r2 - d2, 0.0));
1061                let n_perp = rd - m_dir * b_cos;
1062                let n_moon = normalize(n_perp / sin_r - m_dir * (z_m / sin_r));
1063
1064                let up_icrf = normalize((cam.ecef_from_icrf * vec4<f32>(0.0, 0.0, 1.0, 0.0)).xyz);
1065                let ref_up = select(vec3<f32>(0.0, 1.0, 0.0), up_icrf, abs(dot(up_icrf, m_dir)) < 0.98);
1066                let m_right = normalize(cross(m_dir, ref_up));
1067                let m_up = normalize(cross(m_right, m_dir));
1068                let lx = dot(n_moon, m_right);
1069                let ly = dot(n_moon, m_up);
1070                let lz = dot(n_moon, -m_dir);
1071                let u = atan2(lx, lz) / 6.28318530718 + 0.5;
1072                let v = clamp(0.5 - asin(clamp(ly, -1.0, 1.0)) / 3.14159265359, 0.001, 0.999);
1073                let albedo = textureSampleLevel(moon_tex, env_sampler, vec2<f32>(u, v), 0.0).rgb;
1074
1075                let ndotl_m = max(dot(n_moon, sun_dir), 0.0);
1076                let ndotv_m = max(dot(n_moon, -rd), 0.02);
1077                let lommel = ndotl_m / (ndotl_m + 0.36 * ndotv_m + 0.06);
1078                let earthshine = vec3<f32>(0.024, 0.032, 0.048);
1079                let lit_moon = albedo * (cam.sun_color.rgb * lommel * 1.45 + earthshine);
1080                let aa_m = (1.0 - smoothstep(r2 * 0.90, r2, d2)) * above_horiz_m;
1081                let moon_night_t = 1.0 - smoothstep(-0.10, 0.10, sun_elev);
1082                let moon_25d_vis = mix(0.32, 0.98, moon_night_t) * sky_clear_factor;
1083                col = mix(col, max(col, lit_moon), aa_m * mix(moon_25d_vis, 1.0, space_t));
1084            }
1085        }
1086    }
1087
1088    return vec4<f32>(col, 1.0);
1089}
1090"#;
1091
1092const STARS_WGSL: &str = r#"
1093struct GpuCameraUniforms {
1094    view_proj_rte: mat4x4<f32>,
1095    inv_view_proj_rte: mat4x4<f32>,
1096    ecef_from_icrf: mat4x4<f32>,
1097    icrf_from_ecef: mat4x4<f32>,
1098    light_view_proj_rte: mat4x4<f32>,
1099    eye_high: vec4<f32>,
1100    eye_low: vec4<f32>,
1101    sun_dir: vec4<f32>,
1102    sun_color: vec4<f32>,
1103    ambient_color: vec4<f32>,
1104    sky_top: vec4<f32>,
1105    sky_bottom: vec4<f32>,
1106    moon_dir: vec4<f32>,
1107    env_params: vec4<f32>,
1108    cloud_params: vec4<f32>,
1109    viewport_wh: vec4<f32>,
1110    atmo_25d_params: vec4<f32>,
1111    weather_opt_params: vec4<f32>,
1112    cloud_tint_params: vec4<f32>,
1113    view_flags: vec4<f32>,
1114}
1115
1116struct GpuStar {
1117    icrf_dir_mag: vec4<f32>,
1118    color: vec4<f32>,
1119}
1120
1121@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
1122@group(0) @binding(1) var<storage, read> stars: array<GpuStar>;
1123
1124struct StarVsOut {
1125    @builtin(position) clip_pos: vec4<f32>,
1126    @location(0) local_uv: vec2<f32>,
1127    @location(1) color_flux: vec4<f32>,
1128}
1129
1130@vertex
1131fn vs_star(
1132    @builtin(vertex_index) vid: u32,
1133    @builtin(instance_index) inst_id: u32,
1134) -> StarVsOut {
1135    var offsets = array<vec2<f32>, 6>(
1136        vec2<f32>(-1.0, -1.0),
1137        vec2<f32>(1.0, -1.0),
1138        vec2<f32>(1.0, 1.0),
1139        vec2<f32>(-1.0, -1.0),
1140        vec2<f32>(1.0, 1.0),
1141        vec2<f32>(-1.0, 1.0),
1142    );
1143    let q = offsets[vid];
1144    let s = stars[inst_id];
1145    let dir_ecef = normalize((cam.ecef_from_icrf * vec4<f32>(s.icrf_dir_mag.xyz, 0.0)).xyz);
1146    var clip = cam.view_proj_rte * vec4<f32>(dir_ecef, 0.0);
1147
1148    var out: StarVsOut;
1149    out.local_uv = q;
1150    let space_t = 1.0 - smoothstep(0.0, 0.80, cam.env_params.z);
1151
1152    let eye_pos = cam.eye_high.xyz + cam.eye_low.xyz;
1153    let eye_r = length(eye_pos);
1154    let eye_up = select(vec3<f32>(0.0, 1.0, 0.0), eye_pos / max(eye_r, 1.0), eye_r > 1000000.0);
1155    let r_earth = 6378137.0;
1156    let horiz_sin = select(
1157        0.0,
1158        -sqrt(max(eye_r * eye_r - r_earth * r_earth, 0.0)) / max(eye_r, r_earth),
1159        eye_r > 1000000.0,
1160    );
1161    let sun_elev = dot(normalize(cam.sun_dir.xyz), eye_up);
1162    let star_elev = dot(dir_ecef, eye_up) - horiz_sin;
1163    let sky_clear = 1.0 - clamp(cam.weather_opt_params.y * 0.85 + cam.weather_opt_params.x * 0.55, 0.0, 0.98);
1164    let night_sun_t = 1.0 - smoothstep(-0.14, 0.04, sun_elev);
1165    let night_vis_25d = night_sun_t
1166        * clamp(cam.atmo_25d_params.y, 0.0, 1.0)
1167        * sky_clear
1168        * smoothstep(0.002, 0.045, star_elev);
1169    let eff_vis = max(space_t, night_vis_25d * (1.0 - space_t));
1170
1171    if (clip.w <= 0.001 || eff_vis <= 0.005 || cam.ambient_color.w <= 0.001) {
1172        out.clip_pos = vec4<f32>(2.0, 2.0, 2.0, 1.0);
1173        out.color_flux = vec4<f32>(0.0);
1174        return out;
1175    }
1176
1177    let vmag = s.icrf_dir_mag.w;
1178    let boost_25d = mix(2.35, 1.0, space_t);
1179    let flux = clamp(pow(10.0, -0.32 * (vmag - 2.6)), 0.18, 3.6) * cam.ambient_color.w * eff_vis * boost_25d;
1180    let size_px = clamp(mix(1.85, 1.55, space_t) + (5.0 - vmag) * 0.58, 1.5, 4.8);
1181    clip.z = clip.w * 0.99985;
1182    let px_ndc = (q * size_px / max(cam.viewport_wh.xy, vec2<f32>(1.0, 1.0))) * 2.0;
1183    clip.x += px_ndc.x * clip.w;
1184    clip.y += px_ndc.y * clip.w;
1185
1186    out.clip_pos = clip;
1187    out.color_flux = vec4<f32>(s.color.rgb, flux);
1188    return out;
1189}
1190
1191@fragment
1192fn fs_star(in: StarVsOut) -> @location(0) vec4<f32> {
1193    let r2 = dot(in.local_uv, in.local_uv);
1194    if (r2 > 1.0) {
1195        return vec4<f32>(0.0);
1196    }
1197    let airy = exp(-r2 * 4.8);
1198    return vec4<f32>(in.color_flux.rgb * (in.color_flux.a * airy), airy);
1199}
1200"#;
1201
1202const TERRAIN_PULL_WGSL: &str = r#"
1203struct GpuCameraUniforms {
1204    view_proj_rte: mat4x4<f32>,
1205    inv_view_proj_rte: mat4x4<f32>,
1206    ecef_from_icrf: mat4x4<f32>,
1207    icrf_from_ecef: mat4x4<f32>,
1208    light_view_proj_rte: mat4x4<f32>,
1209    eye_high: vec4<f32>,
1210    eye_low: vec4<f32>,
1211    sun_dir: vec4<f32>,
1212    sun_color: vec4<f32>,
1213    ambient_color: vec4<f32>,
1214    sky_top: vec4<f32>,
1215    sky_bottom: vec4<f32>,
1216    moon_dir: vec4<f32>,
1217    env_params: vec4<f32>,
1218    cloud_params: vec4<f32>,
1219    viewport_wh: vec4<f32>,
1220    atmo_25d_params: vec4<f32>,
1221    weather_opt_params: vec4<f32>,
1222    cloud_tint_params: vec4<f32>,
1223    view_flags: vec4<f32>,
1224}
1225
1226struct GpuOceanUniforms {
1227    origin_high: vec4<f32>,
1228    origin_low: vec4<f32>,
1229    basis_east: vec4<f32>,
1230    basis_north: vec4<f32>,
1231    basis_up: vec4<f32>,
1232    train_a: vec4<f32>,
1233    train_b: vec4<f32>,
1234    blend_params: vec4<f32>,
1235    coastal_params: vec4<f32>,
1236    world_meta: vec4<f32>,
1237    train_a_phases0: vec4<f32>,
1238    train_a_phases1: vec4<f32>,
1239    train_b_phases0: vec4<f32>,
1240    train_b_phases1: vec4<f32>,
1241}
1242
1243struct GpuTileVertex {
1244    pos_u: vec4<f32>,
1245    norm_v: vec4<f32>,
1246}
1247
1248struct GpuTileInstance {
1249    center_high: vec4<f32>,
1250    center_low: vec4<f32>,
1251    uv_rect: vec4<f32>,
1252    night_uv_rect: vec4<f32>,
1253    tint: vec4<f32>,
1254    tile_meta: vec4<u32>,
1255}
1256
1257@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
1258@group(0) @binding(1) var<storage, read> vertices: array<GpuTileVertex>;
1259@group(0) @binding(2) var<storage, read> instances: array<GpuTileInstance>;
1260@group(0) @binding(3) var terrain_atlas: texture_2d_array<f32>;
1261@group(0) @binding(4) var terrain_sampler: sampler;
1262@group(0) @binding(5) var land_mask_tex: texture_2d<f32>;
1263@group(0) @binding(6) var env_wrap_sampler: sampler;
1264
1265@group(1) @binding(0) var shadow_map: texture_depth_2d;
1266@group(1) @binding(1) var shadow_sampler: sampler_comparison;
1267@group(1) @binding(2) var<uniform> ocean: GpuOceanUniforms;
1268@group(1) @binding(3) var coastal_sdf_tex: texture_2d<f32>;
1269@group(1) @binding(4) var coastal_sdf_sampler: sampler;
1270
1271fn dir_to_equirect_uv(d: vec3<f32>) -> vec2<f32> {
1272    let xy_len_sq = dot(d.xy, d.xy);
1273    let az = select(0.0, atan2(d.y, d.x), xy_len_sq > 1e-10);
1274    return vec2<f32>(
1275        fract(az * 0.15915494309 + 0.5),
1276        clamp(0.5 - asin(clamp(d.z, -1.0, 1.0)) * 0.31830988618, 0.001, 0.999),
1277    );
1278}
1279
1280struct TerrainVsOut {
1281    @builtin(position) clip_pos: vec4<f32>,
1282    @location(0) normal: vec3<f32>,
1283    @location(1) uv: vec2<f32>,
1284    @location(2) tint: vec4<f32>,
1285    @location(3) @interpolate(flat) tex_layer: u32,
1286    @location(4) @interpolate(flat) unlit: u32,
1287    @location(5) ecef_pos: vec3<f32>,
1288    @location(6) view_rel: vec3<f32>,
1289    @location(7) night_uv: vec2<f32>,
1290    @location(8) @interpolate(flat) night_layer: u32,
1291    @location(9) land_uv_approx: vec2<f32>,
1292    @location(10) world_mod_256: vec3<f32>,
1293}
1294
1295fn hash21(p: vec2<f32>) -> f32 {
1296    var q = fract(p * vec2<f32>(0.1031, 0.1030));
1297    q += dot(q, q.yx + 33.33);
1298    return fract((q.x + q.y) * q.x);
1299}
1300
1301fn vnoise2(x: vec2<f32>) -> f32 {
1302    let i = floor(x);
1303    let f = fract(x);
1304    let u = f * f * (3.0 - 2.0 * f);
1305    let n00 = hash21(i);
1306    let n10 = hash21(i + vec2<f32>(1.0, 0.0));
1307    let n01 = hash21(i + vec2<f32>(0.0, 1.0));
1308    let n11 = hash21(i + vec2<f32>(1.0, 1.0));
1309    return mix(mix(n00, n10, u.x), mix(n01, n11, u.x), u.y);
1310}
1311
1312// Wraps global Mercator noise offset seamlessly into [0, 32768) m for bit-exact pan/zoom stability.
1313fn ocean_noise_wrap(p_m: vec2<f32>) -> vec2<f32> {
1314    return fract(p_m * (1.0 / 32768.0)) * 32768.0;
1315}
1316
1317// Maps local ENU metres near `ocean.origin` to invariant global Mercator delta metres
1318// so crossing quantized origin cells or 3D<->2.5D morph bands produces zero wave phase jumps.
1319fn ocean_merc_from_en(pos_en: vec2<f32>, blend_25d: f32) -> vec2<f32> {
1320    if (ocean.world_meta.w < 0.0) {
1321        return pos_en;
1322    }
1323    let orig_lat_rad = ocean.world_meta.z;
1324    let east_scale_25d = ocean.world_meta.w;
1325    let dlat_est = clamp(pos_en.y * (1.0 / 6378137.0), -0.4, 0.4);
1326    let cos_curved = max(cos(clamp(orig_lat_rad + dlat_est, -1.483, 1.483)), 0.15);
1327    let cos_eff_e = max(mix(cos_curved, east_scale_25d, blend_25d), 0.15);
1328    let cos_eff_n = max(cos(clamp(orig_lat_rad + 0.5 * dlat_est, -1.483, 1.483)), 0.15);
1329    return vec2<f32>(pos_en.x / cos_eff_e, pos_en.y / cos_eff_n);
1330}
1331
1332// C2 quintic periodic 2D Perlin gradient noise rotated by integer Pythagorean matrix `rot = (rx, ry)`
1333// where `32768.0 * inv_cell == period` (exact integer wrapping across the 32768 m world tile boundary).
1334// `seed` decorrelates independent octaves after modulo wrapping without breaking periodicity.
1335// Returns vec3(value in [0,1], grad_x, grad_y) with normalized dimensionless gradient.
1336fn wrap_period2(i_raw: vec2<f32>, period: f32) -> vec2<f32> {
1337    let w = i_raw - floor(i_raw * (1.0 / period)) * period;
1338    let w_pos = select(w, w + vec2<f32>(period), w < vec2<f32>(0.0));
1339    return select(w_pos, w_pos - vec2<f32>(period), w_pos >= vec2<f32>(period));
1340}
1341
1342fn pgrad2_periodic_rot(
1343    p_mod: vec2<f32>,
1344    inv_cell: f32,
1345    period: f32,
1346    rot: vec2<f32>,
1347    seed: vec2<f32>,
1348) -> vec3<f32> {
1349    let q = p_mod * inv_cell;
1350    let x = vec2<f32>(rot.x * q.x - rot.y * q.y, rot.y * q.x + rot.x * q.y);
1351    let i0_raw = floor(x);
1352    let f = fract(x);
1353    let u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);
1354    let one_minus_f = 1.0 - f;
1355    let du = 30.0 * f * f * one_minus_f * one_minus_f;
1356
1357    let a = wrap_period2(i0_raw, period);
1358    let b = wrap_period2(a + vec2<f32>(1.0), period);
1359
1360    let ang00 = 6.2831853 * hash21(vec2<f32>(a.x, a.y) + seed);
1361    let ang10 = 6.2831853 * hash21(vec2<f32>(b.x, a.y) + seed);
1362    let ang01 = 6.2831853 * hash21(vec2<f32>(a.x, b.y) + seed);
1363    let ang11 = 6.2831853 * hash21(vec2<f32>(b.x, b.y) + seed);
1364
1365    let g00 = vec2<f32>(cos(ang00), sin(ang00));
1366    let g10 = vec2<f32>(cos(ang10), sin(ang10));
1367    let g01 = vec2<f32>(cos(ang01), sin(ang01));
1368    let g11 = vec2<f32>(cos(ang11), sin(ang11));
1369
1370    let v00 = dot(g00, f);
1371    let v10 = dot(g10, f - vec2<f32>(1.0, 0.0));
1372    let v01 = dot(g01, f - vec2<f32>(0.0, 1.0));
1373    let v11 = dot(g11, f - vec2<f32>(1.0, 1.0));
1374
1375    let k1 = v10 - v00;
1376    let k2 = v01 - v00;
1377    let k3 = v00 - v10 - v01 + v11;
1378    let h = v00 + k1 * u.x + k2 * u.y + k3 * u.x * u.y;
1379    let val01 = clamp(h * 0.70 + 0.5, 0.0, 1.0);
1380
1381    let gx_u = mix(mix(g00.x, g10.x, u.x), mix(g01.x, g11.x, u.x), u.y);
1382    let gy_u = mix(mix(g00.y, g10.y, u.x), mix(g01.y, g11.y, u.x), u.y);
1383    let dh_dx = gx_u + du.x * (k1 + k3 * u.y);
1384    let dh_dy = gy_u + du.y * (k2 + k3 * u.x);
1385
1386    let inv_rlen = 1.0 / max(length(rot), 1.0);
1387    let grad_norm = vec2<f32>(rot.x * dh_dx + rot.y * dh_dy, -rot.y * dh_dx + rot.x * dh_dy) * inv_rlen;
1388    return vec3<f32>(val01, grad_norm.x, grad_norm.y);
1389}
1390
1391// Returns Gerstner trochoidal wave displacement vec3(disp_east_m, disp_north_m, disp_up_m)
1392// for the 4 primary macro swells using world-locked phases and short-crested wave-group envelopes.
1393fn eval_ocean_vertex_train(
1394    d_merc: vec2<f32>,
1395    p_noise_base: vec2<f32>,
1396    wind_dir: vec2<f32>,
1397    wind_speed: f32,
1398    t: f32,
1399    wave_scale: f32,
1400    sample_scale_m: f32,
1401    sea_exposure: f32,
1402    phases0: vec4<f32>,
1403) -> vec3<f32> {
1404    let dir0 = normalize(wind_dir);
1405    let perp0 = vec2<f32>(-dir0.y, dir0.x);
1406
1407    let drift_m = ocean_noise_wrap(p_noise_base - dir0 * (t * 0.42));
1408    let n_warp1 = pgrad2_periodic_rot(drift_m, 1.0 / 512.0, 64.0, vec2<f32>(3.0, 4.0), vec2<f32>(11.3, 27.9)).x;
1409    let n_warp2 = pgrad2_periodic_rot(drift_m, 1.0 / 512.0, 64.0, vec2<f32>(8.0, 15.0), vec2<f32>(53.1, 19.7)).x;
1410    let warp_vec = vec2<f32>(n_warp1 - 0.5, n_warp2 - 0.5);
1411    let group_macro = 0.52 + 0.88 * (0.62 * n_warp1 + 0.38 * n_warp2);
1412
1413    // Physical Beaufort saturation curve: calm light air -> smooth ~1.38 asymptote at strong wind.
1414    let beaufort = clamp(1.38 * (1.0 - exp(-max(wind_speed, 0.3) / 10.5)), 0.10, 1.38);
1415    let len_wind = mix(0.48, 1.72, clamp(wind_speed / 18.0, 0.0, 1.3));
1416
1417    var angs = array<f32, 4>(0.04, -0.26, 0.42, -0.58);
1418    var wls = array<f32, 4>(151.0, 97.0, 61.0, 38.0);
1419    var amps = array<f32, 4>(0.025, 0.023, 0.020, 0.017);
1420    var base_ph = array<f32, 4>(phases0.x, phases0.y, phases0.z, phases0.w);
1421
1422    var disp = vec3<f32>(0.0);
1423    for (var i: u32 = 0u; i < 4u; i = i + 1u) {
1424        let wl = max((wls[i] * len_wind) / max(wave_scale, 0.15), 4.0);
1425        let aa_vs = 1.0 - smoothstep(wl * 0.32, wl * 1.05, sample_scale_m);
1426        if (aa_vs > 0.008) {
1427            let ca = cos(angs[i]);
1428            let sa = sin(angs[i]);
1429            let d = dir0 * ca + perp0 * sa;
1430            let k = 6.2831853 / wl;
1431            let p_eff = d_merc + warp_vec * min(wl * 0.48, 52.0);
1432            let ph = base_ph[i] + dot(d, p_eff) * k;
1433            let env_shift = mix(group_macro, 0.52 + 0.88 * n_warp2, select(0.18, 0.55, (i & 1u) == 1u));
1434            let steep = amps[i] * beaufort * sea_exposure * aa_vs * env_shift;
1435            let amp_m = (steep / k) * 0.56;
1436            let q_m = amp_m * 0.48;
1437            disp.x += d.x * (cos(ph) * q_m);
1438            disp.y += d.y * (cos(ph) * q_m);
1439            disp.z += sin(ph) * amp_m;
1440        }
1441    }
1442    return disp;
1443}
1444
1445@vertex
1446fn vs_terrain(
1447    @builtin(vertex_index) local_v: u32,
1448    @builtin(instance_index) inst_id: u32,
1449) -> TerrainVsOut {
1450    let inst = instances[inst_id];
1451    let v = vertices[inst.tile_meta.x + local_v];
1452    let center_rel = (inst.center_high.xyz - cam.eye_high.xyz)
1453                   + (inst.center_low.xyz - cam.eye_low.xyz);
1454    var world_rel = center_rel + v.pos_u.xyz;
1455    let raw_uv = vec2<f32>(v.pos_u.w, v.norm_v.w);
1456    var ecef_p = (inst.center_high.xyz + inst.center_low.xyz) + v.pos_u.xyz;
1457    let dv = normalize(ecef_p);
1458    let land_uv = dir_to_equirect_uv(dv);
1459
1460    let map_2d = clamp(cam.view_flags.x, 0.0, 1.0);
1461    let ocean_on = ocean.origin_high.w * ocean.origin_low.w * (1.0 - map_2d);
1462    if (ocean_on > 0.002 && inst.tile_meta.z == 0u) {
1463        let cam_minus_orig = (cam.eye_high.xyz - ocean.origin_high.xyz)
1464                           + (cam.eye_low.xyz - ocean.origin_low.xyz);
1465        let p_rel_orig = world_rel + cam_minus_orig;
1466        let east_v = ocean.basis_east.xyz;
1467        let north_v = ocean.basis_north.xyz;
1468        let up_v = ocean.basis_up.xyz;
1469        let pos_en = vec2<f32>(dot(p_rel_orig, east_v), dot(p_rel_orig, north_v));
1470        let rel_h = dot(p_rel_orig, up_v);
1471        let eye_pos = cam.eye_high.xyz + cam.eye_low.xyz;
1472        let eye_r = length(eye_pos);
1473        let blend_25d = clamp(cam.env_params.z, 0.0, 1.0) * (1.0 - map_2d);
1474        let curve_sag = select(0.0, 1.0, eye_r > 1000000.0)
1475            * (1.0 - blend_25d)
1476            * dot(pos_en, pos_en)
1477            / (2.0 * 6378137.0);
1478        let sea_elev = rel_h + curve_sag;
1479        let elev_water = 1.0 - smoothstep(-0.25, 2.2, sea_elev);
1480        let env_mask_vs = textureSampleLevel(land_mask_tex, env_wrap_sampler, land_uv, 0.0).r;
1481        let open_ocean_vs = 1.0 - smoothstep(0.04, 0.52, env_mask_vs);
1482
1483        let half_span = max(ocean.coastal_params.y, 50.0);
1484        let sdf_uv = (pos_en - ocean.coastal_params.zw) / (2.0 * half_span) + vec2<f32>(0.5);
1485        let in_sdf = smoothstep(0.01, 0.09, sdf_uv.x) * (1.0 - smoothstep(0.91, 0.99, sdf_uv.x))
1486                   * smoothstep(0.01, 0.09, sdf_uv.y) * (1.0 - smoothstep(0.91, 0.99, sdf_uv.y));
1487        let sdf_s = textureSampleLevel(
1488            coastal_sdf_tex,
1489            coastal_sdf_sampler,
1490            clamp(sdf_uv, vec2<f32>(0.002), vec2<f32>(0.998)),
1491            0.0,
1492        );
1493        let use_sdf = ocean.blend_params.w * in_sdf;
1494        let shore_dist_norm = mix(1.0, sdf_s.g, use_sdf);
1495        let shore_taper = mix(1.0, smoothstep(0.02, 0.16, shore_dist_norm), use_sdf);
1496        let near_exp_vs = mix(0.32, 0.78, smoothstep(0.06, 0.88, shore_dist_norm));
1497        let open_exp_vs = mix(0.38, 1.0, smoothstep(0.05, 0.92, open_ocean_vs));
1498        let sea_exposure_vs = mix(
1499            1.0,
1500            max(near_exp_vs, open_exp_vs),
1501            clamp(use_sdf + (1.0 - open_ocean_vs) * 0.65, 0.0, 1.0),
1502        );
1503        let water_vs = clamp(mix(open_ocean_vs, sdf_s.r, use_sdf) * elev_water * shore_taper, 0.0, 1.0);
1504
1505        if (water_vs > 0.005) {
1506            let view_dist = length(world_rel);
1507            let sample_scale_m = max(view_dist * 0.032, 4.0);
1508            let wave_strength = ocean.basis_east.w;
1509            let wave_scale = ocean.basis_north.w;
1510            let d_merc = ocean_merc_from_en(pos_en, blend_25d);
1511            let p_noise_base = ocean_noise_wrap(ocean.world_meta.xy + d_merc);
1512            let wa = ocean.blend_params.x;
1513            let wb = ocean.blend_params.y;
1514            let w_sum = max(wa + wb, 1e-4);
1515            var disp_enu = vec3<f32>(0.0);
1516            if (wa > 0.002) {
1517                disp_enu += eval_ocean_vertex_train(
1518                    d_merc,
1519                    p_noise_base,
1520                    ocean.train_a.xy,
1521                    ocean.train_a.z,
1522                    ocean.train_a.w,
1523                    wave_scale,
1524                    sample_scale_m,
1525                    sea_exposure_vs,
1526                    ocean.train_a_phases0,
1527                ) * wa;
1528            }
1529            if (wb > 0.002) {
1530                disp_enu += eval_ocean_vertex_train(
1531                    d_merc,
1532                    p_noise_base,
1533                    ocean.train_b.xy,
1534                    ocean.train_b.z,
1535                    ocean.train_b.w,
1536                    wave_scale,
1537                    sample_scale_m,
1538                    sea_exposure_vs,
1539                    ocean.train_b_phases0,
1540                ) * wb;
1541            }
1542            disp_enu = (disp_enu / w_sum) * wave_strength * water_vs * ocean_on * ocean.blend_params.z;
1543            let disp_world = east_v * disp_enu.x + north_v * disp_enu.y + up_v * disp_enu.z;
1544            world_rel += disp_world;
1545            ecef_p += disp_world;
1546        }
1547    }
1548
1549    let mod_base = floor(inst.center_high.xyz * (1.0 / 256.0)) * 256.0;
1550    var out: TerrainVsOut;
1551    out.clip_pos = cam.view_proj_rte * vec4<f32>(world_rel, 1.0);
1552    out.normal = normalize(v.norm_v.xyz);
1553    out.uv = mix(inst.uv_rect.xy, inst.uv_rect.zw, raw_uv);
1554    out.tint = inst.tint;
1555    out.tex_layer = inst.tile_meta.y;
1556    out.unlit = inst.tile_meta.z;
1557    out.ecef_pos = ecef_p;
1558    out.view_rel = world_rel;
1559    out.night_uv = mix(inst.night_uv_rect.xy, inst.night_uv_rect.zw, raw_uv);
1560    out.night_layer = inst.tile_meta.w;
1561    out.land_uv_approx = land_uv;
1562    out.world_mod_256 = (inst.center_high.xyz - mod_base) + inst.center_low.xyz + v.pos_u.xyz;
1563    return out;
1564}
1565
1566fn sample_shadow_pcf(world_rel: vec3<f32>, n_mesh: vec3<f32>, sun_dir: vec3<f32>, shadow_radius: f32) -> f32 {
1567    let ndotl = max(dot(n_mesh, sun_dir), 0.0);
1568    let normal_bias = max(shadow_radius * 0.0016, 0.45) * (1.25 - 0.75 * ndotl);
1569    let biased_rel = world_rel + n_mesh * normal_bias;
1570    let lclip = cam.light_view_proj_rte * vec4<f32>(biased_rel, 1.0);
1571    let ndc = lclip.xyz / max(lclip.w, 1e-5);
1572    let uv = vec2<f32>(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
1573    let depth_ref = clamp(ndc.z - 0.00055, 0.0, 0.9999);
1574
1575    let dims = max(vec2<f32>(textureDimensions(shadow_map)), vec2<f32>(1.0));
1576    let texel = 1.0 / dims;
1577    var acc = 0.0;
1578    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(-texel.x, -texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1579    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(0.0, -texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1580    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(texel.x, -texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1581    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(-texel.x, 0.0), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1582    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv, vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1583    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(texel.x, 0.0), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1584    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(-texel.x, texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1585    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(0.0, texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1586    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(texel.x, texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1587    let pcf = acc * (1.0 / 9.0);
1588
1589    // Smooth edge fade near the border of the orthographic shadow frustum so shadows never clip abruptly.
1590    let border = max(abs(ndc.x), abs(ndc.y));
1591    let in_bounds = (1.0 - smoothstep(0.84, 0.99, border)) * step(0.0, ndc.z) * step(ndc.z, 1.0);
1592    return mix(1.0, pcf, in_bounds);
1593}
1594
1595fn eval_sky_reflection(
1596    rd: vec3<f32>,
1597    eye_up: vec3<f32>,
1598    sun_dir: vec3<f32>,
1599    real_sky_w: f32,
1600    weather_dark: f32,
1601    cloud_cov: f32,
1602) -> vec3<f32> {
1603    let h = clamp(max(dot(rd, eye_up), 0.0), 0.0, 1.0);
1604    let sun_elev = dot(sun_dir, eye_up);
1605    let day_t = smoothstep(-0.08, 0.24, sun_elev);
1606    let twilight_t = smoothstep(-0.22, -0.02, sun_elev) * (1.0 - smoothstep(0.02, 0.22, sun_elev));
1607    let golden_t = exp(-pow((sun_elev - 0.03) * 7.5, 2.0));
1608
1609    let day_zen = mix(vec3<f32>(0.09, 0.14, 0.32), vec3<f32>(0.08, 0.24, 0.56), smoothstep(0.02, 0.35, sun_elev));
1610    let day_hor = mix(vec3<f32>(0.95, 0.48, 0.20), vec3<f32>(0.72, 0.85, 0.96), smoothstep(0.02, 0.32, sun_elev));
1611    let night_zen = vec3<f32>(0.009, 0.016, 0.036);
1612    let night_hor = vec3<f32>(0.026, 0.042, 0.075);
1613
1614    let zen = mix(night_zen, day_zen, day_t) + vec3<f32>(0.04, 0.04, 0.10) * twilight_t;
1615    let hor = mix(night_hor, day_hor, day_t) + vec3<f32>(0.32, 0.15, 0.09) * twilight_t;
1616    var phys = mix(hor, zen, pow(h, 0.55));
1617    let sun_cos = max(dot(rd, sun_dir), 0.0);
1618    let cloud_atten = 1.0 - clamp(weather_dark * 0.78 + cloud_cov * 0.35, 0.0, 0.92);
1619    phys += vec3<f32>(1.0, 0.58, 0.26) * pow(sun_cos, 6.0) * (golden_t * 0.55 + day_t * 0.18) * cloud_atten;
1620
1621    let storm_w = clamp(weather_dark * 0.82 + cloud_cov * 0.22, 0.0, 0.92);
1622    let overcast = mix(vec3<f32>(0.02, 0.025, 0.038), vec3<f32>(0.32, 0.37, 0.44), clamp(day_t + twilight_t * 0.35, 0.0, 1.0));
1623    phys = mix(phys, overcast, storm_w * 0.72);
1624
1625    let classic = mix(vec3<f32>(0.68, 0.82, 0.95), vec3<f32>(0.14, 0.34, 0.66), pow(h, 0.55));
1626    return mix(classic, phys, real_sky_w);
1627}
1628
1629// Evaluates 8 directional anti-aliased short-crested Gerstner swells plus 6 octaves of
1630// Pythagorean-rotated C2 periodic Perlin gradient-noise wavelets & capillary slopes.
1631// Uses world-fixed Mercator deltas (`d_merc`) and pre-reduced CPU f64 base phases (`phases0/1`) so
1632// ocean waves never jump or alter pattern across camera pan, zoom, or 3D<->2.5D morph transitions.
1633// Returns vec4(slope_east, slope_north, crest_steepness, subpixel_aa_roughness).
1634fn eval_ocean_train(
1635    d_merc: vec2<f32>,
1636    p_noise_base: vec2<f32>,
1637    wind_dir: vec2<f32>,
1638    wind_speed: f32,
1639    t: f32,
1640    wave_scale: f32,
1641    px_m: f32,
1642    sea_exposure: f32,
1643    phases0: vec4<f32>,
1644    phases1: vec4<f32>,
1645) -> vec4<f32> {
1646    let dir0 = normalize(wind_dir);
1647    let perp0 = vec2<f32>(-dir0.y, dir0.x);
1648
1649    // Multi-scale advected Perlin gradient noise drives smooth wave packets ("sets"), domain warp, and gusts.
1650    let drift_macro = ocean_noise_wrap(p_noise_base - dir0 * (t * 0.42));
1651    let drift_cross = ocean_noise_wrap(p_noise_base - dir0 * (t * 0.65) + perp0 * (t * 0.22));
1652    let gw1 = pgrad2_periodic_rot(drift_macro, 1.0 / 512.0, 64.0, vec2<f32>(3.0, 4.0), vec2<f32>(11.3, 27.9));
1653    let gw2 = pgrad2_periodic_rot(drift_cross, 1.0 / 512.0, 64.0, vec2<f32>(8.0, 15.0), vec2<f32>(53.1, 19.7));
1654    let n_warp1 = gw1.x;
1655    let n_warp2 = gw2.x;
1656    let warp_vec = vec2<f32>(n_warp1 - 0.5, n_warp2 - 0.5);
1657    let group_macro = 0.48 + 0.96 * (0.60 * n_warp1 + 0.40 * n_warp2);
1658
1659    let drift_mid = ocean_noise_wrap(p_noise_base - dir0 * (t * 0.85) - perp0 * (t * 0.18));
1660    let gc = pgrad2_periodic_rot(drift_mid, 1.0 / 256.0, 128.0, vec2<f32>(5.0, 12.0), vec2<f32>(103.5, 41.2));
1661    let drift_b = ocean_noise_wrap(p_noise_base - dir0 * (t * 1.15) + perp0 * (t * 0.31) + vec2<f32>(317.0, 911.0));
1662    let gd = pgrad2_periodic_rot(drift_b, 1.0 / 128.0, 256.0, vec2<f32>(15.0, 8.0), vec2<f32>(19.7, 131.3));
1663    let n_gust = 0.58 * gc.x + 0.42 * n_warp2;
1664    let group_chop = 0.42 + 1.12 * (0.55 * gc.x + 0.45 * gd.x);
1665
1666    // Physical Beaufort asymptote: calm light ripples at 2 m/s, rolling swells at 7-12 m/s,
1667    // smoothly saturating toward 1.38 in gale winds instead of scaling linearly to extremes.
1668    let beaufort = clamp(1.38 * (1.0 - exp(-max(wind_speed, 0.3) / 10.5)), 0.10, 1.38);
1669    let len_wind = mix(0.48, 1.72, clamp(wind_speed / 18.0, 0.0, 1.3));
1670
1671    // 8 incommensurable directional swells localized into short-crested wave packets so no grid stripes form.
1672    var angs = array<f32, 8>(0.04, -0.26, 0.42, -0.58, 0.77, -0.86, 0.21, -0.41);
1673    var wls = array<f32, 8>(151.0, 97.0, 61.0, 38.0, 23.5, 13.7, 7.9, 4.3);
1674    var amps = array<f32, 8>(0.025, 0.023, 0.020, 0.017, 0.014, 0.011, 0.0085, 0.006);
1675    var base_ph = array<f32, 8>(
1676        phases0.x, phases0.y, phases0.z, phases0.w,
1677        phases1.x, phases1.y, phases1.z, phases1.w,
1678    );
1679
1680    var slope = vec2<f32>(0.0);
1681    var crest_acc = 0.0;
1682    let warp_mid = vec2<f32>(gc.x - 0.5, gd.x - 0.5);
1683
1684    for (var i: u32 = 0u; i < 8u; i = i + 1u) {
1685        let wl = max((wls[i] * len_wind) / max(wave_scale, 0.15), 1.4);
1686        let aa_w = 1.0 - smoothstep(wl * 0.22, wl * 0.58, px_m);
1687        if (aa_w > 0.008) {
1688            let ca = cos(angs[i]);
1689            let sa = sin(angs[i]);
1690            let d = dir0 * ca + perp0 * sa;
1691            let k = 6.2831853 / wl;
1692            let w_m = select(min(wl * 0.28, 7.5), min(wl * 0.48, 52.0), i < 4u);
1693            let p_eff = d_merc + warp_vec * w_m + warp_mid * min(wl * 0.22, 11.0);
1694            let ph = base_ph[i] + dot(d, p_eff) * k;
1695            let s = sin(ph);
1696            let c = cos(ph);
1697            let sharp = 0.5 + 0.5 * s;
1698            let env_alt = 0.45 + 1.05 * select(gd.x, n_warp2, (i & 1u) == 1u);
1699            let env_base = select(group_chop, group_macro, i < 4u);
1700            let env = mix(env_base, env_alt, 0.35);
1701            let steep = amps[i] * beaufort * sea_exposure * aa_w * env;
1702            let d_wave = c * (0.72 + 0.56 * sharp);
1703            slope += d * (d_wave * steep);
1704            crest_acc += pow(sharp, 2.4) * steep * 4.2;
1705        }
1706    }
1707
1708    // 6 isotropic periodic Perlin gradient wavelets (~102m down to ~0.94m) provide rich organic
1709    // ocean texture with zero square-cell artifacts and preserve distant roughness via AA deficit.
1710    var noise_slope = vec2<f32>(0.0);
1711    var aa_rough = 0.0;
1712    let noise_strength = beaufort * sea_exposure * (0.62 + 0.72 * n_gust);
1713
1714    let cell_a = (512.0 / 5.0) / max(wave_scale, 0.25);
1715    let aa_a = 1.0 - smoothstep(cell_a * 0.25, cell_a * 0.85, px_m);
1716    if (aa_a > 0.008) {
1717        noise_slope += gw1.yz * (0.018 * noise_strength * aa_a);
1718    }
1719
1720    let cell_b = (512.0 / 17.0) / max(wave_scale, 0.25);
1721    let aa_b = 1.0 - smoothstep(cell_b * 0.25, cell_b * 0.85, px_m);
1722    if (aa_b > 0.008) {
1723        noise_slope += gw2.yz * (0.021 * noise_strength * aa_b);
1724    }
1725
1726    let cell_c = (256.0 / 13.0) / max(wave_scale, 0.25);
1727    let aa_c = 1.0 - smoothstep(cell_c * 0.25, cell_c * 0.85, px_m);
1728    if (aa_c > 0.008) {
1729        noise_slope += gc.yz * (0.022 * noise_strength * aa_c);
1730    }
1731
1732    let cell_d = (128.0 / 17.0) / max(wave_scale, 0.25);
1733    let aa_d = 1.0 - smoothstep(cell_d * 0.25, cell_d * 0.85, px_m);
1734    if (aa_d > 0.008) {
1735        noise_slope += gd.yz * (0.020 * noise_strength * aa_d);
1736    }
1737    aa_rough += (1.0 - aa_d) * 0.028;
1738
1739    let cell_e = (32.0 / 13.0) / max(wave_scale, 0.25);
1740    let aa_e = 1.0 - smoothstep(cell_e * 0.25, cell_e * 0.85, px_m);
1741    if (aa_e > 0.008) {
1742        let ge = pgrad2_periodic_rot(drift_mid, 1.0 / 32.0, 1024.0, vec2<f32>(12.0, 5.0), vec2<f32>(61.9, 97.1)).yz;
1743        noise_slope += ge * (0.017 * noise_strength * aa_e);
1744    }
1745    aa_rough += (1.0 - aa_e) * 0.042;
1746
1747    let cell_f = (16.0 / 17.0) / max(wave_scale, 0.25);
1748    let aa_f = 1.0 - smoothstep(cell_f * 0.25, cell_f * 0.85, px_m);
1749    if (aa_f > 0.008) {
1750        let gf = pgrad2_periodic_rot(drift_b, 1.0 / 16.0, 2048.0, vec2<f32>(8.0, 15.0), vec2<f32>(149.1, 33.7)).yz;
1751        noise_slope += gf * (0.013 * noise_strength * aa_f);
1752    }
1753    aa_rough += (1.0 - aa_f) * 0.036;
1754
1755    slope += noise_slope;
1756    crest_acc += clamp(length(noise_slope) * 1.45, 0.0, 0.36);
1757    return vec4<f32>(slope.x, slope.y, crest_acc, aa_rough * clamp(sea_exposure * beaufort, 0.15, 1.2));
1758}
1759
1760fn hash31(p: vec3<f32>) -> f32 {
1761    var q = fract(p * vec3<f32>(0.1031, 0.1030, 0.0973));
1762    q += dot(q, q.yxz + 33.33);
1763    return fract((q.x + q.y) * q.z);
1764}
1765
1766fn vnoise3_periodic(p_mod_256: vec3<f32>, period: f32) -> f32 {
1767    let x = p_mod_256 * (period * (1.0 / 256.0));
1768    let i0 = floor(x);
1769    let f = fract(x);
1770    let u = f * f * (3.0 - 2.0 * f);
1771    let a = i0 - floor(i0 / period) * period;
1772    let i1_raw = i0 + vec3<f32>(1.0);
1773    let b = i1_raw - floor(i1_raw / period) * period;
1774
1775    let c000 = hash31(vec3<f32>(a.x, a.y, a.z));
1776    let c100 = hash31(vec3<f32>(b.x, a.y, a.z));
1777    let c010 = hash31(vec3<f32>(a.x, b.y, a.z));
1778    let c110 = hash31(vec3<f32>(b.x, b.y, a.z));
1779    let c001 = hash31(vec3<f32>(a.x, a.y, b.z));
1780    let c101 = hash31(vec3<f32>(b.x, a.y, b.z));
1781    let c011 = hash31(vec3<f32>(a.x, b.y, b.z));
1782    let c111 = hash31(vec3<f32>(b.x, b.y, b.z));
1783
1784    let x00 = mix(c000, c100, u.x);
1785    let x10 = mix(c010, c110, u.x);
1786    let x01 = mix(c001, c101, u.x);
1787    let x11 = mix(c011, c111, u.x);
1788    return mix(mix(x00, x10, u.y), mix(x01, x11, u.y), u.z);
1789}
1790
1791fn eval_micro_height(p_mod_256: vec3<f32>, raw_px_m: f32) -> f32 {
1792    let w8 = 1.0 - smoothstep(1.2, 4.0, raw_px_m);
1793    let w2 = 1.0 - smoothstep(0.32, 1.0, raw_px_m);
1794    let w05 = 1.0 - smoothstep(0.08, 0.30, raw_px_m);
1795    let w01 = 1.0 - smoothstep(0.02, 0.08, raw_px_m);
1796    var h = (vnoise3_periodic(p_mod_256, 32.0) - 0.5) * 0.44 * w8;
1797    h += (vnoise3_periodic(p_mod_256, 128.0) - 0.5) * 0.30 * w2;
1798    if (w05 > 0.01) {
1799        h += (vnoise3_periodic(p_mod_256, 512.0) - 0.5) * 0.18 * w05;
1800    }
1801    if (w01 > 0.01) {
1802        h += (vnoise3_periodic(p_mod_256, 2048.0) - 0.5) * 0.10 * w01;
1803    }
1804    return h;
1805}
1806
1807fn shade_terrain(in: TerrainVsOut, base: vec4<f32>) -> vec4<f32> {
1808    let map_2d = clamp(cam.view_flags.x, 0.0, 1.0);
1809    if (in.unlit != 0u || map_2d >= 0.99) {
1810        return base;
1811    }
1812
1813    let n_mesh = normalize(in.normal);
1814    let sun_dir = normalize(cam.sun_dir.xyz);
1815    let view_dir = normalize(-in.view_rel);
1816
1817    let dn_strength = clamp(cam.env_params.x, 0.0, 1.0);
1818    let city_strength = max(cam.env_params.y, 0.0);
1819    let blend_25d = clamp(cam.env_params.z, 0.0, 1.0) * (1.0 - map_2d);
1820    let real_sky_w = clamp(cam.atmo_25d_params.x, 0.0, 1.0);
1821    let night_star_w = clamp(cam.atmo_25d_params.y, 0.0, 1.0);
1822    let lit_25d_w = clamp(cam.atmo_25d_params.z, 0.0, 1.0);
1823    let shadow_w = clamp(cam.atmo_25d_params.w, 0.0, 1.0);
1824    let weather_dark = clamp(cam.weather_opt_params.x, 0.0, 1.0);
1825    let cloud_cov = clamp(cam.weather_opt_params.y, 0.0, 1.0);
1826    let weather_haze = clamp(cam.weather_opt_params.z, 0.0, 1.0);
1827
1828    let d = normalize(in.ecef_pos);
1829    let eye_pos = cam.eye_high.xyz + cam.eye_low.xyz;
1830    let eye_r = length(eye_pos);
1831    let local_up = select(vec3<f32>(0.0, 1.0, 0.0), d, eye_r > 1000000.0);
1832    let ndotl = dot(local_up, sun_dir);
1833
1834    // Keep derivatives & texture lookups in uniform control flow for WGSL validation.
1835    let raw_px_m = length(fwidth(in.view_rel));
1836    let px_m = max(raw_px_m, 0.15);
1837    let env_uv = dir_to_equirect_uv(d);
1838    let env_lod = clamp(log2(max(px_m * 0.0001022, 1.0)), 0.0, 5.0);
1839    let env_mask = textureSampleLevel(land_mask_tex, env_wrap_sampler, env_uv, env_lod);
1840    let on_land = smoothstep(0.18, 0.55, env_mask.r);
1841
1842    // Close-ground (< ~50-80m) procedural micro-albedo grain & micro-normal bump on land surfaces.
1843    let is_water_est = clamp(
1844        (1.0 - smoothstep(0.08, 0.42, env_mask.r))
1845            + select(0.0, 0.85, (base.b - base.r > 0.015) && env_mask.r < 0.65),
1846        0.0,
1847        1.0,
1848    );
1849    let micro_w = (1.0 - smoothstep(0.05, 0.80, raw_px_m)) * (1.0 - is_water_est) * (1.0 - map_2d);
1850    var n_lit = n_mesh;
1851    var base_micro_rgb = base.rgb;
1852    if (micro_w > 0.005) {
1853        let up_ref = select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(n_mesh.y) > 0.9);
1854        let t_e = normalize(cross(up_ref, n_mesh));
1855        let t_n = cross(n_mesh, t_e);
1856        let h0 = eval_micro_height(in.world_mod_256, raw_px_m);
1857        let eps = max(raw_px_m * 0.75, 0.06);
1858        let he = eval_micro_height(in.world_mod_256 + t_e * eps, raw_px_m);
1859        let hn = eval_micro_height(in.world_mod_256 + t_n * eps, raw_px_m);
1860        let slope_e = ((he - h0) / eps) * 0.16 * micro_w;
1861        let slope_n = ((hn - h0) / eps) * 0.16 * micro_w;
1862        n_lit = normalize(n_mesh - t_e * slope_e - t_n * slope_n);
1863        let albedo_mod = 1.0 + h0 * (0.24 * micro_w);
1864        base_micro_rgb = clamp(base.rgb * albedo_mod, vec3<f32>(0.0), vec3<f32>(1.0));
1865    }
1866    let slope_ndotl = max(dot(n_lit, sun_dir), 0.0);
1867
1868    // Hardware 9-tap PCF directional shadow sampling (uniform control flow).
1869    var shadow_factor = 1.0;
1870    if (shadow_w > 0.001) {
1871        let pcf = sample_shadow_pcf(in.view_rel, n_mesh, sun_dir, max(cam.weather_opt_params.w, 10.0));
1872        shadow_factor = mix(1.0, pcf, shadow_w * (1.0 - weather_dark * 0.58));
1873    }
1874
1875    // --- Orbital 3D lighting ---
1876    let slope_shade = clamp(1.0 + (dot(n_lit, sun_dir) - ndotl) * 0.35 * blend_25d, 0.82, 1.18);
1877    let terminator = smoothstep(-0.14, 0.16, ndotl);
1878    let tn = ndotl * 7.5;
1879    let twilight = exp(-tn * tn) * vec3<f32>(0.42, 0.18, 0.06);
1880    let f1 = 1.0 - max(dot(local_up, view_dir), 0.0);
1881    let fresnel = f1 * f1 * f1;
1882    let atmo_rim = vec3<f32>(0.28, 0.56, 1.0)
1883        * fresnel
1884        * smoothstep(-0.18, 0.32, ndotl)
1885        * 0.45
1886        * (1.0 - blend_25d)
1887        * (1.0 - smoothstep(0.0, 0.55, map_2d));
1888    let ocean_night = vec3<f32>(0.048, 0.068, 0.108);
1889    let land_night = vec3<f32>(0.095, 0.120, 0.174);
1890    let night_fill = mix(ocean_night, land_night, on_land);
1891    let day_lit_3d = (night_fill + cam.sun_color.rgb * terminator + twilight) * slope_shade;
1892    let flat_lit = vec3<f32>(0.98);
1893    var lit = mix(flat_lit, day_lit_3d, dn_strength);
1894
1895    // --- Opt-in Realistic 2.5D Mountain Lighting & Cast Shadows ---
1896    let local_lit_blend = lit_25d_w * blend_25d;
1897    if (local_lit_blend > 0.001) {
1898        let sun_elev = dot(local_up, sun_dir);
1899        let day_t = smoothstep(-0.08, 0.24, sun_elev);
1900        let golden_t = exp(-pow((sun_elev - 0.04) * 7.2, 2.0));
1901        let sun_tint = mix(vec3<f32>(1.0, 0.56, 0.26), vec3<f32>(1.02, 0.99, 0.94), smoothstep(0.01, 0.30, sun_elev));
1902        let weather_sun_atten = 1.0 - clamp(weather_dark * 0.70 + cloud_cov * 0.22, 0.0, 0.85);
1903        // Normalize diffuse relative to typical overhead imagery luminance so sunlit slopes look crisp,
1904        // shaded valley/mountain backs drop dramatically into cool blue ambient shadow!
1905        let direct_intensity = smoothstep(-0.04, 0.12, sun_elev) * weather_sun_atten;
1906        let slope_term = clamp(slope_ndotl / max(sun_elev, 0.28), 0.0, 1.38);
1907        let direct_sun = sun_tint * (0.76 * slope_term * direct_intensity * shadow_factor);
1908
1909        let sky_hemi = 0.5 + 0.5 * dot(n_lit, local_up);
1910        let day_amb = mix(vec3<f32>(0.22, 0.28, 0.40), vec3<f32>(0.34, 0.42, 0.54), sky_hemi)
1911            * mix(1.0, 0.72, weather_dark);
1912        let sunset_amb = vec3<f32>(0.30, 0.22, 0.26) * golden_t * 0.55;
1913        let night_amb = mix(vec3<f32>(0.055, 0.075, 0.125), vec3<f32>(0.095, 0.120, 0.180), on_land)
1914            * (0.75 + 0.25 * sky_hemi);
1915        let ambient_25d = mix(night_amb, day_amb, day_t) + sunset_amb;
1916        let lit_25d = ambient_25d + direct_sun;
1917        lit = mix(lit, lit_25d, local_lit_blend);
1918    }
1919
1920    var rgb = base_micro_rgb * lit + atmo_rim * dn_strength;
1921
1922    // --- GPU-Native Directional Ocean Waves + Optional Coastal Periodic Surf ---
1923    let ocean_on = ocean.origin_high.w * ocean.origin_low.w * (1.0 - map_2d);
1924    if (ocean_on > 0.002) {
1925        // Compute high-precision RTE local tangent coordinates relative to ocean origin.
1926        let cam_minus_orig = (cam.eye_high.xyz - ocean.origin_high.xyz)
1927                           + (cam.eye_low.xyz - ocean.origin_low.xyz);
1928        let p_rel_orig = in.view_rel + cam_minus_orig;
1929        let east_v = ocean.basis_east.xyz;
1930        let north_v = ocean.basis_north.xyz;
1931        let up_v = ocean.basis_up.xyz;
1932        let pos_en = vec2<f32>(dot(p_rel_orig, east_v), dot(p_rel_orig, north_v));
1933        let rel_h = dot(p_rel_orig, up_v);
1934
1935        // 5-tap C1-smooth coastal SDF sample eliminates 128x128 u8 bilinear facets along coastlines.
1936        let half_span = max(ocean.coastal_params.y, 50.0);
1937        let sdf_uv = (pos_en - ocean.coastal_params.zw) / (2.0 * half_span) + vec2<f32>(0.5);
1938        let in_sdf = smoothstep(0.01, 0.09, sdf_uv.x) * (1.0 - smoothstep(0.91, 0.99, sdf_uv.x))
1939                   * smoothstep(0.01, 0.09, sdf_uv.y) * (1.0 - smoothstep(0.91, 0.99, sdf_uv.y));
1940        let sdf_texel = 1.0 / max(vec2<f32>(textureDimensions(coastal_sdf_tex)), vec2<f32>(8.0));
1941        let sdf_d = sdf_texel * 0.70;
1942        let uv_c = clamp(sdf_uv, vec2<f32>(0.002), vec2<f32>(0.998));
1943        let sdf_c0 = textureSampleLevel(coastal_sdf_tex, coastal_sdf_sampler, uv_c, 0.0);
1944        let sdf_c1 = textureSampleLevel(coastal_sdf_tex, coastal_sdf_sampler, clamp(uv_c + vec2<f32>(sdf_d.x, sdf_d.y), vec2<f32>(0.002), vec2<f32>(0.998)), 0.0);
1945        let sdf_c2 = textureSampleLevel(coastal_sdf_tex, coastal_sdf_sampler, clamp(uv_c + vec2<f32>(-sdf_d.x, sdf_d.y), vec2<f32>(0.002), vec2<f32>(0.998)), 0.0);
1946        let sdf_c3 = textureSampleLevel(coastal_sdf_tex, coastal_sdf_sampler, clamp(uv_c + vec2<f32>(sdf_d.x, -sdf_d.y), vec2<f32>(0.002), vec2<f32>(0.998)), 0.0);
1947        let sdf_c4 = textureSampleLevel(coastal_sdf_tex, coastal_sdf_sampler, clamp(uv_c + vec2<f32>(-sdf_d.x, -sdf_d.y), vec2<f32>(0.002), vec2<f32>(0.998)), 0.0);
1948        let sdf_s = sdf_c0 * 0.50 + (sdf_c1 + sdf_c2 + sdf_c3 + sdf_c4) * 0.125;
1949
1950        let use_sdf = ocean.blend_params.w * in_sdf;
1951        let curve_sag = select(0.0, 1.0, eye_r > 1000000.0)
1952            * (1.0 - blend_25d)
1953            * dot(pos_en, pos_en)
1954            / (2.0 * 6378137.0);
1955        let sea_elev = rel_h + curve_sag;
1956        let elev_water = 1.0 - smoothstep(0.6, 5.5, sea_elev);
1957
1958        // Pixel-sharp water classification from satellite imagery & elevation; SDF fills bright foam holes only.
1959        let max_c = max(base.r, max(base.g, base.b));
1960        let min_c = min(base.r, min(base.g, base.b));
1961        let cool_px = select(0.0, 1.0, (base.b >= base.r - 0.010) && (base.b + 0.030 >= base.g) && ((base.b - base.r >= 0.012) || max_c < 0.42));
1962        let emerald_px = select(0.0, 1.0, (base.b >= base.r + 0.014) && (base.g >= base.r + 0.016) && base.r < 0.46);
1963        let surf_foam_px = select(0.0, 1.0, (min_c > 0.56) && (base.b >= base.r - 0.012) && (sea_elev < 0.90) && (env_mask.r < 0.72));
1964        let warm_land = select(0.0, 1.0, (base.r - base.b >= 0.022) || ((min_c > 0.64) && (base.r > base.b + 0.008)));
1965        let img_water = clamp((cool_px + emerald_px + surf_foam_px) * (1.0 - warm_land), 0.0, 1.0);
1966
1967        let open_ocean_mask = 1.0 - smoothstep(0.04, 0.52, env_mask.r);
1968        let gpu_water = clamp(mix(img_water, 1.0, open_ocean_mask) * (1.0 - smoothstep(0.75, 0.96, env_mask.r) * (1.0 - img_water)) * elev_water, 0.0, 1.0);
1969        let sdf_surf_fill = clamp((sdf_s.r - 0.55) * 2.2, 0.0, 1.0)
1970                          * (1.0 - smoothstep(0.3, 2.0, sea_elev))
1971                          * (1.0 - warm_land);
1972        let water_mask = clamp(max(gpu_water, sdf_surf_fill * use_sdf), 0.0, 1.0);
1973
1974        let swash_margin = use_sdf * (1.0 - smoothstep(36.0, 58.0, sdf_s.g * ocean.coastal_params.x))
1975                         * (1.0 - smoothstep(0.20, 1.55, sea_elev));
1976
1977        if (water_mask > 0.01 || swash_margin > 0.01) {
1978            let shore_dist_norm = mix(1.0, sdf_s.g, use_sdf);
1979            let raw_sdir = sdf_s.ba * 2.0 - vec2<f32>(1.0);
1980            let sdir_len = length(raw_sdir);
1981            let shore_dir = select(vec2<f32>(1.0, 0.0), raw_sdir / max(sdir_len, 1e-4), sdir_len > 0.05);
1982
1983            let shoal_boost = use_sdf * (1.0 - smoothstep(0.04, 0.45, shore_dist_norm));
1984
1985            let wave_strength = ocean.basis_east.w;
1986            let wave_scale = ocean.basis_north.w;
1987            let glint_scale = ocean.basis_up.w;
1988            let d_merc = ocean_merc_from_en(pos_en, blend_25d);
1989            let p_noise_base = ocean_noise_wrap(ocean.world_meta.xy + d_merc);
1990
1991            // Smooth noise-warped open-ocean fetch: calm in sheltered coves (~0.34x), gradually building
1992            // seaward to full capped open-sea swells (~1.0x) without shoreline-parallel contour bands.
1993            let d_m_raw = shore_dist_norm * ocean.coastal_params.x;
1994            let n_cw1 = pgrad2_periodic_rot(p_noise_base, 1.0 / 512.0, 64.0, vec2<f32>(3.0, 4.0), vec2<f32>(71.3, 13.9)).x;
1995            let n_cw2 = pgrad2_periodic_rot(p_noise_base, 1.0 / 256.0, 128.0, vec2<f32>(5.0, 12.0), vec2<f32>(29.1, 87.7)).x;
1996            let warp_fetch = (n_cw1 - 0.5) * 110.0 + (n_cw2 - 0.5) * 42.0;
1997            let d_fetch = max(d_m_raw + warp_fetch, 0.0);
1998            let open_fetch = 1.0 - smoothstep(0.02, 0.54, clamp(env_mask.r + (n_cw1 - 0.5) * 0.18, 0.0, 1.0));
1999            let near_fetch = mix(0.32, 0.78, smoothstep(24.0, 320.0, d_fetch));
2000            let far_fetch = mix(0.38, 1.0, smoothstep(0.05, 0.92, open_fetch));
2001            let sea_exposure = mix(1.0, max(near_fetch, far_fetch), clamp(use_sdf + (1.0 - open_ocean_mask) * 0.65, 0.0, 1.0));
2002
2003            // Dual-state smooth wind cross-fade (zero phase-spin glitch on wind angle/speed change!).
2004            let wa = ocean.blend_params.x;
2005            let wb = ocean.blend_params.y;
2006            let w_sum = max(wa + wb, 1e-4);
2007            var wave_res = vec4<f32>(0.0);
2008            if (wa > 0.002) {
2009                wave_res += eval_ocean_train(
2010                    d_merc,
2011                    p_noise_base,
2012                    ocean.train_a.xy,
2013                    ocean.train_a.z,
2014                    ocean.train_a.w,
2015                    wave_scale,
2016                    px_m,
2017                    sea_exposure,
2018                    ocean.train_a_phases0,
2019                    ocean.train_a_phases1,
2020                ) * (wa / w_sum);
2021            }
2022            if (wb > 0.002) {
2023                wave_res += eval_ocean_train(
2024                    d_merc,
2025                    p_noise_base,
2026                    ocean.train_b.xy,
2027                    ocean.train_b.z,
2028                    ocean.train_b.w,
2029                    wave_scale,
2030                    px_m,
2031                    sea_exposure,
2032                    ocean.train_b_phases0,
2033                    ocean.train_b_phases1,
2034                ) * (wb / w_sum);
2035            }
2036
2037            let eff_wind_speed = (ocean.train_a.z * wa + ocean.train_b.z * wb) / w_sum;
2038            let eff_t = (ocean.train_a.w * wa + ocean.train_b.w * wb) / w_sum;
2039
2040            // Optional Coastal Refracted Breaking Surf & Rhythmic Come-and-Go Beach Swash!
2041            var coastal_foam = 0.0;
2042            var surf_slope = vec2<f32>(0.0);
2043            var swash_cov = 0.0;
2044            var wet_darken = 0.0;
2045            if (use_sdf > 0.01 && shore_dist_norm < 0.96) {
2046                let warp_surf = (n_cw1 - 0.5) * 58.0 + (n_cw2 - 0.5) * 24.0;
2047                let d_eff = max(d_m_raw + warp_surf, 0.0);
2048                let surf_wl = clamp(mix(28.0, 48.0, clamp(eff_wind_speed / 16.0, 0.0, 1.0)), 24.0, 52.0);
2049                let k_surf = 6.2831853 / surf_wl;
2050                // Period ~8-11 s real ocean surf period; +omega*t moves crests INWARD toward the beach.
2051                let omega_surf = sqrt(9.81 * k_surf) * 0.58;
2052
2053                // Blend wave propagation direction toward shoreline only close inside <125m (Snell refraction)
2054                let refract_w = 1.0 - smoothstep(15.0, 125.0, d_eff);
2055                let inc_dir = normalize((ocean.train_a.xy * wa + ocean.train_b.xy * wb) / w_sum + vec2<f32>(1e-4, 0.0));
2056                let prop_to_shore = normalize(mix(inc_dir, shore_dir, clamp(0.35 + 0.65 * refract_w, 0.0, 1.0)));
2057
2058                // Along-shore broken wave-packet envelope breaks continuous rings into organic surf arcs.
2059                let p_along = ocean_noise_wrap(p_noise_base - prop_to_shore * (eff_t * 1.4));
2060                let n_along = pgrad2_periodic_rot(p_along, 1.0 / 256.0, 128.0, vec2<f32>(15.0, 8.0), vec2<f32>(83.1, 47.3)).x;
2061                let crest_patch = smoothstep(0.24, 0.76, n_along);
2062                let set_group = (0.55 + 0.45 * sin(0.22 * k_surf * d_eff + 0.18 * omega_surf * eff_t + n_cw1 * 3.1))
2063                              * (0.45 + 0.90 * crest_patch);
2064                let phase_var = k_surf * d_eff + omega_surf * eff_t + (n_cw1 - 0.5) * 2.4;
2065                let surf_aa = 1.0 - smoothstep(surf_wl * 0.16, surf_wl * 0.55, px_m);
2066
2067                // Subtle refracting shoaling swells & broken whitewater crests inside [10m .. 125m] (no 320m rings).
2068                let shoal_swell_zone = smoothstep(8.0, 24.0, d_m_raw) * (1.0 - smoothstep(65.0, 130.0, d_m_raw));
2069                let breaker_zone = smoothstep(10.0, 26.0, d_m_raw) * (1.0 - smoothstep(55.0, 115.0, d_m_raw));
2070                let s_wave = 0.5 + 0.5 * sin(phase_var);
2071                let crest_line = pow(s_wave, 5.2) * breaker_zone * set_group * surf_aa;
2072                let n_foam = pgrad2_periodic_rot(
2073                    ocean_noise_wrap(p_noise_base + prop_to_shore * (eff_t * 1.1)),
2074                    1.0 / 32.0,
2075                    1024.0,
2076                    vec2<f32>(12.0, 5.0),
2077                    vec2<f32>(119.3, 61.7),
2078                ).x;
2079                let foam_noise = 0.42 + 0.58 * n_foam;
2080                let wake_trail = pow(0.5 + 0.5 * sin(phase_var - 0.70), 2.8) * breaker_zone * set_group * 0.24 * surf_aa;
2081                coastal_foam += (crest_line * 0.72 + wake_trail) * foam_noise * use_sdf * water_mask;
2082                surf_slope += prop_to_shore * (cos(phase_var) * shoal_swell_zone * set_group * 0.042 * surf_aa * use_sdf);
2083
2084                // Rhythmic Come-and-Go Shoreline Swash: washes UP onto wet beach margin (-8.5m) and slides BACK (+34m).
2085                if (swash_margin > 0.01) {
2086                    let swash_ph = omega_surf * 0.76 * eff_t + (n_cw1 - 0.5) * 4.8 + (n_along - 0.5) * 2.6;
2087                    let rush_raw = 0.5 + 0.5 * sin(swash_ph);
2088                    let surge = pow(rush_raw, 0.72);
2089                    let surge_vel = cos(swash_ph);
2090                    let beach_s = d_m_raw - max(sea_elev, -0.25) * 10.0;
2091                    let front_s = mix(34.0, -8.5, surge * clamp(0.68 + 0.52 * n_along, 0.48, 1.22));
2092                    let swash_sheet = smoothstep(front_s - 2.5, front_s + 8.5, beach_s)
2093                                    * (1.0 - smoothstep(34.0, 54.0, d_m_raw))
2094                                    * swash_margin;
2095                    let swash_lip = exp(-pow((beach_s - front_s) / 4.2, 2.0))
2096                                  * (0.58 + 0.42 * max(surge_vel, 0.0))
2097                                  * swash_margin;
2098                    let n_lace = pgrad2_periodic_rot(
2099                        ocean_noise_wrap(p_noise_base - shore_dir * (eff_t * 0.75)),
2100                        1.0 / 16.0,
2101                        2048.0,
2102                        vec2<f32>(8.0, 15.0),
2103                        vec2<f32>(137.5, 91.1),
2104                    ).x;
2105                    let lace = smoothstep(0.26, 0.74, n_lace);
2106                    let foam_amt = (swash_sheet * 0.44 * lace + swash_lip * 0.84) * surf_aa * use_sdf;
2107                    coastal_foam += foam_amt;
2108                    let wet_zone = (1.0 - smoothstep(-8.0, 6.0, -beach_s)) * (1.0 - smoothstep(14.0, 34.0, d_m_raw));
2109                    wet_darken = wet_zone * swash_margin * 0.24 * use_sdf;
2110                    swash_cov = clamp(swash_sheet * 0.62 + swash_lip * 0.90, 0.0, 0.94) * use_sdf;
2111                }
2112            }
2113
2114            let cov_eff = clamp(max(water_mask, swash_cov), 0.0, 1.0);
2115            var raw_slope = (wave_res.xy * wave_strength + surf_slope) * cov_eff;
2116            // Miche breaking-steepness soft limiter caps surface slope cleanly at ~0.40 without flat clipping.
2117            let slope_len = length(raw_slope);
2118            if (slope_len > 0.16) {
2119                let over = slope_len - 0.16;
2120                let capped = 0.16 + 0.24 * (over / (0.24 + over));
2121                raw_slope *= capped / slope_len;
2122            }
2123            let n_water = normalize(up_v - east_v * raw_slope.x - north_v * raw_slope.y);
2124
2125            // Physically based Fresnel sky reflection + deep pelagic water absorption.
2126            let ndotv = max(dot(n_water, view_dir), 0.04);
2127            let f_schlick = 0.02 + 0.98 * pow(1.0 - ndotv, 5.0);
2128            var refl_dir = reflect(-view_dir, n_water);
2129            let refl_up = dot(refl_dir, local_up);
2130            if (refl_up < 0.045) {
2131                refl_dir = normalize(refl_dir + local_up * (0.045 - refl_up));
2132            }
2133            let sky_refl = eval_sky_reflection(refl_dir, local_up, sun_dir, real_sky_w, weather_dark, cloud_cov);
2134
2135            let sun_elev = dot(local_up, sun_dir);
2136            let day_t = smoothstep(-0.08, 0.24, sun_elev);
2137            let water_albedo = mix(
2138                base.rgb * lit * (1.0 - wet_darken),
2139                mix(vec3<f32>(0.014, 0.052, 0.095), vec3<f32>(0.028, 0.135, 0.205), shoal_boost) * max(lit, vec3<f32>(0.12)),
2140                mix(0.28, 0.44, water_mask),
2141            );
2142
2143            // Subsurface turquoise glow through sunlit wave crests & shallow coastal water.
2144            let sss = pow(clamp(wave_res.z * 0.72, 0.0, 1.0), 1.4) * smoothstep(-0.04, 0.30, sun_elev)
2145                    * (0.35 + 0.65 * shoal_boost) * shadow_factor * (1.0 - weather_dark * 0.72);
2146            let sss_col = vec3<f32>(0.04, 0.32, 0.36) * sss * 0.38;
2147
2148            // Crisp GGX-like solar specular glitter path widened softly by distant AA roughness + silver moon glitter.
2149            let half_s = normalize(sun_dir + view_dir);
2150            let ndoth_s = max(dot(n_water, half_s), 0.0);
2151            let rough = clamp(mix(0.06, 0.20, clamp(eff_wind_speed / 22.0, 0.0, 1.0)) + wave_res.w, 0.05, 0.34);
2152            let spec_exp = mix(420.0, 32.0, min(rough * 2.9, 1.0));
2153            let sun_vis_w = smoothstep(-0.03, 0.12, sun_elev) * (1.0 - clamp(weather_dark * 0.85 + cloud_cov * 0.45, 0.0, 0.96));
2154            let sun_spec_col = mix(vec3<f32>(1.0, 0.56, 0.22), vec3<f32>(1.0, 0.97, 0.90), smoothstep(0.0, 0.28, sun_elev));
2155            let sun_glint = sun_spec_col * (pow(ndoth_s, spec_exp) * 2.3 + pow(ndoth_s, 22.0) * 0.15)
2156                          * sun_vis_w * shadow_factor * glint_scale * cov_eff;
2157
2158            var moon_glint = vec3<f32>(0.0);
2159            if (cam.moon_dir.w > 0.5 && sun_elev < 0.02) {
2160                let m_dir = normalize(cam.moon_dir.xyz);
2161                let m_elev = dot(local_up, m_dir);
2162                if (m_elev > 0.02) {
2163                    let half_m = normalize(m_dir + view_dir);
2164                    let ndoth_m = max(dot(n_water, half_m), 0.0);
2165                    let night_w = (1.0 - smoothstep(-0.10, 0.02, sun_elev)) * (1.0 - cloud_cov * 0.75);
2166                    moon_glint = vec3<f32>(0.62, 0.74, 0.92) * pow(ndoth_m, 96.0) * 0.45 * night_w * glint_scale * cov_eff;
2167                }
2168            }
2169
2170            // Open-sea whitecap foam gated by fetch & capped Beaufort curve + coastal surf foam.
2171            let wind_foam_thresh = clamp((eff_wind_speed - 8.0) / 13.0, 0.0, 0.85) * smoothstep(0.25, 0.85, sea_exposure);
2172            let chop_noise = pgrad2_periodic_rot(
2173                ocean_noise_wrap(p_noise_base - ocean.train_a.xy * (eff_t * 1.1)),
2174                1.0 / 32.0,
2175                1024.0,
2176                vec2<f32>(5.0, 12.0),
2177                vec2<f32>(173.1, 23.9),
2178            ).x;
2179            let whitecap = smoothstep(0.62, 1.12, wave_res.z * wave_strength * (0.72 + 0.56 * chop_noise))
2180                         * wind_foam_thresh * 0.52 * water_mask;
2181            let total_foam = clamp(whitecap + coastal_foam, 0.0, 0.86);
2182            let foam_sun_tint = mix(vec3<f32>(0.98, 0.78, 0.62), vec3<f32>(0.94, 0.97, 1.0), smoothstep(0.02, 0.28, sun_elev));
2183            let foam_col = mix(vec3<f32>(0.16, 0.20, 0.28), foam_sun_tint, clamp(day_t * 0.9 + 0.12, 0.12, 1.0))
2184                         * mix(1.0, 0.68, weather_dark);
2185
2186            var ocean_rgb = mix(water_albedo + sss_col, sky_refl, clamp(f_schlick * 0.86 + 0.08, 0.0, 0.90))
2187                          + sun_glint + moon_glint;
2188            ocean_rgb = mix(ocean_rgb, foam_col, total_foam);
2189
2190            let dry_wet_rgb = mix(rgb, rgb * (1.0 - wet_darken), step(0.001, wet_darken));
2191            let ocean_blend = clamp(cov_eff * ocean.blend_params.z * ocean_on, 0.0, 1.0);
2192            rgb = mix(dry_wet_rgb, ocean_rgb, ocean_blend);
2193        }
2194    }
2195
2196    // --- Night City Lights (orbital 3D Black Marble + crisp close-2.5D street illumination) ---
2197    let eff_night_city = max(dn_strength * city_strength, local_lit_blend * night_star_w * city_strength);
2198    if (eff_night_city > 0.001 && on_land > 0.001 && ndotl < 0.06) {
2199        let night_mask = (1.0 - smoothstep(-0.14, 0.06, ndotl)) * eff_night_city * on_land;
2200        if (night_mask > 0.001) {
2201            let eg = env_mask.g;
2202            let base_lin = select(
2203                0.0,
2204                max(eg * eg * (0.75 + 0.25 * eg) - 0.022, 0.0) * 1.0225,
2205                eg > 0.175,
2206            );
2207            var black_marble = base_lin;
2208            let detail_night_w = 1.0 - smoothstep(350.0, 1100.0, px_m);
2209            if (in.night_layer != 0u && detail_night_w > 0.005) {
2210                let nl = i32(in.night_layer);
2211                let luma_w = vec3<f32>(0.299, 0.587, 0.114);
2212                let c0 = dot(textureSampleLevel(terrain_atlas, terrain_sampler, in.night_uv, nl, 0.0).rgb, luma_w);
2213                var raw_tile = c0;
2214                if (c0 > 0.015) {
2215                    let hduv = 0.5 / 256.0;
2216                    let c1 = dot(textureSampleLevel(terrain_atlas, terrain_sampler, clamp(in.night_uv + vec2<f32>(hduv, hduv), vec2<f32>(0.0), vec2<f32>(1.0)), nl, 0.0).rgb, luma_w);
2217                    let c2 = dot(textureSampleLevel(terrain_atlas, terrain_sampler, clamp(in.night_uv - vec2<f32>(hduv, hduv), vec2<f32>(0.0), vec2<f32>(1.0)), nl, 0.0).rgb, luma_w);
2218                    raw_tile = c0 * 0.5 + (c1 + c2) * 0.25;
2219                }
2220                let tile_lin = max(raw_tile - 0.022, 0.0) * 1.0225;
2221                black_marble = mix(base_lin, tile_lin, detail_night_w);
2222            }
2223            if (black_marble > 0.00018) {
2224                let bm_srgb = sqrt(clamp(black_marble, 0.0, 1.0));
2225                let city_core = smoothstep(0.08, 0.48, bm_srgb);
2226                let corridor = smoothstep(0.02, 0.22, bm_srgb) * 0.22;
2227                let orbital_city_w = 1.0 - smoothstep(0.08, 0.82, blend_25d);
2228                let local_city_w = smoothstep(0.12, 0.85, blend_25d);
2229                var pinpoint = 0.86;
2230                var corridor_mod = 0.825;
2231                if (orbital_city_w > 0.01 && px_m < 4500.0) {
2232                    let p2 = vec2<f32>(d.x - d.z * 0.618034, d.y + d.z * 0.618034);
2233                    let med_w = 1.0 - smoothstep(1400.0, 4500.0, px_m);
2234                    let n_block = vnoise2(p2 * 2800.0);
2235                    let n_street = vnoise2(p2 * 10500.0);
2236                    let fine_w = 1.0 - smoothstep(160.0, 1200.0, px_m);
2237                    var sub_grid = 1.0;
2238                    if (fine_w > 0.02) {
2239                        let arterial = smoothstep(0.30, 0.88, vnoise2(p2 * 68000.0));
2240                        let fine_mask = 0.24 + 1.12 * arterial;
2241                        sub_grid = mix(1.0, fine_mask, fine_w);
2242                    }
2243                    let street_grid = smoothstep(0.24, 0.86, n_block * 0.55 + n_street * 0.45);
2244                    let detail_pin = mix(0.62, 1.38, street_grid * (0.62 + 0.38 * n_street)) * sub_grid;
2245                    pinpoint = mix(0.86, detail_pin, med_w);
2246                    corridor_mod = mix(0.825, (0.65 + 0.35 * n_block) * sub_grid, med_w);
2247                }
2248                let orbital_luma = (city_core * pinpoint + corridor * corridor_mod) * night_mask * orbital_city_w * 0.92;
2249                let base_luma = dot(base.rgb, vec3<f32>(0.299, 0.587, 0.114));
2250                let urban_mat = smoothstep(0.18, 0.52, base_luma)
2251                    * (1.0 - smoothstep(0.03, 0.10, base.g - max(base.r, base.b)))
2252                    * (1.0 - smoothstep(0.04, 0.12, base.b - base.r));
2253                let street_hi = smoothstep(0.36, 0.72, base_luma);
2254                let local_luma = (bm_srgb * (0.14 + 0.36 * urban_mat + 0.44 * street_hi))
2255                    * night_mask * local_city_w * 0.58;
2256                let warm_amber = vec3<f32>(0.97, 0.74, 0.38);
2257                let warm_white = vec3<f32>(1.0, 0.90, 0.68);
2258                rgb += mix(warm_amber, warm_white, city_core) * orbital_luma
2259                     + mix(vec3<f32>(0.96, 0.68, 0.32), vec3<f32>(1.0, 0.88, 0.66), street_hi) * local_luma;
2260            }
2261        }
2262    }
2263
2264    // --- Weather- & Sky-Matched Aerial Perspective / Precipitation Mist ---
2265    let morph_fade_2d = 1.0 - smoothstep(0.0, 0.55, map_2d);
2266    if (blend_25d > 0.01 && morph_fade_2d > 0.001) {
2267        let view_dist = length(in.view_rel);
2268        let haze_density = mix(0.000018, 0.00016, weather_haze);
2269        let haze_near = mix(3500.0, 420.0, weather_haze);
2270        let haze_far = mix(52000.0, 9500.0, weather_haze);
2271        let haze_start = smoothstep(haze_near, haze_far, view_dist);
2272        let aerial_haze = clamp((1.0 - exp(-view_dist * haze_density)) * haze_start * blend_25d * mix(0.68, 0.84, weather_haze), 0.0, 0.82) * morph_fade_2d;
2273
2274        let day_scale = clamp(max(cam.sky_bottom.b, max(cam.sky_bottom.r, cam.sky_bottom.g)), 0.0, 1.0);
2275        let classic_haze = vec3<f32>(0.73, 0.85, 0.96) * day_scale * mix(vec3<f32>(1.0), clamp(lit * 1.15, vec3<f32>(0.35), vec3<f32>(1.0)), dn_strength);
2276        let horiz_dir = normalize(in.view_rel - local_up * dot(in.view_rel, local_up) + local_up * 0.02);
2277        let phys_haze = eval_sky_reflection(horiz_dir, local_up, sun_dir, 1.0, weather_dark, cloud_cov);
2278        let horizon_haze_col = mix(classic_haze, phys_haze, max(real_sky_w, weather_haze * 0.65));
2279        rgb = mix(rgb, horizon_haze_col, aerial_haze);
2280    }
2281
2282    if (map_2d > 0.001) {
2283        rgb = mix(rgb, base.rgb, smoothstep(0.0, 0.95, map_2d));
2284    }
2285
2286    return vec4<f32>(rgb, base.a);
2287}
2288
2289@fragment
2290fn fs_terrain_opaque(in: TerrainVsOut) -> @location(0) vec4<f32> {
2291    let sampled = textureSample(terrain_atlas, terrain_sampler, in.uv, i32(in.tex_layer));
2292    return shade_terrain(in, sampled * in.tint);
2293}
2294
2295@fragment
2296fn fs_terrain(in: TerrainVsOut) -> @location(0) vec4<f32> {
2297    let sampled = textureSample(terrain_atlas, terrain_sampler, in.uv, i32(in.tex_layer));
2298    let base = sampled * in.tint;
2299    if (base.a <= 0.001) {
2300        discard;
2301    }
2302    return shade_terrain(in, base);
2303}
2304"#;
2305
2306const TERRAIN_SHADOW_WGSL: &str = r#"
2307struct GpuCameraUniforms {
2308    view_proj_rte: mat4x4<f32>,
2309    inv_view_proj_rte: mat4x4<f32>,
2310    ecef_from_icrf: mat4x4<f32>,
2311    icrf_from_ecef: mat4x4<f32>,
2312    light_view_proj_rte: mat4x4<f32>,
2313    eye_high: vec4<f32>,
2314    eye_low: vec4<f32>,
2315    sun_dir: vec4<f32>,
2316    sun_color: vec4<f32>,
2317    ambient_color: vec4<f32>,
2318    sky_top: vec4<f32>,
2319    sky_bottom: vec4<f32>,
2320    moon_dir: vec4<f32>,
2321    env_params: vec4<f32>,
2322    cloud_params: vec4<f32>,
2323    viewport_wh: vec4<f32>,
2324    atmo_25d_params: vec4<f32>,
2325    weather_opt_params: vec4<f32>,
2326    cloud_tint_params: vec4<f32>,
2327    view_flags: vec4<f32>,
2328}
2329
2330struct GpuTileVertex {
2331    pos_u: vec4<f32>,
2332    norm_v: vec4<f32>,
2333}
2334
2335struct GpuTileInstance {
2336    center_high: vec4<f32>,
2337    center_low: vec4<f32>,
2338    uv_rect: vec4<f32>,
2339    night_uv_rect: vec4<f32>,
2340    tint: vec4<f32>,
2341    tile_meta: vec4<u32>,
2342}
2343
2344@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
2345@group(0) @binding(1) var<storage, read> vertices: array<GpuTileVertex>;
2346@group(0) @binding(2) var<storage, read> instances: array<GpuTileInstance>;
2347
2348@vertex
2349fn vs_terrain_shadow(
2350    @builtin(vertex_index) local_v: u32,
2351    @builtin(instance_index) inst_id: u32,
2352) -> @builtin(position) vec4<f32> {
2353    let inst = instances[inst_id];
2354    let v = vertices[inst.tile_meta.x + local_v];
2355    let center_rel = (inst.center_high.xyz - cam.eye_high.xyz)
2356                   + (inst.center_low.xyz - cam.eye_low.xyz);
2357    let world_rel = center_rel + v.pos_u.xyz;
2358    return cam.light_view_proj_rte * vec4<f32>(world_rel, 1.0);
2359}
2360"#;
2361
2362const CLOUD_SHELL_WGSL: &str = r#"
2363struct GpuCameraUniforms {
2364    view_proj_rte: mat4x4<f32>,
2365    inv_view_proj_rte: mat4x4<f32>,
2366    ecef_from_icrf: mat4x4<f32>,
2367    icrf_from_ecef: mat4x4<f32>,
2368    light_view_proj_rte: mat4x4<f32>,
2369    eye_high: vec4<f32>,
2370    eye_low: vec4<f32>,
2371    sun_dir: vec4<f32>,
2372    sun_color: vec4<f32>,
2373    ambient_color: vec4<f32>,
2374    sky_top: vec4<f32>,
2375    sky_bottom: vec4<f32>,
2376    moon_dir: vec4<f32>,
2377    env_params: vec4<f32>,
2378    cloud_params: vec4<f32>,
2379    viewport_wh: vec4<f32>,
2380    atmo_25d_params: vec4<f32>,
2381    weather_opt_params: vec4<f32>,
2382    cloud_tint_params: vec4<f32>,
2383    view_flags: vec4<f32>,
2384}
2385
2386@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
2387@group(0) @binding(1) var cloud_tex: texture_2d<f32>;
2388@group(0) @binding(2) var cloud_sampler: sampler;
2389@group(0) @binding(3) var cloud_noise_tex: texture_2d<f32>;
2390@group(0) @binding(4) var cloud_noise_sampler: sampler;
2391
2392struct CloudOut {
2393    @builtin(position) clip_pos: vec4<f32>,
2394    @location(0) unit_pos: vec3<f32>,
2395    @location(1) uv_par: vec4<f32>,
2396    @location(2) params_fs: vec4<f32>,
2397    @location(3) light_ts_term: vec4<f32>,
2398    @location(4) view_ts_haze: vec4<f32>,
2399    @location(5) sun_ts_lod: vec4<f32>,
2400    @location(6) grad_step_bic: vec4<f32>,
2401}
2402
2403fn sample_cloud_density(uv: vec2<f32>, lod: f32) -> f32 {
2404    return textureSampleLevel(cloud_tex, cloud_sampler, uv, lod).r;
2405}
2406
2407fn sample_cloud_bicubic_density(uv: vec2<f32>, dims: vec2<f32>, inv_dims: vec2<f32>) -> f32 {
2408    let tc = uv * dims - vec2<f32>(0.5, 0.5);
2409    let i = floor(tc);
2410    let f = clamp(tc - i, vec2<f32>(0.0), vec2<f32>(1.0));
2411    let f2 = f * f;
2412    let f3 = f2 * f;
2413
2414    let omf = vec2<f32>(1.0) - f;
2415    let w0 = omf * omf * omf * (1.0 / 6.0);
2416    let w1 = (3.0 * f3 - 6.0 * f2 + vec2<f32>(4.0)) * (1.0 / 6.0);
2417    let w2 = (-3.0 * f3 + 3.0 * f2 + 3.0 * f + vec2<f32>(1.0)) * (1.0 / 6.0);
2418    let w3 = f3 * (1.0 / 6.0);
2419
2420    let g0 = w0 + w1;
2421    let g1 = w2 + w3;
2422    let u0 = fract((i.x - 0.5 + w1.x / max(g0.x, 1e-5)) * inv_dims.x);
2423    let u1 = fract((i.x + 1.5 + w3.x / max(g1.x, 1e-5)) * inv_dims.x);
2424    let v0 = clamp((i.y - 0.5 + w1.y / max(g0.y, 1e-5)) * inv_dims.y, 0.001, 0.999);
2425    let v1 = clamp((i.y + 1.5 + w3.y / max(g1.y, 1e-5)) * inv_dims.y, 0.001, 0.999);
2426
2427    let c00 = sample_cloud_density(vec2<f32>(u0, v0), 0.0);
2428    let c10 = sample_cloud_density(vec2<f32>(u1, v0), 0.0);
2429    let c01 = sample_cloud_density(vec2<f32>(u0, v1), 0.0);
2430    let c11 = sample_cloud_density(vec2<f32>(u1, v1), 0.0);
2431
2432    let top = mix(c10, c00, g0.x);
2433    let bot = mix(c11, c01, g0.x);
2434    return mix(bot, top, g0.y);
2435}
2436
2437fn cloud_density_to_height(d: f32) -> f32 {
2438    let x = clamp(d, 0.0, 1.0);
2439    let dome = smoothstep(0.06, 0.88, x);
2440    return dome * (0.65 + 0.35 * x * (2.0 - x));
2441}
2442
2443@vertex
2444fn vs_cloud(@location(0) pos_u: vec4<f32>, @location(1) norm_v: vec4<f32>) -> CloudOut {
2445    let base_cloud_r = 6391500.0;
2446    let r_earth = 6378137.0;
2447    let d = normalize(pos_u.xyz);
2448    let eye_pos = cam.eye_high.xyz + cam.eye_low.xyz;
2449    let eye_r = max(length(eye_pos), 1.0);
2450    let eye_alt = max(eye_r - r_earth, 0.0);
2451    let eye_dir = eye_pos / eye_r;
2452    let below_clouds = select(0.0, 1.0, eye_r < base_cloud_r);
2453    let horiz_cos = r_earth / max(eye_r, r_earth);
2454    let above_shell = max(eye_r - base_cloud_r, 0.0);
2455    let vert_disp_w = smoothstep(18000.0, 75000.0, above_shell)
2456        * (1.0 - smoothstep(110000.0, 220000.0, above_shell));
2457
2458    let u_unwrapped = atan2(d.y, d.x) * 0.15915494309 + 0.5;
2459    let v_unwrapped = clamp(0.5 - asin(clamp(d.z, -1.0, 1.0)) * 0.31830988618, 0.001, 0.999);
2460
2461    var cloud_r = base_cloud_r;
2462    if (vert_disp_w > 0.001 && dot(d, eye_dir) > horiz_cos - 0.16) {
2463        let u_v = fract(u_unwrapped + cam.cloud_params.y * 0.15915494309);
2464        let h_vert = cloud_density_to_height(sample_cloud_density(vec2<f32>(u_v, v_unwrapped), 2.5));
2465        cloud_r = mix(base_cloud_r, 6390200.0 + h_vert * 4200.0, vert_disp_w);
2466    }
2467
2468    let world_pos = d * cloud_r;
2469    let world_rel = (world_pos - cam.eye_high.xyz) - cam.eye_low.xyz;
2470    var clip = cam.view_proj_rte * vec4<f32>(world_rel, 1.0);
2471    if (clip.w > 0.0) {
2472        clip.z = min(clip.z, clip.w * 0.9995);
2473    }
2474
2475    let opacity = clamp(cam.cloud_params.x + cam.viewport_wh.w, 0.0, 1.0);
2476    let detail_w = 1.0 - smoothstep(120000.0, 2200000.0, eye_alt);
2477    let mode_25d = smoothstep(0.15, 0.75, clamp(max(detail_w, below_clouds), 0.0, 1.0));
2478    let gate_25d = smoothstep(0.85, 0.995, mode_25d);
2479    let cover_boost = clamp(cam.cloud_tint_params.w, 0.0, 1.0) * below_clouds;
2480    let coarse_gate = mix(0.014, mix(0.212, 0.015, cover_boost), gate_25d);
2481
2482    let shell_pos = d * base_cloud_r;
2483    let view_vec = shell_pos - eye_pos;
2484    let view_dist = max(length(view_vec), 1.0);
2485    let view_dir = view_vec / view_dist;
2486
2487    let above_fade = smoothstep(1500.0, 160000.0, max(eye_r - base_cloud_r, 0.0));
2488    let below_fade = smoothstep(1200.0, 9000.0, max(base_cloud_r - eye_r, 0.0));
2489    let plane_alt_fade = mix(0.24, 1.0, mix(above_fade, below_fade, below_clouds));
2490    let ray_prox_fade = mix(0.78, 1.0, smoothstep(600.0, 10000.0, view_dist));
2491    let horiz_sin = -sqrt(max(eye_r * eye_r - r_earth * r_earth, 0.0)) / max(eye_r, r_earth);
2492    let ray_elev = dot(view_dir, eye_dir) - horiz_sin;
2493    let sky_hemi_fade = mix(1.0, smoothstep(-0.015, 0.035, ray_elev), below_clouds);
2494    let cross_fade = plane_alt_fade * ray_prox_fade * sky_hemi_fade;
2495
2496    let low_alt_factor = 1.0 - smoothstep(40000.0, 350000.0, eye_alt);
2497    let horizon_graze = abs(dot(view_dir, d));
2498    let dist_persp_fade = 1.0 - 0.58 * smoothstep(55000.0, 260000.0, view_dist) * below_clouds;
2499    let horizon_fade = mix(1.0, smoothstep(0.004, 0.055, horizon_graze), low_alt_factor) * dist_persp_fade;
2500
2501    let sun_dir = normalize(cam.sun_dir.xyz);
2502    let ndotl = dot(d, sun_dir);
2503    let dn_strength = clamp(cam.env_params.x, 0.0, 1.0);
2504    let term = smoothstep(-0.14, 0.18, ndotl);
2505    let night_fade = mix(0.14, 1.0, mix(1.0, term, dn_strength));
2506    let lit_mask = mix(night_fade, 1.0, below_clouds);
2507    let layer_translucency = mix(1.0, mix(0.88, 0.96, cover_boost), below_clouds);
2508    let common_alpha = opacity * lit_mask * cross_fade * horizon_fade * layer_translucency;
2509
2510    let east_raw = vec3<f32>(-d.y, d.x, 0.0);
2511    let east_len = length(east_raw);
2512    let t_east = select(vec3<f32>(1.0, 0.0, 0.0), east_raw / max(east_len, 1e-5), east_len > 1e-4);
2513    let t_north = normalize(cross(d, t_east));
2514
2515    let v_east = dot(view_dir, t_east);
2516    let v_north = dot(view_dir, t_north);
2517    let v_up = dot(view_dir, d);
2518    let v_rad = max(abs(v_up), 0.25);
2519    let par_amp = mix(0.0015, 0.00075, mode_25d) / v_rad;
2520    let east_scale = clamp(east_len, 0.25, 1.0);
2521    let par_vec = vec2<f32>(v_east * par_amp * east_scale, v_north * par_amp);
2522
2523    let unlit_key = normalize(d * 0.52 + t_north * 0.62 - t_east * 0.58);
2524    let relief_light = normalize(mix(unlit_key, normalize(sun_dir + d * 0.28), max(dn_strength, cam.atmo_25d_params.x) * 0.75));
2525    let light_ts = vec3<f32>(dot(relief_light, t_east), dot(relief_light, t_north), dot(relief_light, d));
2526    let sun_ts = vec3<f32>(dot(sun_dir, t_east), dot(sun_dir, t_north), ndotl);
2527    let uv_lod = clamp(0.6931472 * smoothstep(2200000.0, 14000000.0, eye_alt), 0.0, 3.0);
2528    let cloud_haze_t = smoothstep(25000.0, 180000.0, view_dist) * 0.65 * below_clouds;
2529
2530    let dims = max(vec2<f32>(textureDimensions(cloud_tex, 0)), vec2<f32>(1.0));
2531    let step_scale = mix(1.75, 1.35, detail_w);
2532    let bicubic_w = 1.0 - smoothstep(70000.0, 220000.0, eye_alt);
2533
2534    var out: CloudOut;
2535    out.clip_pos = clip;
2536    out.unit_pos = d;
2537    out.uv_par = vec4<f32>(u_unwrapped, v_unwrapped, par_vec.x, par_vec.y);
2538    out.params_fs = vec4<f32>(common_alpha, coarse_gate, detail_w, mode_25d);
2539    out.light_ts_term = vec4<f32>(light_ts, term);
2540    out.view_ts_haze = vec4<f32>(v_east, v_north, v_up, cloud_haze_t);
2541    out.sun_ts_lod = vec4<f32>(sun_ts, uv_lod);
2542    out.grad_step_bic = vec4<f32>(step_scale / dims.x, step_scale / dims.y, bicubic_w, below_clouds);
2543    return out;
2544}
2545
2546@fragment
2547fn fs_cloud(in: CloudOut) -> @location(0) vec4<f32> {
2548    let common_alpha = in.params_fs.x;
2549    if (common_alpha <= 0.004) {
2550        return vec4<f32>(0.0);
2551    }
2552
2553    let d = in.unit_pos;
2554    var u_unwrapped = in.uv_par.x;
2555    var v_base = in.uv_par.y;
2556    let d_xy_r = sqrt(max(d.x * d.x + d.y * d.y, 0.0));
2557    if ((d.x < 0.0 && abs(d.y) < max(d_xy_r * 0.45, 0.06)) || abs(d.z) > 0.85) {
2558        let dn = normalize(d);
2559        let az = select(0.0, atan2(dn.y, dn.x), dot(dn.xy, dn.xy) > 1e-10);
2560        u_unwrapped = az * 0.15915494309 + 0.5;
2561        v_base = clamp(0.5 - asin(clamp(dn.z, -1.0, 1.0)) * 0.31830988618, 0.001, 0.999);
2562    }
2563    let u_base = fract(u_unwrapped + cam.cloud_params.y * 0.15915494309);
2564    let uv_lod = in.sun_ts_lod.w;
2565
2566    let cover_boost = clamp(cam.cloud_tint_params.w, 0.0, 1.0) * in.grad_step_bic.w;
2567    let d_coarse = sample_cloud_density(vec2<f32>(u_base, v_base), max(uv_lod, 2.0));
2568    if (d_coarse + cover_boost * 0.65 <= in.params_fs.y) {
2569        return vec4<f32>(0.0);
2570    }
2571
2572    let detail_w = in.params_fs.z;
2573    let mode_25d = in.params_fs.w;
2574    let h_off = cloud_density_to_height(d_coarse) - 0.22;
2575    let u = fract(u_base - in.uv_par.z * h_off);
2576    let v = clamp(v_base + in.uv_par.w * h_off, 0.001, 0.999);
2577
2578    let p_cloud2 = vec2<f32>(d.x - d.z * 0.618034, d.y + d.z * 0.618034);
2579    let noise_uv = p_cloud2 * 26.5625 + vec2<f32>(cam.cloud_params.z * 0.000005625, 0.0);
2580
2581    let d_c_lin = sample_cloud_density(vec2<f32>(u, v), uv_lod);
2582    let d_e = sample_cloud_density(vec2<f32>(fract(u + in.grad_step_bic.x), v), uv_lod);
2583    let d_n = sample_cloud_density(vec2<f32>(u, clamp(v - in.grad_step_bic.y, 0.001, 0.999)), uv_lod);
2584    let ns_all = textureSampleLevel(cloud_noise_tex, cloud_noise_sampler, noise_uv, 0.0);
2585
2586    var d_c_base = d_c_lin;
2587    let bicubic_w = in.grad_step_bic.z;
2588    if (bicubic_w > 0.02) {
2589        let dims = max(vec2<f32>(textureDimensions(cloud_tex, 0)), vec2<f32>(1.0));
2590        d_c_base = mix(d_c_lin, sample_cloud_bicubic_density(vec2<f32>(u, v), dims, 1.0 / dims), bicubic_w);
2591    }
2592    let warp_delta = (ns_all.ba - vec2<f32>(0.5)) * (0.55 * detail_w);
2593    let d_c = clamp(
2594        d_c_base + warp_delta.x * (d_e - d_c_lin) + warp_delta.y * (d_n - d_c_lin) + cover_boost * 0.55,
2595        0.0,
2596        1.0,
2597    );
2598
2599    let crisp_3d = d_c * (0.35 + 0.65 * d_c);
2600    let base_density = 0.56 * d_c + 0.22 * (d_e + d_n);
2601    let clear_cut = smoothstep(0.14, 0.54, base_density);
2602    let fbm = ns_all.x * 0.65 + ns_all.y * 0.35;
2603    let fbm_billow = (fbm - 0.5) * 0.16 * detail_w;
2604    let eroded = clamp(clear_cut * (0.44 + fbm * 1.16) - 0.13, 0.0, 1.0);
2605    let refined = mix(clear_cut, eroded, detail_w * 0.88);
2606
2607    let sigmoid_approx = smoothstep(0.11, 0.75, refined);
2608    let hard_zero_gate = smoothstep(0.13, 0.31, refined);
2609    let mask_25d = clamp(sigmoid_approx * hard_zero_gate * 1.04, 0.0, 1.0);
2610    let mask_density = mix(crisp_3d, mask_25d, mode_25d);
2611
2612    let alpha = mask_density * common_alpha;
2613    if (alpha <= 0.003) {
2614        return vec4<f32>(0.0);
2615    }
2616
2617    let h_c = clamp(cloud_density_to_height(d_c) + fbm_billow, 0.0, 1.0);
2618    let h_e = cloud_density_to_height(d_e);
2619    let h_n = cloud_density_to_height(d_n);
2620    let h_smooth = clamp(0.52 * h_c + 0.24 * (h_e + h_n), 0.0, 1.0);
2621
2622    let normal_amp = mix(3.4, 2.2, detail_w);
2623    let dh_east = (h_e - h_c) * 2.0;
2624    let dh_north = (h_n - h_c) * 2.0;
2625    let n_ts = normalize(vec3<f32>(-dh_east * normal_amp, -dh_north * normal_amp, 1.0));
2626
2627    let light_ts = in.light_ts_term.xyz;
2628    let slope_lit = clamp(dot(n_ts, light_ts), 0.0, 1.0);
2629    let horizon_shadow = clamp(-(dh_east * light_ts.x - dh_north * light_ts.y) * 1.15, -0.28, 0.28);
2630    let height_ao = mix(0.68, 1.06, smoothstep(0.05, 0.85, h_smooth));
2631    let rim_base = 1.0 - clamp(abs(dot(in.view_ts_haze.xyz, n_ts)), 0.0, 1.0);
2632    let silver_rim = (rim_base * rim_base * rim_base)
2633        * smoothstep(0.12, 0.52, d_c)
2634        * (1.0 - smoothstep(0.58, 0.92, d_c))
2635        * 0.18;
2636
2637    let below_clouds = in.grad_step_bic.w;
2638    let relief_factor = clamp(0.55 + slope_lit * 0.45 + horizon_shadow * 0.65, 0.0, 1.0);
2639    let tex_tint = clamp(height_ao * (0.86 + horizon_shadow * 0.45) + silver_rim, 0.68, 1.08);
2640    let shade_base = mix(
2641        vec3<f32>(0.62, 0.69, 0.79),
2642        vec3<f32>(0.995, 0.998, 1.0),
2643        clamp(h_smooth * 0.62 + relief_factor * 0.46, 0.0, 1.0),
2644    ) * tex_tint;
2645    let below_shade = mix(
2646        vec3<f32>(0.70, 0.76, 0.85),
2647        vec3<f32>(0.99, 0.995, 1.0),
2648        clamp((1.0 - h_smooth * 0.35) * 0.45 + relief_factor * 0.55, 0.0, 1.0),
2649    ) * clamp(tex_tint * 1.03, 0.74, 1.06);
2650    let flat_cloud = mix(shade_base, below_shade, below_clouds);
2651
2652    let ndotl = in.sun_ts_lod.z;
2653    let sn = ndotl * 7.5;
2654    let sn2 = sn * sn;
2655    let sunset = (1.0 / (1.0 + sn2 + 0.5 * sn2 * sn2)) * vec3<f32>(0.54, 0.24, 0.09);
2656    let sun_slope = smoothstep(-0.10, 0.65, dot(n_ts, in.sun_ts_lod.xyz));
2657    let term = in.light_ts_term.w;
2658    let dn_strength = clamp(cam.env_params.x, 0.0, 1.0);
2659    let real_sky_w = clamp(cam.atmo_25d_params.x, 0.0, 1.0);
2660    let weather_dark = clamp(cam.weather_opt_params.x, 0.0, 1.0);
2661
2662    let day_cloud = (vec3<f32>(0.04, 0.06, 0.10) + cam.sun_color.rgb * term * mix(0.76, 1.12, sun_slope) + sunset) * tex_tint;
2663    let below_lit_blend = max(dn_strength * (1.0 - below_clouds), real_sky_w * below_clouds);
2664    var rgb = mix(flat_cloud, day_cloud, below_lit_blend);
2665
2666    // Unified Base Weather API cloud storm darkening & tint (bright cumulus -> brooding nimbostratus!).
2667    let storm_dark_w = clamp(weather_dark, 0.0, 1.0) * below_clouds;
2668    if (storm_dark_w > 0.002) {
2669        let day_t = mix(1.0, smoothstep(-0.08, 0.22, ndotl), real_sky_w);
2670        let storm_underbelly = mix(vec3<f32>(0.03, 0.04, 0.06), vec3<f32>(0.24, 0.28, 0.34), day_t)
2671                             * mix(0.76, 1.12, relief_factor);
2672        rgb = mix(rgb, storm_underbelly, storm_dark_w * 0.78);
2673    }
2674    rgb *= cam.cloud_tint_params.xyz;
2675
2676    let cloud_haze_t = in.view_ts_haze.w;
2677    if (cloud_haze_t > 0.001) {
2678        let day_scale = clamp(max(cam.sky_bottom.b, max(cam.sky_bottom.r, cam.sky_bottom.g)), 0.0, 1.0);
2679        let classic_fog = vec3<f32>(0.75, 0.86, 0.96) * day_scale;
2680        let day_t = smoothstep(-0.08, 0.24, ndotl);
2681        let golden_t = exp(-pow((ndotl - 0.03) * 7.5, 2.0));
2682        var phys_fog = mix(vec3<f32>(0.022, 0.036, 0.066), mix(vec3<f32>(0.92, 0.48, 0.20), vec3<f32>(0.72, 0.85, 0.96), smoothstep(0.02, 0.32, ndotl)), day_t)
2683                     + vec3<f32>(0.25, 0.12, 0.06) * golden_t;
2684        phys_fog = mix(phys_fog, vec3<f32>(0.28, 0.32, 0.38) * max(day_t, 0.08), weather_dark * 0.72);
2685        rgb = mix(rgb, mix(classic_fog, phys_fog, real_sky_w), cloud_haze_t);
2686    }
2687
2688    return vec4<f32>(rgb, alpha);
2689}
2690"#;
2691
2692const DYNAMIC_MESH_WGSL: &str = r#"
2693struct GpuCameraUniforms {
2694    view_proj_rte: mat4x4<f32>,
2695    inv_view_proj_rte: mat4x4<f32>,
2696    ecef_from_icrf: mat4x4<f32>,
2697    icrf_from_ecef: mat4x4<f32>,
2698    light_view_proj_rte: mat4x4<f32>,
2699    eye_high: vec4<f32>,
2700    eye_low: vec4<f32>,
2701    sun_dir: vec4<f32>,
2702    sun_color: vec4<f32>,
2703    ambient_color: vec4<f32>,
2704    sky_top: vec4<f32>,
2705    sky_bottom: vec4<f32>,
2706    moon_dir: vec4<f32>,
2707    env_params: vec4<f32>,
2708    cloud_params: vec4<f32>,
2709    viewport_wh: vec4<f32>,
2710    atmo_25d_params: vec4<f32>,
2711    weather_opt_params: vec4<f32>,
2712    cloud_tint_params: vec4<f32>,
2713    view_flags: vec4<f32>,
2714}
2715
2716struct GpuDynamicUniforms {
2717    anchor_high: vec4<f32>,
2718    anchor_low: vec4<f32>,
2719    color: vec4<f32>,
2720    dyn_meta: vec4<u32>,
2721}
2722
2723@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
2724@group(0) @binding(1) var<uniform> dyn_u: GpuDynamicUniforms;
2725
2726struct DynVsOut {
2727    @builtin(position) clip_pos: vec4<f32>,
2728    @location(0) normal: vec3<f32>,
2729    @location(1) color: vec4<f32>,
2730    @location(2) @interpolate(flat) unlit: u32,
2731}
2732
2733@vertex
2734fn vs_dynamic(
2735    @location(0) pos_u: vec4<f32>,
2736    @location(1) norm_v: vec4<f32>,
2737) -> DynVsOut {
2738    let center_rel = (dyn_u.anchor_high.xyz - cam.eye_high.xyz)
2739                   + (dyn_u.anchor_low.xyz - cam.eye_low.xyz);
2740    let world_rel = center_rel + pos_u.xyz;
2741    var out: DynVsOut;
2742    out.clip_pos = cam.view_proj_rte * vec4<f32>(world_rel, 1.0);
2743    out.normal = norm_v.xyz;
2744    out.color = dyn_u.color;
2745    out.unlit = dyn_u.dyn_meta.x;
2746    return out;
2747}
2748
2749@fragment
2750fn fs_dynamic(in: DynVsOut) -> @location(0) vec4<f32> {
2751    if (in.unlit != 0u) {
2752        return in.color;
2753    }
2754    let len_sq = dot(in.normal, in.normal);
2755    let n = select(vec3<f32>(0.0, 1.0, 0.0), normalize(in.normal), len_sq > 0.0001);
2756    let ndotl = max(dot(n, normalize(cam.sun_dir.xyz)), 0.0);
2757    let dn = max(clamp(cam.env_params.x, 0.0, 1.0), clamp(cam.atmo_25d_params.z * cam.env_params.z, 0.0, 1.0));
2758    let flat_lit = vec3<f32>(0.85) + vec3<f32>(0.22) * ndotl;
2759    let day_lit = cam.ambient_color.rgb + cam.sun_color.rgb * ndotl;
2760    let lit = mix(flat_lit, day_lit, dn);
2761    return vec4<f32>(in.color.rgb * lit, in.color.a);
2762}
2763"#;
2764
2765const GEO_OBJECT_WGSL: &str = r#"
2766struct GpuCameraUniforms {
2767    view_proj_rte: mat4x4<f32>,
2768    inv_view_proj_rte: mat4x4<f32>,
2769    ecef_from_icrf: mat4x4<f32>,
2770    icrf_from_ecef: mat4x4<f32>,
2771    light_view_proj_rte: mat4x4<f32>,
2772    eye_high: vec4<f32>,
2773    eye_low: vec4<f32>,
2774    sun_dir: vec4<f32>,
2775    sun_color: vec4<f32>,
2776    ambient_color: vec4<f32>,
2777    sky_top: vec4<f32>,
2778    sky_bottom: vec4<f32>,
2779    moon_dir: vec4<f32>,
2780    env_params: vec4<f32>,
2781    cloud_params: vec4<f32>,
2782    viewport_wh: vec4<f32>,
2783    atmo_25d_params: vec4<f32>,
2784    weather_opt_params: vec4<f32>,
2785    cloud_tint_params: vec4<f32>,
2786    view_flags: vec4<f32>,
2787}
2788
2789struct GpuGeoInstance {
2790    anchor_high: vec4<f32>,
2791    anchor_low: vec4<f32>,
2792    col0: vec4<f32>,
2793    col1: vec4<f32>,
2794    col2: vec4<f32>,
2795    base_color: vec4<f32>,
2796    emissive: vec4<f32>,
2797}
2798
2799@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
2800@group(0) @binding(1) var<storage, read> geo_instances: array<GpuGeoInstance>;
2801@group(1) @binding(0) var shadow_map: texture_depth_2d;
2802@group(1) @binding(1) var shadow_sampler: sampler_comparison;
2803@group(2) @binding(0) var geo_albedo_tex: texture_2d<f32>;
2804@group(2) @binding(1) var geo_albedo_sampler: sampler;
2805
2806struct GeoVsOut {
2807    @builtin(position) clip_pos: vec4<f32>,
2808    @location(0) world_rel: vec3<f32>,
2809    @location(1) normal: vec3<f32>,
2810    @location(2) base_color: vec4<f32>,
2811    @location(3) emissive: vec4<f32>,
2812    @location(4) material_params: vec4<f32>,
2813    @location(5) uv: vec2<f32>,
2814}
2815
2816@vertex
2817fn vs_geo_object(
2818    @location(0) pos_u: vec4<f32>,
2819    @location(1) norm_v: vec4<f32>,
2820    @location(2) vert_color: vec4<f32>,
2821    @builtin(instance_index) inst_idx: u32,
2822) -> GeoVsOut {
2823    let inst = geo_instances[inst_idx];
2824    let c0 = inst.col0.xyz;
2825    let c1 = inst.col1.xyz;
2826    let c2 = inst.col2.xyz;
2827
2828    let center_rel = (inst.anchor_high.xyz - cam.eye_high.xyz)
2829                   + (inst.anchor_low.xyz - cam.eye_low.xyz);
2830    let local_offset = c0 * pos_u.x + c1 * pos_u.y + c2 * pos_u.z;
2831    let world_rel = center_rel + local_offset;
2832
2833    let adj0 = cross(c1, c2);
2834    let adj1 = cross(c2, c0);
2835    let adj2 = cross(c0, c1);
2836    var world_n = adj0 * norm_v.x + adj1 * norm_v.y + adj2 * norm_v.z;
2837    if (dot(world_n, world_n) < 1e-12) {
2838        world_n = c0 * norm_v.x + c1 * norm_v.y + c2 * norm_v.z;
2839    }
2840
2841    var out: GeoVsOut;
2842    out.clip_pos = cam.view_proj_rte * vec4<f32>(world_rel, 1.0);
2843    out.world_rel = world_rel;
2844    out.normal = world_n;
2845    out.base_color = inst.base_color * vert_color;
2846    out.emissive = inst.emissive;
2847    out.material_params = vec4<f32>(inst.col0.w, inst.col1.w, inst.col2.w, norm_v.w);
2848    out.uv = vec2<f32>(pos_u.w, norm_v.w);
2849    return out;
2850}
2851
2852fn sample_geo_shadow(world_rel: vec3<f32>, n: vec3<f32>, sun_dir: vec3<f32>, shadow_radius: f32) -> f32 {
2853    let ndotl = max(dot(n, sun_dir), 0.0);
2854    let normal_bias = max(shadow_radius * 0.0014, 0.35) * (1.2 - 0.7 * ndotl);
2855    let lclip = cam.light_view_proj_rte * vec4<f32>(world_rel + n * normal_bias, 1.0);
2856    let ndc = lclip.xyz / max(lclip.w, 1e-5);
2857    let uv = vec2<f32>(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
2858    let depth_ref = clamp(ndc.z - 0.0005, 0.0, 0.9999);
2859    let dims = max(vec2<f32>(textureDimensions(shadow_map)), vec2<f32>(1.0));
2860    let texel = 1.0 / dims;
2861    var acc = 0.0;
2862    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(-texel.x, -texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
2863    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(texel.x, -texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
2864    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv, vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
2865    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(-texel.x, texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
2866    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(texel.x, texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
2867    let border = max(abs(ndc.x), abs(ndc.y));
2868    let in_bounds = (1.0 - smoothstep(0.84, 0.99, border)) * step(0.0, ndc.z) * step(ndc.z, 1.0);
2869    return mix(1.0, acc * 0.2, in_bounds);
2870}
2871
2872@fragment
2873fn fs_geo_object(in: GeoVsOut) -> @location(0) vec4<f32> {
2874    let tex = textureSample(geo_albedo_tex, geo_albedo_sampler, in.uv);
2875    let tinted = in.base_color * tex;
2876    let accent_t = clamp(in.material_params.w * in.emissive.w, 0.0, 1.0);
2877    let albedo = mix(tinted.rgb, vec3<f32>(0.97, 0.99, 1.0), accent_t);
2878
2879    if (in.material_params.z >= 0.5) {
2880        return vec4<f32>(clamp(albedo + in.emissive.rgb, vec3<f32>(0.0), vec3<f32>(1.0)), tinted.a);
2881    }
2882
2883    let len_sq = dot(in.normal, in.normal);
2884    let n = select(vec3<f32>(0.0, 0.0, 1.0), normalize(in.normal), len_sq > 1e-10);
2885    let view_dir = select(vec3<f32>(0.0, 0.0, 1.0), normalize(-in.world_rel), dot(in.world_rel, in.world_rel) > 1e-8);
2886    let sun_dir = normalize(cam.sun_dir.xyz);
2887
2888    let roughness = clamp(in.material_params.x, 0.05, 1.0);
2889    let metalness = clamp(in.material_params.y, 0.0, 1.0);
2890
2891    let dn = max(clamp(cam.env_params.x, 0.0, 1.0), clamp(cam.atmo_25d_params.z * cam.env_params.z, 0.0, 1.0));
2892    let shadow_w = clamp(cam.atmo_25d_params.w, 0.0, 1.0);
2893    var shadow_f = 1.0;
2894    if (shadow_w > 0.001) {
2895        shadow_f = mix(1.0, sample_geo_shadow(in.world_rel, n, sun_dir, max(cam.weather_opt_params.w, 10.0)), shadow_w * (1.0 - cam.weather_opt_params.x * 0.55));
2896    }
2897
2898    let ndotl_sun = max(dot(n, sun_dir), 0.0) * shadow_f;
2899    let ndotv = max(dot(n, view_dir), 0.0);
2900    let hemi = 0.5 + 0.5 * dot(n, view_dir);
2901
2902    let studio_lit = vec3<f32>(0.42 + 0.24 * hemi) + vec3<f32>(0.52) * max(ndotl_sun, ndotv * 0.65);
2903    let day_lit = cam.ambient_color.rgb * (0.75 + 0.45 * hemi) + cam.sun_color.rgb * ndotl_sun * (1.0 - cam.weather_opt_params.x * 0.55);
2904    let diffuse_light = mix(studio_lit, day_lit, dn);
2905
2906    let half_vec = select(view_dir, normalize(sun_dir + view_dir), dot(sun_dir + view_dir, sun_dir + view_dir) > 1e-6);
2907    let ndoth = max(dot(n, half_vec), 0.0);
2908    let shininess = mix(96.0, 8.0, roughness * roughness);
2909    let spec_strength = (1.0 - roughness * 0.75) * mix(0.22, 0.85, metalness);
2910    let f0 = mix(vec3<f32>(0.04), albedo, metalness);
2911    let spec = f0 * pow(ndoth, shininess) * spec_strength * max(ndotl_sun, 1.0 - dn);
2912
2913    let diffuse_albedo = albedo * (1.0 - metalness * 0.65);
2914    let color = clamp(diffuse_albedo * diffuse_light + spec + in.emissive.rgb, vec3<f32>(0.0), vec3<f32>(1.0));
2915    return vec4<f32>(color, tinted.a);
2916}
2917"#;
2918
2919const GEO_SHADOW_WGSL: &str = r#"
2920struct GpuCameraUniforms {
2921    view_proj_rte: mat4x4<f32>,
2922    inv_view_proj_rte: mat4x4<f32>,
2923    ecef_from_icrf: mat4x4<f32>,
2924    icrf_from_ecef: mat4x4<f32>,
2925    light_view_proj_rte: mat4x4<f32>,
2926    eye_high: vec4<f32>,
2927    eye_low: vec4<f32>,
2928    sun_dir: vec4<f32>,
2929    sun_color: vec4<f32>,
2930    ambient_color: vec4<f32>,
2931    sky_top: vec4<f32>,
2932    sky_bottom: vec4<f32>,
2933    moon_dir: vec4<f32>,
2934    env_params: vec4<f32>,
2935    cloud_params: vec4<f32>,
2936    viewport_wh: vec4<f32>,
2937    atmo_25d_params: vec4<f32>,
2938    weather_opt_params: vec4<f32>,
2939    cloud_tint_params: vec4<f32>,
2940    view_flags: vec4<f32>,
2941}
2942
2943struct GpuGeoInstance {
2944    anchor_high: vec4<f32>,
2945    anchor_low: vec4<f32>,
2946    col0: vec4<f32>,
2947    col1: vec4<f32>,
2948    col2: vec4<f32>,
2949    base_color: vec4<f32>,
2950    emissive: vec4<f32>,
2951}
2952
2953@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
2954@group(0) @binding(1) var<storage, read> geo_instances: array<GpuGeoInstance>;
2955
2956@vertex
2957fn vs_geo_shadow(
2958    @location(0) pos_u: vec4<f32>,
2959    @location(1) norm_v: vec4<f32>,
2960    @builtin(instance_index) inst_idx: u32,
2961) -> @builtin(position) vec4<f32> {
2962    let inst = geo_instances[inst_idx];
2963    let center_rel = (inst.anchor_high.xyz - cam.eye_high.xyz)
2964                   + (inst.anchor_low.xyz - cam.eye_low.xyz);
2965    let local_offset = inst.col0.xyz * pos_u.x + inst.col1.xyz * pos_u.y + inst.col2.xyz * pos_u.z;
2966    return cam.light_view_proj_rte * vec4<f32>(center_rel + local_offset, 1.0);
2967}
2968"#;
2969
2970const PARTICLE_VOLUME_WGSL: &str = r#"
2971struct GpuCameraUniforms {
2972    view_proj_rte: mat4x4<f32>,
2973    inv_view_proj_rte: mat4x4<f32>,
2974    ecef_from_icrf: mat4x4<f32>,
2975    icrf_from_ecef: mat4x4<f32>,
2976    light_view_proj_rte: mat4x4<f32>,
2977    eye_high: vec4<f32>,
2978    eye_low: vec4<f32>,
2979    sun_dir: vec4<f32>,
2980    sun_color: vec4<f32>,
2981    ambient_color: vec4<f32>,
2982    sky_top: vec4<f32>,
2983    sky_bottom: vec4<f32>,
2984    moon_dir: vec4<f32>,
2985    env_params: vec4<f32>,
2986    cloud_params: vec4<f32>,
2987    viewport_wh: vec4<f32>,
2988    atmo_25d_params: vec4<f32>,
2989    weather_opt_params: vec4<f32>,
2990    cloud_tint_params: vec4<f32>,
2991    view_flags: vec4<f32>,
2992}
2993
2994struct GpuParticleLayerUniforms {
2995    basis_east: vec4<f32>,
2996    basis_north: vec4<f32>,
2997    basis_up: vec4<f32>,
2998    forward_bias: vec4<f32>,
2999    cam_right_mpx: vec4<f32>,
3000    cam_up_pad: vec4<f32>,
3001    altitude_bounds: vec4<f32>,
3002    volume_params: vec4<f32>,
3003    motion_params: vec4<f32>,
3004    size_params: vec4<f32>,
3005    flutter_clamp: vec4<f32>,
3006    color: vec4<f32>,
3007    particle_meta: vec4<u32>,
3008}
3009
3010@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
3011@group(0) @binding(1) var<uniform> layer: GpuParticleLayerUniforms;
3012@group(1) @binding(0) var sprite_tex: texture_2d<f32>;
3013@group(1) @binding(1) var sprite_sampler: sampler;
3014
3015struct ParticleVsOut {
3016    @builtin(position) clip_pos: vec4<f32>,
3017    @location(0) uv: vec2<f32>,
3018    @location(1) color: vec4<f32>,
3019    @location(2) @interpolate(flat) sprite_mode: u32,
3020}
3021
3022fn pcg_u32(v: u32) -> u32 {
3023    let state = v * 747796405u + 2891336453u;
3024    let word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;
3025    return (word >> 22u) ^ word;
3026}
3027
3028fn hash01(seed: u32) -> f32 {
3029    return f32(pcg_u32(seed)) * (1.0 / 4294967296.0);
3030}
3031
3032@vertex
3033fn vs_particle(
3034    @builtin(vertex_index) vid: u32,
3035    @builtin(instance_index) inst_idx: u32,
3036) -> ParticleVsOut {
3037    var out: ParticleVsOut;
3038    out.clip_pos = vec4<f32>(2.0, 2.0, 2.0, 1.0);
3039    out.uv = vec2<f32>(0.5, 0.5);
3040    out.color = vec4<f32>(0.0);
3041    out.sprite_mode = layer.particle_meta.x;
3042
3043    let base_seed = inst_idx * 4u + layer.particle_meta.z * 1664525u + 1013904223u;
3044    let r0 = hash01(base_seed + 0u);
3045    let r1 = hash01(base_seed + 1u);
3046    let r2 = hash01(base_seed + 2u);
3047    let r3 = hash01(base_seed + 3u);
3048
3049    let extent_xy = max(layer.volume_params.x, 1.0);
3050    let extent_z = max(layer.volume_params.y, 1.0);
3051    let edge_fade_frac = clamp(layer.volume_params.z, 0.04, 0.48);
3052    let near_fade_m = max(layer.volume_params.w, 0.1);
3053
3054    let u_e = fract(r0 + layer.basis_east.w);
3055    let u_n = fract(r1 + layer.basis_north.w);
3056    let u_z = fract(r2 + layer.basis_up.w);
3057
3058    var rel_e = (u_e - 0.5) * extent_xy;
3059    var rel_n = (u_n - 0.5) * extent_xy;
3060    let rel_z = (u_z - 0.5) * extent_z;
3061
3062    let time_s = layer.motion_params.w;
3063    let flutter_amp = layer.flutter_clamp.x;
3064    if (flutter_amp > 0.0001) {
3065        let flutter_freq = layer.flutter_clamp.y;
3066        let phase = r3 * 6.2831853 + time_s * flutter_freq * (0.72 + 0.56 * fract(r0 * 17.31));
3067        let amp = flutter_amp * (0.55 + 0.90 * r3);
3068        rel_e += sin(phase) * amp;
3069        rel_n += cos(phase * 0.83 + r1 * 6.2831853) * amp;
3070    }
3071
3072    let east = layer.basis_east.xyz;
3073    let north = layer.basis_north.xyz;
3074    let up = layer.basis_up.xyz;
3075    let center_rel = east * rel_e + north * rel_n + up * rel_z + layer.forward_bias.xyz;
3076
3077    let center_clip = cam.view_proj_rte * vec4<f32>(center_rel, 1.0);
3078    if (center_clip.w <= 0.05) {
3079        return out;
3080    }
3081
3082    let dist = max(length(center_rel), 0.05);
3083    let nx = abs(rel_e) / (0.5 * extent_xy);
3084    let ny = abs(rel_n) / (0.5 * extent_xy);
3085    let nz = abs(rel_z) / (0.5 * extent_z);
3086    let box_r = max(max(nx, ny), nz);
3087    let edge_fade = 1.0 - smoothstep(1.0 - edge_fade_frac, 1.0, box_r);
3088    let near_fade = smoothstep(near_fade_m * 0.30, near_fade_m, dist);
3089
3090    // Physical altitude bounds: clip smoothly at ground terrain surface and cloud ceiling.
3091    let bias_alt = dot(layer.forward_bias.xyz, up);
3092    let particle_alt_msl = layer.altitude_bounds.x + rel_z + bias_alt;
3093    let ground_alt_msl = layer.altitude_bounds.y;
3094    let ceiling_alt_msl = layer.altitude_bounds.z;
3095    let ceiling_fade_m = max(layer.altitude_bounds.w, 1.0);
3096    let above_ground = smoothstep(ground_alt_msl - 0.5, ground_alt_msl + 2.5, particle_alt_msl);
3097    let below_ceiling = 1.0 - smoothstep(ceiling_alt_msl - ceiling_fade_m, ceiling_alt_msl, particle_alt_msl);
3098
3099    let alpha_mul = edge_fade * near_fade * above_ground * below_ceiling;
3100    if (alpha_mul <= 0.003 || layer.color.a <= 0.003) {
3101        return out;
3102    }
3103
3104    var corners = array<vec2<f32>, 6>(
3105        vec2<f32>(-1.0, -1.0),
3106        vec2<f32>(1.0, -1.0),
3107        vec2<f32>(1.0, 1.0),
3108        vec2<f32>(-1.0, -1.0),
3109        vec2<f32>(1.0, 1.0),
3110        vec2<f32>(-1.0, 1.0),
3111    );
3112    let corner = corners[vid % 6u];
3113
3114    let cam_right = layer.cam_right_mpx.xyz;
3115    let cam_up = layer.cam_up_pad.xyz;
3116    let m_per_px = dist * max(layer.cam_right_mpx.w, 1e-6);
3117    let min_px = max(layer.flutter_clamp.z, 0.75);
3118    let max_px = max(layer.flutter_clamp.w, min_px);
3119
3120    var right_axis = cam_right;
3121    var up_axis = cam_up;
3122    var hw = 0.05;
3123    var hh = 0.05;
3124    var uv = vec2<f32>(corner.x * 0.5 + 0.5, 0.5 - corner.y * 0.5);
3125
3126    if (layer.particle_meta.y == 0u) {
3127        // VelocityAligned: align streak or far-field curtain vertically along 3D wind + gravity velocity vector.
3128        let fall_v = layer.motion_params.x;
3129        let wind_e = layer.motion_params.y;
3130        let wind_n = layer.motion_params.z;
3131        let vel = east * wind_e + north * wind_n - up * fall_v;
3132        let speed = max(length(vel), 0.05);
3133        let v_dir = vel / speed;
3134        let view_dir = center_rel / dist;
3135        let side_raw = cross(v_dir, view_dir);
3136        let side_len = length(side_raw);
3137        let foreshorten = mix(0.26, 1.0, smoothstep(0.06, 0.42, side_len));
3138
3139        if (side_len > 0.04) {
3140            right_axis = side_raw / side_len;
3141            up_axis = -v_dir;
3142        } else {
3143            right_axis = cam_right;
3144            up_axis = cam_up;
3145        }
3146
3147        let size_var = 0.75 + 0.50 * r3;
3148        let raw_hw = max(layer.size_params.x * 0.5 * size_var, 0.004);
3149        let raw_hh = max((layer.size_params.y + speed * layer.size_params.z) * 0.5 * size_var, raw_hw);
3150        if (layer.particle_meta.x == 4u) {
3151            // ProceduralCurtain: wide translucent rain-shaft / snow-squall veil without narrow streak clamp.
3152            hw = clamp(raw_hw, min_px * 0.5 * m_per_px, max_px * 0.5 * m_per_px);
3153            hh = clamp(raw_hh, min_px * 0.5 * m_per_px, max_px * 0.9 * m_per_px) * mix(0.45, 1.0, foreshorten);
3154        } else {
3155            let max_streak_w_px = min(max_px * 0.12, max(min_px * 2.2, 3.2));
3156            hw = clamp(raw_hw, min_px * 0.5 * m_per_px, max_streak_w_px * 0.5 * m_per_px);
3157            hh = clamp(raw_hh, min_px * 0.5 * m_per_px, max_px * 0.5 * m_per_px) * foreshorten;
3158            hh = max(hh, hw * 1.15);
3159        }
3160        uv = vec2<f32>(corner.x * 0.5 + 0.5, corner.y * 0.5 + 0.5);
3161    } else {
3162        // CameraFacing: 2D camera-aligned billboard with per-particle spin.
3163        let spin_dir = select(-1.0, 1.0, (inst_idx & 1u) == 0u);
3164        let ang = r3 * 6.2831853 + time_s * layer.size_params.w * spin_dir;
3165        let s = sin(ang);
3166        let c = cos(ang);
3167        right_axis = cam_right * c - cam_up * s;
3168        up_axis = cam_right * s + cam_up * c;
3169
3170        let size_var = 0.65 + 0.70 * r3;
3171        let raw_hw = max(layer.size_params.x * 0.5 * size_var, 0.005);
3172        let raw_hh = max(layer.size_params.y * 0.5 * size_var, 0.005);
3173        hw = clamp(raw_hw, min_px * 0.5 * m_per_px, max_px * 0.5 * m_per_px);
3174        hh = clamp(raw_hh, min_px * 0.5 * m_per_px, max_px * 0.5 * m_per_px);
3175        uv = vec2<f32>(corner.x * 0.5 + 0.5, 0.5 - corner.y * 0.5);
3176    }
3177
3178    let world_rel = center_rel + right_axis * (corner.x * hw) + up_axis * (corner.y * hh);
3179    out.clip_pos = cam.view_proj_rte * vec4<f32>(world_rel, 1.0);
3180    out.uv = uv;
3181
3182    // Day/night/sunset lighting tint so precipitation responds naturally to sun elevation.
3183    let dn = max(clamp(cam.env_params.x, 0.0, 1.0), clamp(cam.atmo_25d_params.z * cam.env_params.z, 0.0, 1.0));
3184    let sun_elev = dot(normalize(up), normalize(cam.sun_dir.xyz));
3185    let sun_w = smoothstep(-0.10, 0.28, sun_elev);
3186    let golden_w = exp(-pow((sun_elev - 0.03) * 7.5, 2.0));
3187    let sun_warm = mix(vec3<f32>(1.0, 0.68, 0.42), cam.sun_color.rgb, smoothstep(0.0, 0.28, sun_elev));
3188    let day_lit = mix(
3189        vec3<f32>(0.22, 0.27, 0.38),
3190        cam.ambient_color.rgb * 0.85 + sun_warm * 0.92 + vec3<f32>(0.18, 0.09, 0.03) * golden_w,
3191        sun_w,
3192    );
3193    let lit = mix(vec3<f32>(0.96, 0.98, 1.0), clamp(day_lit, vec3<f32>(0.20), vec3<f32>(1.12)), dn);
3194    let depth_fade = 0.80 + 0.20 * (1.0 - clamp(dist / max(extent_xy, 1.0), 0.0, 1.0));
3195    out.color = vec4<f32>(layer.color.rgb * lit, layer.color.a * alpha_mul * depth_fade);
3196    return out;
3197}
3198
3199@fragment
3200fn fs_particle(in: ParticleVsOut) -> @location(0) vec4<f32> {
3201    let p = in.uv * 2.0 - vec2<f32>(1.0);
3202    let r = length(p);
3203
3204    // Pre-compute simplistic 6-fold mathematical snowflake SDF in uniform control flow for fwidth().
3205    let sector = 1.04719755;
3206    let safe_ang = select(0.0, atan2(p.y, p.x), r > 1e-4);
3207    let folded = abs(safe_ang - sector * floor(safe_ang / sector + 0.5));
3208    let su = r * cos(folded);
3209    let sv = r * sin(folded);
3210    let d_core = r - 0.18;
3211    let spoke_u = clamp(su, 0.0, 0.86);
3212    let d_spoke = length(vec2<f32>(su - spoke_u, sv)) - 0.062;
3213    let b_dir = vec2<f32>(0.5, 0.8660254);
3214    let b_rel = vec2<f32>(su - 0.44, sv);
3215    let b_proj = clamp(dot(b_rel, b_dir), 0.0, 0.29);
3216    let d_branch = length(b_rel - b_dir * b_proj) - 0.048;
3217    let d_crystal = min(d_core, min(d_spoke, d_branch));
3218    let aa_crystal = max(fwidth(d_crystal), 0.045);
3219
3220    var out_col = in.color;
3221    if (in.sprite_mode == 0u) {
3222        let texel = textureSampleLevel(sprite_tex, sprite_sampler, in.uv, 0.0);
3223        out_col = texel * in.color;
3224    } else if (in.sprite_mode == 1u) {
3225        // Pure mathematical tapered 2D raindrop streak.
3226        let t = clamp(in.uv.y, 0.0, 1.0);
3227        let width_prof = mix(0.76, 0.20, smoothstep(0.08, 1.0, t)) * smoothstep(0.0, 0.08, t);
3228        let x_norm = abs(p.x) / max(width_prof, 0.04);
3229        let core = exp(-x_norm * x_norm * 2.5);
3230        let tail_fade = (1.0 - smoothstep(0.14, 1.0, t)) * smoothstep(0.0, 0.06, t);
3231        let head_glint = exp(-((p.y + 0.72) * (p.y + 0.72) * 14.0 + p.x * p.x * 5.5)) * 0.35;
3232        let mask = clamp(core * tail_fade + head_glint * core, 0.0, 1.0);
3233        out_col = vec4<f32>(in.color.rgb + vec3<f32>(head_glint * 0.25), in.color.a * mask);
3234    } else if (in.sprite_mode == 2u) {
3235        // Simplistic mathematical 6-fold 2D snowflake crystal (zero asset files).
3236        let crystal = 1.0 - smoothstep(-aa_crystal, aa_crystal, d_crystal);
3237        let soft_halo = (1.0 - smoothstep(0.18, 0.94, r)) * 0.26;
3238        let mask = clamp(max(crystal, soft_halo), 0.0, 1.0) * (1.0 - smoothstep(0.92, 1.0, r));
3239        out_col = vec4<f32>(in.color.rgb, in.color.a * mask);
3240    } else if (in.sprite_mode == 4u) {
3241        // ProceduralCurtain: ultra-soft atmospheric regional rain-shaft / snow-squall mist veil.
3242        let x_env = exp(-p.x * p.x * 2.4);
3243        let y_env = smoothstep(0.0, 0.34, in.uv.y) * (1.0 - smoothstep(0.62, 1.0, in.uv.y));
3244        let soft_stria = 0.86 + 0.14 * sin(in.uv.x * 9.4248 + in.uv.y * 1.8) * cos(in.uv.x * 15.708 - in.uv.y * 2.4);
3245        let mask = clamp(x_env * y_env * soft_stria, 0.0, 1.0);
3246        out_col = vec4<f32>(in.color.rgb, in.color.a * mask);
3247    } else {
3248        // ProceduralPellet: compact translucent sleet / graupel ice pellet.
3249        let pr = length(vec2<f32>(p.x * 1.18, p.y * 0.85));
3250        let mask = (1.0 - smoothstep(0.35, 0.95, pr));
3251        let glint = exp(-pr * pr * 5.0) * 0.25;
3252        out_col = vec4<f32>(in.color.rgb + vec3<f32>(glint), in.color.a * mask);
3253    }
3254
3255    if (out_col.a <= 0.004) {
3256        discard;
3257    }
3258    return out_col;
3259}
3260"#;
3261
3262const OVERLAY_COMPOSITE_WGSL: &str = r#"
3263@group(0) @binding(0) var overlay_tex: texture_2d<f32>;
3264@group(0) @binding(1) var overlay_sampler: sampler;
3265
3266struct OverlayOut {
3267    @builtin(position) pos: vec4<f32>,
3268    @location(0) uv: vec2<f32>,
3269}
3270
3271@vertex
3272fn vs_overlay(@builtin(vertex_index) vid: u32) -> OverlayOut {
3273    var positions = array<vec2<f32>, 3>(
3274        vec2<f32>(-1.0, -3.0),
3275        vec2<f32>(3.0, 1.0),
3276        vec2<f32>(-1.0, 1.0),
3277    );
3278    let p = positions[vid];
3279    var out: OverlayOut;
3280    out.pos = vec4<f32>(p, 0.0, 1.0);
3281    out.uv = vec2<f32>((p.x + 1.0) * 0.5, (1.0 - p.y) * 0.5);
3282    return out;
3283}
3284
3285@fragment
3286fn fs_overlay(in: OverlayOut) -> @location(0) vec4<f32> {
3287    let c = textureSample(overlay_tex, overlay_sampler, in.uv);
3288    if (c.a <= 0.001) {
3289        return vec4<f32>(0.0);
3290    }
3291    return c;
3292}
3293"#;
3294
3295#[derive(Clone, Copy)]
3296struct SlabEntry {
3297    revision: u64,
3298    offset: u32,
3299    len: u32,
3300    grid_res: u32,
3301    has_skirts: bool,
3302    last_used_frame: u64,
3303}
3304
3305/// Free-list GPU vertex slab allocator holding tile-local RTC vertices across frames.
3306struct GpuTileSlabAllocator {
3307    buffer: wgpu::Buffer,
3308    capacity_vertices: u32,
3309    resident: HashMap<TileKeyId, SlabEntry>,
3310    free_blocks: Vec<(u32, u32)>, // (offset, len)
3311    bump_cursor: u32,
3312}
3313
3314impl GpuTileSlabAllocator {
3315    fn new(device: &wgpu::Device, initial_capacity_vertices: u32) -> Self {
3316        let cap = initial_capacity_vertices.max(65_536);
3317        let buffer = device.create_buffer(&wgpu::BufferDescriptor {
3318            label: Some("strata_earth_tile_vertex_slab"),
3319            size: (cap as u64) * (std::mem::size_of::<RteTileVertex>() as u64),
3320            usage: wgpu::BufferUsages::STORAGE
3321                | wgpu::BufferUsages::COPY_DST
3322                | wgpu::BufferUsages::COPY_SRC,
3323            mapped_at_creation: false,
3324        });
3325        Self {
3326            buffer,
3327            capacity_vertices: cap,
3328            resident: HashMap::new(),
3329            free_blocks: Vec::new(),
3330            bump_cursor: 0,
3331        }
3332    }
3333
3334    fn alloc_range(
3335        &mut self,
3336        device: &wgpu::Device,
3337        queue: &wgpu::Queue,
3338        needed: u32,
3339        current_frame: u64,
3340    ) -> (u32, bool) {
3341        // 1. Reuse best-fit free block.
3342        if let Some((idx, (off, len))) = self
3343            .free_blocks
3344            .iter()
3345            .copied()
3346            .enumerate()
3347            .filter(|(_, (_, l))| *l >= needed)
3348            .min_by_key(|(_, (_, l))| *l)
3349        {
3350            self.free_blocks.swap_remove(idx);
3351            if len > needed {
3352                self.free_blocks.push((off + needed, len - needed));
3353            }
3354            return (off, false);
3355        }
3356
3357        // 2. Bump allocate if space remains.
3358        if self.bump_cursor + needed <= self.capacity_vertices {
3359            let off = self.bump_cursor;
3360            self.bump_cursor += needed;
3361            return (off, false);
3362        }
3363
3364        // 3. Evict LRU tiles not used this frame.
3365        let mut stale: Vec<(TileKeyId, SlabEntry)> = self
3366            .resident
3367            .iter()
3368            .filter(|(_, e)| e.last_used_frame < current_frame)
3369            .map(|(k, e)| (*k, *e))
3370            .collect();
3371        stale.sort_by_key(|(_, e)| e.last_used_frame);
3372
3373        let mut reclaimed = 0u32;
3374        for (k, e) in stale {
3375            self.resident.remove(&k);
3376            self.free_blocks.push((e.offset, e.len));
3377            reclaimed += e.len;
3378            if reclaimed >= needed {
3379                break;
3380            }
3381        }
3382        self.coalesce_free_blocks();
3383
3384        if let Some((idx, (off, len))) = self
3385            .free_blocks
3386            .iter()
3387            .copied()
3388            .enumerate()
3389            .filter(|(_, (_, l))| *l >= needed)
3390            .min_by_key(|(_, (_, l))| *l)
3391        {
3392            self.free_blocks.swap_remove(idx);
3393            if len > needed {
3394                self.free_blocks.push((off + needed, len - needed));
3395            }
3396            return (off, false);
3397        }
3398
3399        // 4. Grow buffer if still tight.
3400        let new_cap = (self.capacity_vertices * 2).max(self.bump_cursor + needed + 65_536);
3401        let new_buf = device.create_buffer(&wgpu::BufferDescriptor {
3402            label: Some("strata_earth_tile_vertex_slab_grown"),
3403            size: (new_cap as u64) * (std::mem::size_of::<RteTileVertex>() as u64),
3404            usage: wgpu::BufferUsages::STORAGE
3405                | wgpu::BufferUsages::COPY_DST
3406                | wgpu::BufferUsages::COPY_SRC,
3407            mapped_at_creation: false,
3408        });
3409        let copy_bytes = (self.bump_cursor as u64) * (std::mem::size_of::<RteTileVertex>() as u64);
3410        if copy_bytes > 0 {
3411            let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
3412                label: Some("strata_earth_slab_grow_copy"),
3413            });
3414            enc.copy_buffer_to_buffer(&self.buffer, 0, &new_buf, 0, copy_bytes);
3415            queue.submit(Some(enc.finish()));
3416        }
3417        self.buffer = new_buf;
3418        self.capacity_vertices = new_cap;
3419        let off = self.bump_cursor;
3420        self.bump_cursor += needed;
3421        (off, true)
3422    }
3423
3424    fn coalesce_free_blocks(&mut self) {
3425        if self.free_blocks.len() < 2 {
3426            return;
3427        }
3428        self.free_blocks.sort_unstable_by_key(|(o, _)| *o);
3429        let mut merged: Vec<(u32, u32)> = Vec::with_capacity(self.free_blocks.len());
3430        for (o, l) in self.free_blocks.drain(..) {
3431            if let Some(last) = merged.last_mut() {
3432                if last.0 + last.1 == o {
3433                    last.1 += l;
3434                    continue;
3435                }
3436            }
3437            merged.push((o, l));
3438        }
3439        // Reclaim tail back into bump_cursor.
3440        while let Some(&(o, l)) = merged.last() {
3441            if o + l == self.bump_cursor {
3442                self.bump_cursor = o;
3443                merged.pop();
3444            } else {
3445                break;
3446            }
3447        }
3448        self.free_blocks = merged;
3449    }
3450
3451    fn upload_meshes(
3452        &mut self,
3453        device: &wgpu::Device,
3454        queue: &wgpu::Queue,
3455        meshes: &[Arc<RetainedTileMesh>],
3456        frame_idx: u64,
3457        budget: usize,
3458    ) -> (bool, bool) {
3459        let mut bind_group_dirty = false;
3460        let mut deferred_any = false;
3461        let mut uploaded = 0usize;
3462
3463        // First mark already-resident entries for visible keys as fresh this frame so LRU never evicts a fallback.
3464        for mesh in meshes {
3465            if let Some(entry) = self.resident.get_mut(&mesh.key) {
3466                if entry.len == mesh.vertices.len() as u32
3467                    && entry.grid_res == mesh.grid_res
3468                    && entry.has_skirts == mesh.has_skirts
3469                {
3470                    entry.last_used_frame = frame_idx;
3471                }
3472            }
3473        }
3474
3475        for mesh in meshes {
3476            let needed = mesh.vertices.len() as u32;
3477            if needed == 0 {
3478                continue;
3479            }
3480            if let Some(entry) = self.resident.get(&mesh.key) {
3481                if entry.revision == mesh.revision
3482                    && entry.len == needed
3483                    && entry.grid_res == mesh.grid_res
3484                    && entry.has_skirts == mesh.has_skirts
3485                {
3486                    continue;
3487                }
3488            }
3489            if uploaded >= budget {
3490                deferred_any = true;
3491                continue;
3492            }
3493            if let Some(old) = self.resident.remove(&mesh.key) {
3494                self.free_blocks.push((old.offset, old.len));
3495                self.coalesce_free_blocks();
3496            }
3497            let (off, grew) = self.alloc_range(device, queue, needed, frame_idx);
3498            if grew {
3499                bind_group_dirty = true;
3500            }
3501            let byte_offset = (off as u64) * (std::mem::size_of::<RteTileVertex>() as u64);
3502            queue.write_buffer(
3503                &self.buffer,
3504                byte_offset,
3505                bytemuck::cast_slice(&mesh.vertices),
3506            );
3507            self.resident.insert(
3508                mesh.key,
3509                SlabEntry {
3510                    revision: mesh.revision,
3511                    offset: off,
3512                    len: needed,
3513                    grid_res: mesh.grid_res,
3514                    has_skirts: mesh.has_skirts,
3515                    last_used_frame: frame_idx,
3516                },
3517            );
3518            uploaded += 1;
3519        }
3520        (bind_group_dirty, deferred_any)
3521    }
3522
3523    fn resident_slot(&self, key: TileKeyId, revision: u64) -> Option<(u32, u32, bool)> {
3524        let entry = self.resident.get(&key)?;
3525        let _ = revision;
3526        Some((entry.offset, entry.grid_res, entry.has_skirts))
3527    }
3528}
3529
3530#[derive(Clone, Copy)]
3531struct AtlasSlot {
3532    tex_id: u64,
3533    revision: u64,
3534    layer: u32,
3535    last_used_frame: u64,
3536}
3537
3538/// LRU `Texture2DArray` tile imagery atlas (layer 0 = solid white fallback).
3539struct GpuImageryAtlas {
3540    _texture: wgpu::Texture,
3541    view: wgpu::TextureView,
3542    slots_by_id: HashMap<u64, AtlasSlot>,
3543    layer_owner: Vec<Option<u64>>,
3544}
3545
3546impl GpuImageryAtlas {
3547    fn new(
3548        device: &wgpu::Device,
3549        queue: &wgpu::Queue,
3550        layers: u32,
3551        color_format: wgpu::TextureFormat,
3552    ) -> Self {
3553        let layers = layers.max(16);
3554        let format = if color_format.is_srgb() {
3555            wgpu::TextureFormat::Rgba8UnormSrgb
3556        } else {
3557            wgpu::TextureFormat::Rgba8Unorm
3558        };
3559        let texture = device.create_texture(&wgpu::TextureDescriptor {
3560            label: Some("strata_earth_imagery_atlas"),
3561            size: wgpu::Extent3d {
3562                width: ATLAS_TILE_SIZE,
3563                height: ATLAS_TILE_SIZE,
3564                depth_or_array_layers: layers,
3565            },
3566            mip_level_count: 1,
3567            sample_count: 1,
3568            dimension: wgpu::TextureDimension::D2,
3569            format,
3570            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
3571            view_formats: &[],
3572        });
3573
3574        // Layer 0: solid white fallback texture.
3575        let white = vec![255u8; (ATLAS_TILE_SIZE * ATLAS_TILE_SIZE * 4) as usize];
3576        Self::write_layer(queue, &texture, 0, ATLAS_TILE_SIZE, ATLAS_TILE_SIZE, &white);
3577
3578        let view = texture.create_view(&wgpu::TextureViewDescriptor {
3579            label: Some("strata_earth_imagery_atlas_view"),
3580            dimension: Some(wgpu::TextureViewDimension::D2Array),
3581            ..Default::default()
3582        });
3583
3584        Self {
3585            _texture: texture,
3586            view,
3587            slots_by_id: HashMap::new(),
3588            layer_owner: vec![None; layers as usize],
3589        }
3590    }
3591
3592    fn write_layer(
3593        queue: &wgpu::Queue,
3594        texture: &wgpu::Texture,
3595        layer: u32,
3596        w: u32,
3597        h: u32,
3598        rgba: &[u8],
3599    ) {
3600        if w == ATLAS_TILE_SIZE
3601            && h == ATLAS_TILE_SIZE
3602            && rgba.len() >= (ATLAS_TILE_SIZE * ATLAS_TILE_SIZE * 4) as usize
3603        {
3604            queue.write_texture(
3605                wgpu::TexelCopyTextureInfo {
3606                    texture,
3607                    mip_level: 0,
3608                    origin: wgpu::Origin3d {
3609                        x: 0,
3610                        y: 0,
3611                        z: layer,
3612                    },
3613                    aspect: wgpu::TextureAspect::All,
3614                },
3615                &rgba[..(ATLAS_TILE_SIZE * ATLAS_TILE_SIZE * 4) as usize],
3616                wgpu::TexelCopyBufferLayout {
3617                    offset: 0,
3618                    bytes_per_row: Some(ATLAS_TILE_SIZE * 4),
3619                    rows_per_image: Some(ATLAS_TILE_SIZE),
3620                },
3621                wgpu::Extent3d {
3622                    width: ATLAS_TILE_SIZE,
3623                    height: ATLAS_TILE_SIZE,
3624                    depth_or_array_layers: 1,
3625                },
3626            );
3627            return;
3628        }
3629        // Nearest/bilinear resample into ATLAS_TILE_SIZE x ATLAS_TILE_SIZE on CPU edge case.
3630        let mut resampled = vec![255u8; (ATLAS_TILE_SIZE * ATLAS_TILE_SIZE * 4) as usize];
3631        if w > 0 && h > 0 && rgba.len() >= (w * h * 4) as usize {
3632            for dy in 0..ATLAS_TILE_SIZE {
3633                let sy = ((dy as u64 * h as u64) / ATLAS_TILE_SIZE as u64).min(h as u64 - 1) as u32;
3634                for dx in 0..ATLAS_TILE_SIZE {
3635                    let sx =
3636                        ((dx as u64 * w as u64) / ATLAS_TILE_SIZE as u64).min(w as u64 - 1) as u32;
3637                    let si = ((sy * w + sx) * 4) as usize;
3638                    let di = ((dy * ATLAS_TILE_SIZE + dx) * 4) as usize;
3639                    resampled[di..di + 4].copy_from_slice(&rgba[si..si + 4]);
3640                }
3641            }
3642        }
3643        queue.write_texture(
3644            wgpu::TexelCopyTextureInfo {
3645                texture,
3646                mip_level: 0,
3647                origin: wgpu::Origin3d {
3648                    x: 0,
3649                    y: 0,
3650                    z: layer,
3651                },
3652                aspect: wgpu::TextureAspect::All,
3653            },
3654            &resampled,
3655            wgpu::TexelCopyBufferLayout {
3656                offset: 0,
3657                bytes_per_row: Some(ATLAS_TILE_SIZE * 4),
3658                rows_per_image: Some(ATLAS_TILE_SIZE),
3659            },
3660            wgpu::Extent3d {
3661                width: ATLAS_TILE_SIZE,
3662                height: ATLAS_TILE_SIZE,
3663                depth_or_array_layers: 1,
3664            },
3665        );
3666    }
3667
3668    fn upload_textures(
3669        &mut self,
3670        queue: &wgpu::Queue,
3671        textures: &[Arc<RetainedTileTexture>],
3672        frame_idx: u64,
3673        budget: usize,
3674    ) -> bool {
3675        for tex in textures {
3676            if let Some(slot) = self.slots_by_id.get_mut(&tex.id) {
3677                if slot.revision == tex.revision {
3678                    slot.last_used_frame = frame_idx;
3679                }
3680            }
3681        }
3682        let mut uploaded = 0usize;
3683        let mut deferred_any = false;
3684        for tex in textures {
3685            if let Some(slot) = self.slots_by_id.get(&tex.id) {
3686                if slot.revision == tex.revision {
3687                    continue;
3688                }
3689            }
3690            if uploaded >= budget {
3691                deferred_any = true;
3692                continue;
3693            }
3694            let target_layer = if let Some(existing) = self.slots_by_id.get(&tex.id) {
3695                existing.layer
3696            } else if let Some((idx, _)) = self
3697                .layer_owner
3698                .iter()
3699                .enumerate()
3700                .skip(1)
3701                .find(|(_, owner)| owner.is_none())
3702            {
3703                idx as u32
3704            } else if let Some((victim_id, victim_layer)) = self
3705                .slots_by_id
3706                .values()
3707                .filter(|s| s.last_used_frame < frame_idx)
3708                .min_by_key(|s| s.last_used_frame)
3709                .map(|s| (s.tex_id, s.layer))
3710            {
3711                self.slots_by_id.remove(&victim_id);
3712                victim_layer
3713            } else {
3714                continue;
3715            };
3716
3717            Self::write_layer(
3718                queue,
3719                &self._texture,
3720                target_layer,
3721                tex.width,
3722                tex.height,
3723                &tex.rgba8,
3724            );
3725            self.layer_owner[target_layer as usize] = Some(tex.id);
3726            self.slots_by_id.insert(
3727                tex.id,
3728                AtlasSlot {
3729                    tex_id: tex.id,
3730                    revision: tex.revision,
3731                    layer: target_layer,
3732                    last_used_frame: frame_idx,
3733                },
3734            );
3735            uploaded += 1;
3736        }
3737        deferred_any
3738    }
3739
3740    #[inline]
3741    fn layer_for(&self, tex_id: Option<u64>, revision: u64) -> u32 {
3742        let Some(id) = tex_id else {
3743            return 0;
3744        };
3745        let _ = revision;
3746        self.slots_by_id.get(&id).map(|s| s.layer).unwrap_or(0)
3747    }
3748}
3749
3750struct CachedIndexTopology {
3751    buffer: wgpu::Buffer,
3752    index_count: u32,
3753}
3754
3755#[repr(C)]
3756#[derive(Clone, Copy, Pod, Zeroable)]
3757struct GpuGeoVertex {
3758    pos_u: [f32; 4],
3759    norm_v: [f32; 4],
3760    color: [f32; 4],
3761}
3762
3763struct CachedDynamicGpuMesh {
3764    revision: u64,
3765    vbuf: wgpu::Buffer,
3766    ibuf: wgpu::Buffer,
3767    index_count: u32,
3768    last_used_seq: u64,
3769}
3770
3771struct CachedGeoGpuMesh {
3772    revision: u64,
3773    vbuf: wgpu::Buffer,
3774    ibuf: wgpu::Buffer,
3775    index_count: u32,
3776    has_vertex_alpha: bool,
3777    albedo_tex_id: Option<u64>,
3778    last_used_seq: u64,
3779}
3780
3781struct CachedGeoTexture {
3782    revision: u64,
3783    width: u32,
3784    height: u32,
3785    has_alpha: bool,
3786    _texture: wgpu::Texture,
3787    bind_group: wgpu::BindGroup,
3788    last_used_seq: u64,
3789}
3790
3791struct OffscreenTarget {
3792    width: u32,
3793    height: u32,
3794    format: wgpu::TextureFormat,
3795    color: wgpu::Texture,
3796    color_view: wgpu::TextureView,
3797    _depth: wgpu::Texture,
3798    depth_view: wgpu::TextureView,
3799    readback: wgpu::Buffer,
3800    padded_bytes_per_row: u32,
3801}
3802
3803struct GpuEnvironmentState {
3804    land_mask_id_rev: Option<(u64, u64)>,
3805    cloud_map_id_rev: Option<(u64, u64)>,
3806    moon_tex_id_rev: Option<(u64, u64)>,
3807    skybox_cube_id_rev: Option<(u64, u64)>,
3808    stars_ptr: usize,
3809    stars_len: usize,
3810    land_mask_view: wgpu::TextureView,
3811    cloud_map_view: wgpu::TextureView,
3812    cloud_noise_view: wgpu::TextureView,
3813    moon_view: wgpu::TextureView,
3814    skybox_cube_view: wgpu::TextureView,
3815    env_sampler: wgpu::Sampler,
3816    cloud_noise_sampler: wgpu::Sampler,
3817    star_buffer: wgpu::Buffer,
3818    star_capacity: usize,
3819    star_count: u32,
3820}
3821
3822struct SrgbDownsampleLuts {
3823    to_lin_div4_scaled: [f32; 256],
3824    to_srgb: [u8; 16384],
3825}
3826
3827fn srgb_downsample_luts() -> &'static SrgbDownsampleLuts {
3828    static LUTS: std::sync::OnceLock<SrgbDownsampleLuts> = std::sync::OnceLock::new();
3829    LUTS.get_or_init(|| {
3830        const MAX_IDX: f32 = 16383.0;
3831        let mut to_lin_div4_scaled = [0.0f32; 256];
3832        for (i, slot) in to_lin_div4_scaled.iter_mut().enumerate() {
3833            let x = i as f32 / 255.0;
3834            let lin = if x <= 0.04045 {
3835                x / 12.92
3836            } else {
3837                ((x + 0.055) / 1.055).powf(2.4)
3838            };
3839            *slot = lin * (0.25 * MAX_IDX);
3840        }
3841        let mut to_srgb = [0u8; 16384];
3842        for (i, slot) in to_srgb.iter_mut().enumerate() {
3843            let x = (i as f32 / MAX_IDX).clamp(0.0, 1.0);
3844            let s = if x <= 0.0031308 {
3845                x * 12.92
3846            } else {
3847                1.055 * x.powf(1.0 / 2.4) - 0.055
3848            };
3849            *slot = (s * 255.0).round().clamp(0.0, 255.0) as u8;
3850        }
3851        SrgbDownsampleLuts {
3852            to_lin_div4_scaled,
3853            to_srgb,
3854        }
3855    })
3856}
3857
3858fn downsample_srgb_rows(
3859    src: &[u8],
3860    w: u32,
3861    h: u32,
3862    nw: u32,
3863    y_start: u32,
3864    out_slice: &mut [u8],
3865    luts: &SrgbDownsampleLuts,
3866) {
3867    let w_usize = w as usize;
3868    let nw_usize = nw as usize;
3869    let row_stride = w_usize * 4;
3870    let lin = &luts.to_lin_div4_scaled;
3871    let srgb = &luts.to_srgb;
3872    let fast_x = w >= nw * 2;
3873    let y_count = out_slice.len() / (nw_usize * 4);
3874
3875    for dy in 0..y_count {
3876        let y = y_start + dy as u32;
3877        let sy0 = (y * 2).min(h - 1) as usize;
3878        let sy1 = (y * 2 + 1).min(h - 1) as usize;
3879        let row0 = &src[sy0 * row_stride..(sy0 + 1) * row_stride];
3880        let row1 = &src[sy1 * row_stride..(sy1 + 1) * row_stride];
3881        let out_row = &mut out_slice[dy * nw_usize * 4..(dy + 1) * nw_usize * 4];
3882
3883        if fast_x {
3884            for x in 0..nw_usize {
3885                let s = x * 8;
3886                let a = &row0[s..s + 8];
3887                let b = &row1[s..s + 8];
3888                let ir = (lin[a[0] as usize]
3889                    + lin[a[4] as usize]
3890                    + lin[b[0] as usize]
3891                    + lin[b[4] as usize]
3892                    + 0.5) as usize;
3893                let ig = (lin[a[1] as usize]
3894                    + lin[a[5] as usize]
3895                    + lin[b[1] as usize]
3896                    + lin[b[5] as usize]
3897                    + 0.5) as usize;
3898                let ib = (lin[a[2] as usize]
3899                    + lin[a[6] as usize]
3900                    + lin[b[2] as usize]
3901                    + lin[b[6] as usize]
3902                    + 0.5) as usize;
3903                let alpha = (a[3] as u32 + a[7] as u32 + b[3] as u32 + b[7] as u32 + 2) >> 2;
3904                let d = x * 4;
3905                out_row[d] = srgb[ir.min(16383)];
3906                out_row[d + 1] = srgb[ig.min(16383)];
3907                out_row[d + 2] = srgb[ib.min(16383)];
3908                out_row[d + 3] = alpha as u8;
3909            }
3910        } else {
3911            for x in 0..nw_usize {
3912                let sx0 = ((x * 2) as u32).min(w - 1) as usize * 4;
3913                let sx1 = ((x * 2 + 1) as u32).min(w - 1) as usize * 4;
3914                let ir = (lin[row0[sx0] as usize]
3915                    + lin[row0[sx1] as usize]
3916                    + lin[row1[sx0] as usize]
3917                    + lin[row1[sx1] as usize]
3918                    + 0.5) as usize;
3919                let ig = (lin[row0[sx0 + 1] as usize]
3920                    + lin[row0[sx1 + 1] as usize]
3921                    + lin[row1[sx0 + 1] as usize]
3922                    + lin[row1[sx1 + 1] as usize]
3923                    + 0.5) as usize;
3924                let ib = (lin[row0[sx0 + 2] as usize]
3925                    + lin[row0[sx1 + 2] as usize]
3926                    + lin[row1[sx0 + 2] as usize]
3927                    + lin[row1[sx1 + 2] as usize]
3928                    + 0.5) as usize;
3929                let alpha = (row0[sx0 + 3] as u32
3930                    + row0[sx1 + 3] as u32
3931                    + row1[sx0 + 3] as u32
3932                    + row1[sx1 + 3] as u32
3933                    + 2)
3934                    >> 2;
3935                let d = x * 4;
3936                out_row[d] = srgb[ir.min(16383)];
3937                out_row[d + 1] = srgb[ig.min(16383)];
3938                out_row[d + 2] = srgb[ib.min(16383)];
3939                out_row[d + 3] = alpha as u8;
3940            }
3941        }
3942    }
3943}
3944
3945fn parallel_downsample_rgba8<F>(w: u32, h: u32, row_fn: F) -> (u32, u32, Vec<u8>)
3946where
3947    F: Fn(u32, &mut [u8]) + Sync,
3948{
3949    let nw = (w / 2).max(1);
3950    let nh = (h / 2).max(1);
3951    let mut out = vec![0u8; (nw as usize) * (nh as usize) * 4];
3952    if nw * nh >= 262_144 && nh >= 64 {
3953        let workers = std::thread::available_parallelism()
3954            .map(|n| n.get())
3955            .unwrap_or(4)
3956            .clamp(2, 6);
3957        let rows_per_chunk = (nh as usize).div_ceil(workers);
3958        let chunk_bytes = rows_per_chunk * (nw as usize) * 4;
3959        std::thread::scope(|s| {
3960            for (chunk_idx, chunk) in out.chunks_mut(chunk_bytes).enumerate() {
3961                let y_start = (chunk_idx * rows_per_chunk) as u32;
3962                let rf = &row_fn;
3963                s.spawn(move || rf(y_start, chunk));
3964            }
3965        });
3966    } else {
3967        row_fn(0, &mut out);
3968    }
3969    (nw, nh, out)
3970}
3971
3972fn downsample_srgb_rgba8_half(src: &[u8], w: u32, h: u32) -> (u32, u32, Vec<u8>) {
3973    let luts = srgb_downsample_luts();
3974    let nw = (w / 2).max(1);
3975    parallel_downsample_rgba8(w, h, |y_start, chunk| {
3976        downsample_srgb_rows(src, w, h, nw, y_start, chunk, luts);
3977    })
3978}
3979
3980fn downsample_linear_rows(
3981    src: &[u8],
3982    w: u32,
3983    h: u32,
3984    nw: u32,
3985    y_start: u32,
3986    out_slice: &mut [u8],
3987) {
3988    let w_usize = w as usize;
3989    let nw_usize = nw as usize;
3990    let row_stride = w_usize * 4;
3991    let fast_x = w >= nw * 2;
3992    let y_count = out_slice.len() / (nw_usize * 4);
3993
3994    for dy in 0..y_count {
3995        let y = y_start + dy as u32;
3996        let sy0 = (y * 2).min(h - 1) as usize;
3997        let sy1 = (y * 2 + 1).min(h - 1) as usize;
3998        let row0 = &src[sy0 * row_stride..(sy0 + 1) * row_stride];
3999        let row1 = &src[sy1 * row_stride..(sy1 + 1) * row_stride];
4000        let out_row = &mut out_slice[dy * nw_usize * 4..(dy + 1) * nw_usize * 4];
4001        if fast_x {
4002            for x in 0..nw_usize {
4003                let s = x * 8;
4004                let a = &row0[s..s + 8];
4005                let b = &row1[s..s + 8];
4006                let d = x * 4;
4007                for c in 0..4 {
4008                    out_row[d + c] =
4009                        ((a[c] as u32 + a[4 + c] as u32 + b[c] as u32 + b[4 + c] as u32 + 2) >> 2)
4010                            as u8;
4011                }
4012            }
4013        } else {
4014            for x in 0..nw_usize {
4015                let sx0 = ((x * 2) as u32).min(w - 1) as usize * 4;
4016                let sx1 = ((x * 2 + 1) as u32).min(w - 1) as usize * 4;
4017                let d = x * 4;
4018                for c in 0..4 {
4019                    out_row[d + c] = ((row0[sx0 + c] as u32
4020                        + row0[sx1 + c] as u32
4021                        + row1[sx0 + c] as u32
4022                        + row1[sx1 + c] as u32
4023                        + 2)
4024                        >> 2) as u8;
4025                }
4026            }
4027        }
4028    }
4029}
4030
4031fn downsample_linear_rgba8_half(src: &[u8], w: u32, h: u32) -> (u32, u32, Vec<u8>) {
4032    let nw = (w / 2).max(1);
4033    parallel_downsample_rgba8(w, h, |y_start, chunk| {
4034        downsample_linear_rows(src, w, h, nw, y_start, chunk);
4035    })
4036}
4037
4038fn downsample_srgb_rgba8_half_single(src: &[u8], w: u32, h: u32) -> (u32, u32, Vec<u8>) {
4039    let luts = srgb_downsample_luts();
4040    let nw = (w / 2).max(1);
4041    let nh = (h / 2).max(1);
4042    let mut out = vec![0u8; (nw as usize) * (nh as usize) * 4];
4043    downsample_srgb_rows(src, w, h, nw, 0, &mut out, luts);
4044    (nw, nh, out)
4045}
4046
4047fn create_rgba8_cube_view(
4048    device: &wgpu::Device,
4049    queue: &wgpu::Queue,
4050    label: &str,
4051    face_size: u32,
4052    faces: &[std::sync::Arc<Vec<u8>>; 6],
4053    format: wgpu::TextureFormat,
4054) -> wgpu::TextureView {
4055    let max_dim = device.limits().max_texture_dimension_2d.max(1);
4056    let mut size = face_size.max(1);
4057    let mut base_override: Option<[Vec<u8>; 6]> = None;
4058
4059    if size > max_dim && size > 1 {
4060        let mut owned: [Vec<u8>; 6] = std::array::from_fn(|i| {
4061            let expected = (size as usize) * (size as usize) * 4;
4062            if faces[i].len() >= expected {
4063                faces[i][..expected].to_vec()
4064            } else {
4065                vec![0u8; expected]
4066            }
4067        });
4068        while size > max_dim && size > 1 {
4069            let cur_size = size;
4070            let mut next_size = size;
4071            let next_owned: [Vec<u8>; 6] = std::thread::scope(|s| {
4072                let handles: [_; 6] = std::array::from_fn(|i| {
4073                    let buf = owned[i].as_slice();
4074                    s.spawn(move || downsample_srgb_rgba8_half_single(buf, cur_size, cur_size))
4075                });
4076                handles.map(|h| {
4077                    let (nw, _, down) = h.join().expect("cube downsample thread panicked");
4078                    next_size = nw;
4079                    down
4080                })
4081            });
4082            owned = next_owned;
4083            size = next_size;
4084        }
4085        base_override = Some(owned);
4086    }
4087
4088    let mip_level_count = if size > 1 {
4089        32 - size.leading_zeros()
4090    } else {
4091        1
4092    };
4093    let tex = device.create_texture(&wgpu::TextureDescriptor {
4094        label: Some(label),
4095        size: wgpu::Extent3d {
4096            width: size,
4097            height: size,
4098            depth_or_array_layers: 6,
4099        },
4100        mip_level_count,
4101        sample_count: 1,
4102        dimension: wgpu::TextureDimension::D2,
4103        format,
4104        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
4105        view_formats: &[],
4106    });
4107
4108    let build_face_mips = |base: &[u8]| -> Vec<(u32, Vec<u8>)> {
4109        let mut mips = Vec::with_capacity((mip_level_count.saturating_sub(1)) as usize);
4110        if mip_level_count <= 1 {
4111            return mips;
4112        }
4113        let expected0 = (size as usize) * (size as usize) * 4;
4114        if base.len() < expected0 {
4115            return mips;
4116        }
4117        let (mut cur_w, _, cur_buf) =
4118            downsample_srgb_rgba8_half_single(&base[..expected0], size, size);
4119        mips.push((cur_w, cur_buf));
4120        for _ in 2..mip_level_count {
4121            let prev = &mips.last().expect("pushed mip").1;
4122            let (nw, _, next) = downsample_srgb_rgba8_half_single(prev, cur_w, cur_w);
4123            cur_w = nw;
4124            mips.push((cur_w, next));
4125        }
4126        mips
4127    };
4128
4129    // Generate mip levels 1..N across all 6 cube faces in parallel without copying mip 0.
4130    let base_refs: [&[u8]; 6] = match &base_override {
4131        Some(owned) => std::array::from_fn(|i| owned[i].as_slice()),
4132        None => std::array::from_fn(|i| faces[i].as_slice()),
4133    };
4134    let extra_mips: [Vec<(u32, Vec<u8>)>; 6] = if mip_level_count > 1 && size >= 64 {
4135        let _ = srgb_downsample_luts();
4136        std::thread::scope(|s| {
4137            let handles: [_; 6] = std::array::from_fn(|i| {
4138                let base = base_refs[i];
4139                s.spawn(move || build_face_mips(base))
4140            });
4141            handles.map(|h| h.join().expect("cube mip thread panicked"))
4142        })
4143    } else {
4144        std::array::from_fn(|i| build_face_mips(base_refs[i]))
4145    };
4146
4147    for layer in 0..6u32 {
4148        let expected0 = (size as usize) * (size as usize) * 4;
4149        if base_refs[layer as usize].len() >= expected0 {
4150            queue.write_texture(
4151                wgpu::TexelCopyTextureInfo {
4152                    texture: &tex,
4153                    mip_level: 0,
4154                    origin: wgpu::Origin3d {
4155                        x: 0,
4156                        y: 0,
4157                        z: layer,
4158                    },
4159                    aspect: wgpu::TextureAspect::All,
4160                },
4161                &base_refs[layer as usize][..expected0],
4162                wgpu::TexelCopyBufferLayout {
4163                    offset: 0,
4164                    bytes_per_row: Some(size * 4),
4165                    rows_per_image: Some(size),
4166                },
4167                wgpu::Extent3d {
4168                    width: size,
4169                    height: size,
4170                    depth_or_array_layers: 1,
4171                },
4172            );
4173        }
4174        for (idx, (mip_w, buf)) in extra_mips[layer as usize].iter().enumerate() {
4175            let mip = (idx + 1) as u32;
4176            let expected = (*mip_w as usize) * (*mip_w as usize) * 4;
4177            if buf.len() >= expected {
4178                queue.write_texture(
4179                    wgpu::TexelCopyTextureInfo {
4180                        texture: &tex,
4181                        mip_level: mip,
4182                        origin: wgpu::Origin3d {
4183                            x: 0,
4184                            y: 0,
4185                            z: layer,
4186                        },
4187                        aspect: wgpu::TextureAspect::All,
4188                    },
4189                    &buf[..expected],
4190                    wgpu::TexelCopyBufferLayout {
4191                        offset: 0,
4192                        bytes_per_row: Some(*mip_w * 4),
4193                        rows_per_image: Some(*mip_w),
4194                    },
4195                    wgpu::Extent3d {
4196                        width: *mip_w,
4197                        height: *mip_w,
4198                        depth_or_array_layers: 1,
4199                    },
4200                );
4201            }
4202        }
4203    }
4204
4205    tex.create_view(&wgpu::TextureViewDescriptor {
4206        label: Some(label),
4207        dimension: Some(wgpu::TextureViewDimension::Cube),
4208        ..Default::default()
4209    })
4210}
4211
4212#[derive(Clone, Copy)]
4213enum MipGenMode {
4214    Srgb,
4215    LinearBox,
4216}
4217
4218fn create_rgba8_2d_view(
4219    device: &wgpu::Device,
4220    queue: &wgpu::Queue,
4221    label: &str,
4222    width: u32,
4223    height: u32,
4224    rgba: &[u8],
4225) -> wgpu::TextureView {
4226    create_rgba8_2d_view_opts(device, queue, label, width, height, rgba, MipGenMode::Srgb)
4227}
4228
4229fn create_rgba8_2d_view_opts(
4230    device: &wgpu::Device,
4231    queue: &wgpu::Queue,
4232    label: &str,
4233    width: u32,
4234    height: u32,
4235    rgba: &[u8],
4236    mip_mode: MipGenMode,
4237) -> wgpu::TextureView {
4238    let max_dim = device.limits().max_texture_dimension_2d.max(1);
4239    let mut w = width.max(1);
4240    let mut h = height.max(1);
4241    let mut scaled: Option<Vec<u8>> = None;
4242    let initial_expected = (w as usize) * (h as usize) * 4;
4243    if rgba.len() >= initial_expected && (w > max_dim || h > max_dim) {
4244        let mut buf = rgba[..initial_expected].to_vec();
4245        while (w > max_dim || h > max_dim) && w > 1 && h > 1 {
4246            let (nw, nh, next) = match mip_mode {
4247                MipGenMode::LinearBox => downsample_linear_rgba8_half(&buf, w, h),
4248                MipGenMode::Srgb => downsample_srgb_rgba8_half(&buf, w, h),
4249            };
4250            w = nw;
4251            h = nh;
4252            buf = next;
4253        }
4254        scaled = Some(buf);
4255    }
4256    let data: &[u8] = scaled.as_deref().unwrap_or(rgba);
4257
4258    let expected = (w as usize) * (h as usize) * 4;
4259    let max_mips = if matches!(mip_mode, MipGenMode::LinearBox) {
4260        6
4261    } else {
4262        5
4263    };
4264    let mip_level_count = if data.len() >= expected && w >= 64 && h >= 64 {
4265        (32 - w.min(h).leading_zeros()).min(max_mips)
4266    } else {
4267        1
4268    };
4269
4270    let tex = device.create_texture(&wgpu::TextureDescriptor {
4271        label: Some(label),
4272        size: wgpu::Extent3d {
4273            width: w,
4274            height: h,
4275            depth_or_array_layers: 1,
4276        },
4277        mip_level_count,
4278        sample_count: 1,
4279        dimension: wgpu::TextureDimension::D2,
4280        format: wgpu::TextureFormat::Rgba8Unorm,
4281        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
4282        view_formats: &[],
4283    });
4284    if data.len() >= expected {
4285        let mut cur_w = w;
4286        let mut cur_h = h;
4287        let mut mip_owned: Option<Vec<u8>> = None;
4288        for mip in 0..mip_level_count {
4289            let mip_bytes = mip_owned.as_deref().unwrap_or(&data[..expected]);
4290            let mip_exp = (cur_w as usize) * (cur_h as usize) * 4;
4291            if mip_bytes.len() >= mip_exp {
4292                queue.write_texture(
4293                    wgpu::TexelCopyTextureInfo {
4294                        texture: &tex,
4295                        mip_level: mip,
4296                        origin: wgpu::Origin3d::ZERO,
4297                        aspect: wgpu::TextureAspect::All,
4298                    },
4299                    &mip_bytes[..mip_exp],
4300                    wgpu::TexelCopyBufferLayout {
4301                        offset: 0,
4302                        bytes_per_row: Some(cur_w * 4),
4303                        rows_per_image: Some(cur_h),
4304                    },
4305                    wgpu::Extent3d {
4306                        width: cur_w,
4307                        height: cur_h,
4308                        depth_or_array_layers: 1,
4309                    },
4310                );
4311            }
4312            if mip + 1 < mip_level_count {
4313                let (nw, nh, next) = match mip_mode {
4314                    MipGenMode::LinearBox => downsample_linear_rgba8_half(mip_bytes, cur_w, cur_h),
4315                    MipGenMode::Srgb => downsample_srgb_rgba8_half(mip_bytes, cur_w, cur_h),
4316                };
4317                cur_w = nw;
4318                cur_h = nh;
4319                mip_owned = Some(next);
4320            }
4321        }
4322    }
4323    tex.create_view(&Default::default())
4324}
4325
4326fn downsample_cloud_r8_half(src: &[u8], w: u32, h: u32) -> (u32, u32, Vec<u8>) {
4327    let nw = (w / 2).max(1);
4328    let nh = (h / 2).max(1);
4329    let mut out = vec![0u8; (nw as usize) * (nh as usize)];
4330    let w_usize = w as usize;
4331    let nw_usize = nw as usize;
4332    for y in 0..(nh as usize) {
4333        let y0 = ((y * 2) as u32).min(h - 1) as usize * w_usize;
4334        let y1 = ((y * 2 + 1) as u32).min(h - 1) as usize * w_usize;
4335        let out_row = &mut out[y * nw_usize..(y + 1) * nw_usize];
4336        for (x, dst) in out_row.iter_mut().enumerate() {
4337            let x0 = ((x * 2) as u32).min(w - 1) as usize;
4338            let x1 = ((x * 2 + 1) as u32).min(w - 1) as usize;
4339            let a = src[y0 + x0] as u32;
4340            let b = src[y0 + x1] as u32;
4341            let c = src[y1 + x0] as u32;
4342            let d = src[y1 + x1] as u32;
4343            let avg = (a + b + c + d + 2) >> 2;
4344            let m = a.max(b).max(c).max(d);
4345            *dst = ((avg * 7 + m + 4) >> 3) as u8;
4346        }
4347    }
4348    (nw, nh, out)
4349}
4350
4351fn create_cloud_density_r8_view(
4352    device: &wgpu::Device,
4353    queue: &wgpu::Queue,
4354    label: &str,
4355    width: u32,
4356    height: u32,
4357    rgba: &[u8],
4358) -> wgpu::TextureView {
4359    let max_dim = device.limits().max_texture_dimension_2d.max(1);
4360    let mut w = width.max(1);
4361    let mut h = height.max(1);
4362    let initial_px = (w as usize) * (h as usize);
4363    let mut r8 = vec![0u8; initial_px];
4364    if rgba.len() >= initial_px * 4 {
4365        for (i, px) in rgba[..initial_px * 4].chunks_exact(4).enumerate() {
4366            let r = px[0];
4367            let g = px[1];
4368            let b = px[2];
4369            let a = px[3];
4370            if a == 255 {
4371                r8[i] = ((77 * r as u32 + 150 * g as u32 + 29 * b as u32 + 128) >> 8) as u8;
4372            } else if a > 0 {
4373                let inv = 1.0 / 255.0;
4374                let af = a as f32 * inv;
4375                let luma = (0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32) * inv;
4376                let t = ((af - 0.97) * (1.0 / 0.029)).clamp(0.0, 1.0);
4377                let sm = t * t * (3.0 - 2.0 * t);
4378                let d = af * (luma * sm + (1.0 - sm));
4379                r8[i] = (d.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
4380            }
4381        }
4382    }
4383    while (w > max_dim || h > max_dim) && w > 1 && h > 1 {
4384        let (nw, nh, next) = downsample_cloud_r8_half(&r8, w, h);
4385        w = nw;
4386        h = nh;
4387        r8 = next;
4388    }
4389
4390    let mip_level_count = if w >= 64 && h >= 64 {
4391        (32 - w.min(h).leading_zeros()).min(6)
4392    } else {
4393        1
4394    };
4395    let tex = device.create_texture(&wgpu::TextureDescriptor {
4396        label: Some(label),
4397        size: wgpu::Extent3d {
4398            width: w,
4399            height: h,
4400            depth_or_array_layers: 1,
4401        },
4402        mip_level_count,
4403        sample_count: 1,
4404        dimension: wgpu::TextureDimension::D2,
4405        format: wgpu::TextureFormat::R8Unorm,
4406        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
4407        view_formats: &[],
4408    });
4409
4410    let mut cur_w = w;
4411    let mut cur_h = h;
4412    let mut cur_buf = r8;
4413    for mip in 0..mip_level_count {
4414        let mip_exp = (cur_w as usize) * (cur_h as usize);
4415        if cur_buf.len() >= mip_exp {
4416            queue.write_texture(
4417                wgpu::TexelCopyTextureInfo {
4418                    texture: &tex,
4419                    mip_level: mip,
4420                    origin: wgpu::Origin3d::ZERO,
4421                    aspect: wgpu::TextureAspect::All,
4422                },
4423                &cur_buf[..mip_exp],
4424                wgpu::TexelCopyBufferLayout {
4425                    offset: 0,
4426                    bytes_per_row: Some(cur_w),
4427                    rows_per_image: Some(cur_h),
4428                },
4429                wgpu::Extent3d {
4430                    width: cur_w,
4431                    height: cur_h,
4432                    depth_or_array_layers: 1,
4433                },
4434            );
4435        }
4436        if mip + 1 < mip_level_count {
4437            let (nw, nh, next) = downsample_cloud_r8_half(&cur_buf, cur_w, cur_h);
4438            cur_w = nw;
4439            cur_h = nh;
4440            cur_buf = next;
4441        }
4442    }
4443    tex.create_view(&Default::default())
4444}
4445
4446fn create_cloud_noise_lut_view(device: &wgpu::Device, queue: &wgpu::Queue) -> wgpu::TextureView {
4447    const DIM: u32 = 128;
4448    let hash_cell = |ix: u32, iy: u32, period: u32, seed: u32| -> f32 {
4449        let x = ix % period;
4450        let y = iy % period;
4451        let mut h = x
4452            .wrapping_mul(0x9e37_79b1)
4453            .wrapping_add(y.wrapping_mul(0x85eb_ca77))
4454            .wrapping_add(seed.wrapping_mul(0xc2b2_ae3d));
4455        h ^= h >> 16;
4456        h = h.wrapping_mul(0x27d4_eb2f);
4457        h ^= h >> 15;
4458        (h & 0xffff) as f32 * (1.0 / 65535.0)
4459    };
4460    let sample_periodic = |u: f32, v: f32, period: u32, seed: u32| -> u8 {
4461        let x = u * (period as f32);
4462        let y = v * (period as f32);
4463        let ix = x.floor() as u32;
4464        let iy = y.floor() as u32;
4465        let fx = x - x.floor();
4466        let fy = y - y.floor();
4467        let ux = fx * fx * (3.0 - 2.0 * fx);
4468        let uy = fy * fy * (3.0 - 2.0 * fy);
4469        let n00 = hash_cell(ix, iy, period, seed);
4470        let n10 = hash_cell(ix + 1, iy, period, seed);
4471        let n01 = hash_cell(ix, iy + 1, period, seed);
4472        let n11 = hash_cell(ix + 1, iy + 1, period, seed);
4473        let nx0 = n00 + (n10 - n00) * ux;
4474        let nx1 = n01 + (n11 - n01) * ux;
4475        let val = nx0 + (nx1 - nx0) * uy;
4476        (val.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
4477    };
4478
4479    let mut rgba = vec![0u8; (DIM * DIM * 4) as usize];
4480    let inv = 1.0 / (DIM as f32);
4481    for y in 0..DIM {
4482        let v = (y as f32 + 0.5) * inv;
4483        for x in 0..DIM {
4484            let u = (x as f32 + 0.5) * inv;
4485            let idx = ((y * DIM + x) * 4) as usize;
4486            rgba[idx] = sample_periodic(u, v, 32, 1);
4487            rgba[idx + 1] = sample_periodic(u, v, 96, 2);
4488            rgba[idx + 2] = sample_periodic(u, v, 32, 3);
4489            rgba[idx + 3] = sample_periodic(u, v, 32, 4);
4490        }
4491    }
4492
4493    let tex = device.create_texture(&wgpu::TextureDescriptor {
4494        label: Some("strata_env_cloud_noise_lut"),
4495        size: wgpu::Extent3d {
4496            width: DIM,
4497            height: DIM,
4498            depth_or_array_layers: 1,
4499        },
4500        mip_level_count: 1,
4501        sample_count: 1,
4502        dimension: wgpu::TextureDimension::D2,
4503        format: wgpu::TextureFormat::Rgba8Unorm,
4504        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
4505        view_formats: &[],
4506    });
4507    queue.write_texture(
4508        wgpu::TexelCopyTextureInfo {
4509            texture: &tex,
4510            mip_level: 0,
4511            origin: wgpu::Origin3d::ZERO,
4512            aspect: wgpu::TextureAspect::All,
4513        },
4514        &rgba,
4515        wgpu::TexelCopyBufferLayout {
4516            offset: 0,
4517            bytes_per_row: Some(DIM * 4),
4518            rows_per_image: Some(DIM),
4519        },
4520        wgpu::Extent3d {
4521            width: DIM,
4522            height: DIM,
4523            depth_or_array_layers: 1,
4524        },
4525    );
4526    tex.create_view(&Default::default())
4527}
4528
4529fn build_unit_icosphere(subdivisions: u32) -> (Vec<RteTileVertex>, Vec<u32>) {
4530    let t = (1.0f32 + 5.0f32.sqrt()) * 0.5;
4531    let raw = [
4532        [-1.0, t, 0.0],
4533        [1.0, t, 0.0],
4534        [-1.0, -t, 0.0],
4535        [1.0, -t, 0.0],
4536        [0.0, -1.0, t],
4537        [0.0, 1.0, t],
4538        [0.0, -1.0, -t],
4539        [0.0, 1.0, -t],
4540        [t, 0.0, -1.0],
4541        [t, 0.0, 1.0],
4542        [-t, 0.0, -1.0],
4543        [-t, 0.0, 1.0],
4544    ];
4545    let norm = |p: [f32; 3]| -> [f32; 3] {
4546        let l = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt().max(1e-6);
4547        [p[0] / l, p[1] / l, p[2] / l]
4548    };
4549    let mut verts: Vec<[f32; 3]> = raw.iter().map(|p| norm(*p)).collect();
4550    let mut tris: Vec<[u32; 3]> = vec![
4551        [0, 11, 5],
4552        [0, 5, 1],
4553        [0, 1, 7],
4554        [0, 7, 10],
4555        [0, 10, 11],
4556        [1, 5, 9],
4557        [5, 11, 4],
4558        [11, 10, 2],
4559        [10, 7, 6],
4560        [7, 1, 8],
4561        [3, 9, 4],
4562        [3, 4, 2],
4563        [3, 2, 6],
4564        [3, 6, 8],
4565        [3, 8, 9],
4566        [4, 9, 5],
4567        [2, 4, 11],
4568        [6, 2, 10],
4569        [8, 6, 7],
4570        [9, 8, 1],
4571    ];
4572
4573    for _ in 0..subdivisions {
4574        let mut mid_cache: HashMap<(u32, u32), u32> = HashMap::new();
4575        let mut get_mid = |a: u32, b: u32, vs: &mut Vec<[f32; 3]>| -> u32 {
4576            let key = if a < b { (a, b) } else { (b, a) };
4577            if let Some(&idx) = mid_cache.get(&key) {
4578                return idx;
4579            }
4580            let pa = vs[a as usize];
4581            let pb = vs[b as usize];
4582            let m = norm([
4583                (pa[0] + pb[0]) * 0.5,
4584                (pa[1] + pb[1]) * 0.5,
4585                (pa[2] + pb[2]) * 0.5,
4586            ]);
4587            let idx = vs.len() as u32;
4588            vs.push(m);
4589            mid_cache.insert(key, idx);
4590            idx
4591        };
4592        let mut next_tris = Vec::with_capacity(tris.len() * 4);
4593        for [a, b, c] in tris {
4594            let ab = get_mid(a, b, &mut verts);
4595            let bc = get_mid(b, c, &mut verts);
4596            let ca = get_mid(c, a, &mut verts);
4597            next_tris.push([a, ab, ca]);
4598            next_tris.push([b, bc, ab]);
4599            next_tris.push([c, ca, bc]);
4600            next_tris.push([ab, bc, ca]);
4601        }
4602        tris = next_tris;
4603    }
4604
4605    let rte_verts: Vec<RteTileVertex> = verts
4606        .into_iter()
4607        .map(|p| RteTileVertex::new(p, p, [0.0, 0.0]))
4608        .collect();
4609    let mut indices = Vec::with_capacity(tris.len() * 3);
4610    for [a, b, c] in tris {
4611        indices.push(a);
4612        indices.push(b);
4613        indices.push(c);
4614    }
4615    (rte_verts, indices)
4616}
4617
4618struct CachedParticleTexture {
4619    revision: u64,
4620    width: u32,
4621    height: u32,
4622    _texture: wgpu::Texture,
4623    bind_group: wgpu::BindGroup,
4624}
4625
4626/// Hardware GPU pass durations resolved asynchronously from `wgpu::Features::TIMESTAMP_QUERY`.
4627#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
4628pub struct GpuPassTimings {
4629    /// True when the active adapter/device supports `wgpu::Features::TIMESTAMP_QUERY`.
4630    pub supported: bool,
4631    /// Directional shadow-map pass duration on GPU (microseconds).
4632    pub shadow_pass_us: u32,
4633    /// Main 3D scene pass (terrain/atmosphere/ocean/buildings/clouds/objects) duration on GPU (microseconds).
4634    pub scene_3d_pass_us: u32,
4635    /// Standalone 2D overlay / cached-3D blit+composite pass duration on GPU (microseconds).
4636    pub overlay_pass_us: u32,
4637    /// Combined 3D GPU duration (`shadow_pass_us + scene_3d_pass_us`).
4638    pub total_3d_gpu_us: u32,
4639}
4640
4641const GPU_TS_SLOTS: usize = 3;
4642const GPU_TS_QUERY_COUNT: u32 = 6; // [0..2]=shadow, [2..4]=main 3D, [4..6]=overlay/blit
4643const GPU_TS_RESOLVE_STRIDE: u64 = 256; // WebGPU QUERY_RESOLVE_BUFFER_ALIGNMENT
4644
4645struct TimestampSlot {
4646    query_set: wgpu::QuerySet,
4647    resolve_buffer: wgpu::Buffer,
4648    readback_buffer: wgpu::Buffer,
4649    mapped_ready: Arc<std::sync::atomic::AtomicBool>,
4650    in_flight: bool,
4651    wrote_shadow: bool,
4652    wrote_main: bool,
4653    wrote_overlay: bool,
4654}
4655
4656struct GpuTimestampProfiler {
4657    slots: Vec<TimestampSlot>,
4658    next_slot: usize,
4659    timestamp_period_ns: f64,
4660    last_timings: GpuPassTimings,
4661}
4662
4663impl GpuTimestampProfiler {
4664    fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
4665        let mut slots = Vec::with_capacity(GPU_TS_SLOTS);
4666        let resolve_bytes = GPU_TS_RESOLVE_STRIDE * 3;
4667        let readback_bytes = (GPU_TS_QUERY_COUNT as u64) * 8;
4668        for i in 0..GPU_TS_SLOTS {
4669            let query_set = device.create_query_set(&wgpu::QuerySetDescriptor {
4670                label: Some(&format!("strata_gpu_ts_query_set_{i}")),
4671                ty: wgpu::QueryType::Timestamp,
4672                count: GPU_TS_QUERY_COUNT,
4673            });
4674            let resolve_buffer = device.create_buffer(&wgpu::BufferDescriptor {
4675                label: Some(&format!("strata_gpu_ts_resolve_{i}")),
4676                size: resolve_bytes,
4677                usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC,
4678                mapped_at_creation: false,
4679            });
4680            let readback_buffer = device.create_buffer(&wgpu::BufferDescriptor {
4681                label: Some(&format!("strata_gpu_ts_readback_{i}")),
4682                size: readback_bytes,
4683                usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
4684                mapped_at_creation: false,
4685            });
4686            slots.push(TimestampSlot {
4687                query_set,
4688                resolve_buffer,
4689                readback_buffer,
4690                mapped_ready: Arc::new(std::sync::atomic::AtomicBool::new(false)),
4691                in_flight: false,
4692                wrote_shadow: false,
4693                wrote_main: false,
4694                wrote_overlay: false,
4695            });
4696        }
4697        Self {
4698            slots,
4699            next_slot: 0,
4700            timestamp_period_ns: (queue.get_timestamp_period() as f64).max(0.0),
4701            last_timings: GpuPassTimings {
4702                supported: true,
4703                ..Default::default()
4704            },
4705        }
4706    }
4707
4708    fn poll_ready(&mut self, device: &wgpu::Device) {
4709        device.poll(wgpu::Maintain::Poll);
4710        let period_ns = self.timestamp_period_ns;
4711        for slot in &mut self.slots {
4712            if !slot.in_flight
4713                || !slot
4714                    .mapped_ready
4715                    .load(std::sync::atomic::Ordering::Acquire)
4716            {
4717                continue;
4718            }
4719            {
4720                let view = slot.readback_buffer.slice(..).get_mapped_range();
4721                if view.len() >= (GPU_TS_QUERY_COUNT as usize) * 8 {
4722                    let read_u64 = |idx: usize| -> u64 {
4723                        let off = idx * 8;
4724                        u64::from_le_bytes(view[off..off + 8].try_into().unwrap_or([0; 8]))
4725                    };
4726                    let ticks_to_us = |start: u64, end: u64| -> u32 {
4727                        let delta = end.saturating_sub(start) as f64;
4728                        ((delta * period_ns) / 1000.0).round().clamp(0.0, u32::MAX as f64) as u32
4729                    };
4730                    if slot.wrote_shadow {
4731                        self.last_timings.shadow_pass_us = ticks_to_us(read_u64(0), read_u64(1));
4732                    } else if slot.wrote_main {
4733                        self.last_timings.shadow_pass_us = 0;
4734                    }
4735                    if slot.wrote_main {
4736                        self.last_timings.scene_3d_pass_us = ticks_to_us(read_u64(2), read_u64(3));
4737                        self.last_timings.total_3d_gpu_us = self
4738                            .last_timings
4739                            .shadow_pass_us
4740                            .saturating_add(self.last_timings.scene_3d_pass_us);
4741                    }
4742                    if slot.wrote_overlay {
4743                        self.last_timings.overlay_pass_us = ticks_to_us(read_u64(4), read_u64(5));
4744                    }
4745                }
4746            }
4747            slot.readback_buffer.unmap();
4748            slot.mapped_ready
4749                .store(false, std::sync::atomic::Ordering::Release);
4750            slot.in_flight = false;
4751            slot.wrote_shadow = false;
4752            slot.wrote_main = false;
4753            slot.wrote_overlay = false;
4754        }
4755    }
4756
4757    fn acquire_idle_slot(&mut self, device: &wgpu::Device) -> Option<usize> {
4758        self.poll_ready(device);
4759        let n = self.slots.len();
4760        for off in 0..n {
4761            let idx = (self.next_slot + off) % n;
4762            if !self.slots[idx].in_flight {
4763                self.next_slot = (idx + 1) % n;
4764                let s = &mut self.slots[idx];
4765                s.wrote_shadow = false;
4766                s.wrote_main = false;
4767                s.wrote_overlay = false;
4768                return Some(idx);
4769            }
4770        }
4771        None
4772    }
4773
4774    fn resolve_and_copy(&self, slot_idx: usize, encoder: &mut wgpu::CommandEncoder) {
4775        let slot = &self.slots[slot_idx];
4776        // Vulkan requires resolving ONLY query indices that were actually written in this submission;
4777        // resolving unwritten queries blocks forever on VK_QUERY_RESULT_WAIT_BIT.
4778        if slot.wrote_shadow {
4779            encoder.resolve_query_set(&slot.query_set, 0..2, &slot.resolve_buffer, 0);
4780            encoder.copy_buffer_to_buffer(&slot.resolve_buffer, 0, &slot.readback_buffer, 0, 16);
4781        }
4782        if slot.wrote_main {
4783            encoder.resolve_query_set(
4784                &slot.query_set,
4785                2..4,
4786                &slot.resolve_buffer,
4787                GPU_TS_RESOLVE_STRIDE,
4788            );
4789            encoder.copy_buffer_to_buffer(
4790                &slot.resolve_buffer,
4791                GPU_TS_RESOLVE_STRIDE,
4792                &slot.readback_buffer,
4793                16,
4794                16,
4795            );
4796        }
4797        if slot.wrote_overlay {
4798            encoder.resolve_query_set(
4799                &slot.query_set,
4800                4..6,
4801                &slot.resolve_buffer,
4802                GPU_TS_RESOLVE_STRIDE * 2,
4803            );
4804            encoder.copy_buffer_to_buffer(
4805                &slot.resolve_buffer,
4806                GPU_TS_RESOLVE_STRIDE * 2,
4807                &slot.readback_buffer,
4808                32,
4809                16,
4810            );
4811        }
4812    }
4813
4814    fn begin_async_map(&mut self, slot_idx: usize) {
4815        let slot = &mut self.slots[slot_idx];
4816        if !slot.wrote_shadow && !slot.wrote_main && !slot.wrote_overlay {
4817            return;
4818        }
4819        slot.in_flight = true;
4820        slot.mapped_ready
4821            .store(false, std::sync::atomic::Ordering::Release);
4822        let ready = Arc::clone(&slot.mapped_ready);
4823        slot.readback_buffer
4824            .slice(..)
4825            .map_async(wgpu::MapMode::Read, move |res| {
4826                if res.is_ok() {
4827                    ready.store(true, std::sync::atomic::Ordering::Release);
4828                }
4829            });
4830    }
4831}
4832
4833/// Hardware-accelerated `wgpu` 3D renderer capable of rendering directly into any `TextureView`
4834/// (swapchain surface) or offscreen RGBA target.
4835pub struct Wgpu3DRenderer {
4836    device: Arc<wgpu::Device>,
4837    queue: Arc<wgpu::Queue>,
4838    color_format: wgpu::TextureFormat,
4839    camera_buffer: wgpu::Buffer,
4840    sky_pipeline: wgpu::RenderPipeline,
4841    sky_opaque_pipeline: wgpu::RenderPipeline,
4842    sky_bind_group_layout: wgpu::BindGroupLayout,
4843    sky_bind_group: wgpu::BindGroup,
4844    star_pipeline: wgpu::RenderPipeline,
4845    star_bind_group_layout: wgpu::BindGroupLayout,
4846    star_bind_group: wgpu::BindGroup,
4847    cloud_pipeline: wgpu::RenderPipeline,
4848    cloud_inside_pipeline: wgpu::RenderPipeline,
4849    cloud_twosided_pipeline: wgpu::RenderPipeline,
4850    cloud_bind_group_layout: wgpu::BindGroupLayout,
4851    cloud_bind_group: wgpu::BindGroup,
4852    cloud_vbuf: wgpu::Buffer,
4853    cloud_ibuf: wgpu::Buffer,
4854    cloud_index_count: u32,
4855    env_state: GpuEnvironmentState,
4856    terrain_pipeline: wgpu::RenderPipeline,
4857    terrain_opaque_pipeline: wgpu::RenderPipeline,
4858    terrain_shadow_pipeline: wgpu::RenderPipeline,
4859    terrain_bind_group_layout: wgpu::BindGroupLayout,
4860    terrain_bind_group: wgpu::BindGroup,
4861    terrain_sampler: wgpu::Sampler,
4862    shadow_ocean_bgl: wgpu::BindGroupLayout,
4863    shadow_ocean_bind_group: wgpu::BindGroup,
4864    shadow_sampler: wgpu::Sampler,
4865    _shadow_fallback_tex: wgpu::Texture,
4866    shadow_fallback_view: wgpu::TextureView,
4867    shadow_target: Option<(u32, wgpu::Texture, wgpu::TextureView)>,
4868    ocean_uniform_buffer: wgpu::Buffer,
4869    coastal_sdf_sampler: wgpu::Sampler,
4870    _coastal_sdf_fallback_tex: wgpu::Texture,
4871    coastal_sdf_fallback_view: wgpu::TextureView,
4872    coastal_sdf_cached: Option<(u64, u64, u32, u32, wgpu::Texture, wgpu::TextureView)>,
4873    instance_buffer: wgpu::Buffer,
4874    instance_capacity: usize,
4875    slab: GpuTileSlabAllocator,
4876    atlas: GpuImageryAtlas,
4877    topologies: HashMap<(u32, bool), CachedIndexTopology>,
4878    dynamic_pipeline: wgpu::RenderPipeline,
4879    dynamic_bind_group_layout: wgpu::BindGroupLayout,
4880    dynamic_uniform_buffer: wgpu::Buffer,
4881    dynamic_uniform_capacity: usize,
4882    dynamic_uniform_stride: u32,
4883    dynamic_bind_group: wgpu::BindGroup,
4884    dynamic_meshes: HashMap<u64, CachedDynamicGpuMesh>,
4885    geo_object_pipeline: wgpu::RenderPipeline,
4886    geo_object_transparent_pipeline: wgpu::RenderPipeline,
4887    geo_shadow_pipeline: wgpu::RenderPipeline,
4888    geo_object_bind_group_layout: wgpu::BindGroupLayout,
4889    geo_object_bind_group: wgpu::BindGroup,
4890    geo_tex_bgl: wgpu::BindGroupLayout,
4891    geo_sampler: wgpu::Sampler,
4892    geo_default_tex_bg: wgpu::BindGroup,
4893    geo_instance_buffer: wgpu::Buffer,
4894    geo_instance_capacity: usize,
4895    geo_meshes: HashMap<u64, CachedGeoGpuMesh>,
4896    geo_textures: HashMap<u64, CachedGeoTexture>,
4897    particle_pipeline: wgpu::RenderPipeline,
4898    particle_common_bgl: wgpu::BindGroupLayout,
4899    particle_tex_bgl: wgpu::BindGroupLayout,
4900    particle_sampler: wgpu::Sampler,
4901    particle_uniform_buffer: wgpu::Buffer,
4902    particle_uniform_capacity: usize,
4903    particle_uniform_stride: u32,
4904    particle_common_bind_group: wgpu::BindGroup,
4905    particle_default_tex_bg: wgpu::BindGroup,
4906    particle_textures: HashMap<u64, CachedParticleTexture>,
4907    overlay_pipeline: wgpu::RenderPipeline,
4908    overlay_main_pass_pipeline: wgpu::RenderPipeline,
4909    scene_blit_pipeline: wgpu::RenderPipeline,
4910    overlay_bind_group_layout: wgpu::BindGroupLayout,
4911    overlay_sampler: wgpu::Sampler,
4912    depth_target: Option<(u32, u32, wgpu::TextureView)>,
4913    offscreen: Option<OffscreenTarget>,
4914    timestamp_profiler: Option<GpuTimestampProfiler>,
4915    frame_index: u64,
4916    last_geometry_rev: u64,
4917    last_terrain_frame: Option<Arc<RetainedTerrainFrame>>,
4918    cached_fallback_frames: HashMap<(usize, u32, u32), (u64, Arc<RetainedTerrainFrame>)>,
4919    is_software_adapter: bool,
4920}
4921
4922/// Returns adapter-supported [`wgpu::Limits`] requesting up to [`MAX_ATLAS_LAYERS`] texture array layers.
4923pub fn preferred_wgpu_limits(adapter: &wgpu::Adapter) -> wgpu::Limits {
4924    let mut limits = wgpu::Limits::default();
4925    limits.max_texture_array_layers = adapter
4926        .limits()
4927        .max_texture_array_layers
4928        .min(MAX_ATLAS_LAYERS)
4929        .max(limits.max_texture_array_layers);
4930    limits
4931}
4932
4933/// Acquires the first compatible [`wgpu::Adapter`] whose `request_device` succeeds,
4934/// preferring discrete GPUs first and automatically failing over across integrated/software
4935/// adapters when the primary GPU driver reports device loss or resource exhaustion.
4936pub fn request_working_adapter_and_device(
4937    instance: &wgpu::Instance,
4938    compatible_surface: Option<&wgpu::Surface<'_>>,
4939    label: &str,
4940) -> Result<(wgpu::Adapter, wgpu::Device, wgpu::Queue), String> {
4941    let mut candidates: Vec<wgpu::Adapter> = Vec::new();
4942    let mut seen: Vec<(u32, u32, wgpu::DeviceType, wgpu::Backend, String)> = Vec::new();
4943    let mut push_unique = |adapter: wgpu::Adapter| {
4944        if let Some(surface) = compatible_surface {
4945            if !adapter.is_surface_supported(surface) {
4946                return;
4947            }
4948        }
4949        let info = adapter.get_info();
4950        let key = (
4951            info.vendor,
4952            info.device,
4953            info.device_type,
4954            info.backend,
4955            info.name,
4956        );
4957        if !seen.contains(&key) {
4958            seen.push(key);
4959            candidates.push(adapter);
4960        }
4961    };
4962
4963    if let Some(preferred) = pollster::block_on(instance.request_adapter(
4964        &wgpu::RequestAdapterOptions {
4965            power_preference: wgpu::PowerPreference::HighPerformance,
4966            compatible_surface,
4967            force_fallback_adapter: false,
4968        },
4969    )) {
4970        push_unique(preferred);
4971    }
4972
4973    let mut enumerated: Vec<wgpu::Adapter> = instance
4974        .enumerate_adapters(wgpu::Backends::all())
4975        .into_iter()
4976        .collect();
4977    enumerated.sort_by_key(|a| {
4978        let info = a.get_info();
4979        let dev_rank = match info.device_type {
4980            wgpu::DeviceType::DiscreteGpu => 0u8,
4981            wgpu::DeviceType::IntegratedGpu => 1,
4982            wgpu::DeviceType::VirtualGpu => 2,
4983            wgpu::DeviceType::Cpu => 3,
4984            wgpu::DeviceType::Other => 4,
4985        };
4986        let backend_rank = match info.backend {
4987            wgpu::Backend::Vulkan => 0u8,
4988            wgpu::Backend::Metal | wgpu::Backend::Dx12 => 1,
4989            wgpu::Backend::Gl => 2,
4990            _ => 3,
4991        };
4992        (dev_rank, backend_rank)
4993    });
4994    for adapter in enumerated {
4995        push_unique(adapter);
4996    }
4997
4998    if candidates.is_empty() {
4999        return Err(if compatible_surface.is_some() {
5000            "no compatible wgpu adapter for window surface".to_string()
5001        } else {
5002            "no wgpu adapter available".to_string()
5003        });
5004    }
5005
5006    let mut errors = Vec::new();
5007    for adapter in candidates {
5008        let info = adapter.get_info();
5009        let required_limits = preferred_wgpu_limits(&adapter);
5010        let optional_ts = adapter.features() & wgpu::Features::TIMESTAMP_QUERY;
5011        let first_try = pollster::block_on(adapter.request_device(
5012            &wgpu::DeviceDescriptor {
5013                label: Some(label),
5014                required_features: optional_ts,
5015                required_limits: required_limits.clone(),
5016                memory_hints: wgpu::MemoryHints::Performance,
5017            },
5018            None,
5019        ));
5020        match first_try {
5021            Ok((device, queue)) => return Ok((adapter, device, queue)),
5022            Err(_) if !optional_ts.is_empty() => {
5023                // Gracefully fall back if driver advertises TIMESTAMP_QUERY but rejects device creation.
5024                match pollster::block_on(adapter.request_device(
5025                    &wgpu::DeviceDescriptor {
5026                        label: Some(label),
5027                        required_features: wgpu::Features::empty(),
5028                        required_limits,
5029                        memory_hints: wgpu::MemoryHints::Performance,
5030                    },
5031                    None,
5032                )) {
5033                    Ok((device, queue)) => return Ok((adapter, device, queue)),
5034                    Err(e) => {
5035                        errors.push(format!(
5036                            "{} ({:?}/{:?}): {e}",
5037                            info.name, info.backend, info.device_type
5038                        ));
5039                    }
5040                }
5041            }
5042            Err(e) => {
5043                errors.push(format!(
5044                    "{} ({:?}/{:?}): {e}",
5045                    info.name, info.backend, info.device_type
5046                ));
5047            }
5048        }
5049    }
5050
5051    Err(format!("request_device failed: {}", errors.join("; ")))
5052}
5053
5054impl Wgpu3DRenderer {
5055    /// Creates a headless `Wgpu3DRenderer` using any available hardware or software Vulkan/GL adapter.
5056    pub fn new_headless(color_format: wgpu::TextureFormat) -> Result<Self, String> {
5057        let instance = wgpu::Instance::default();
5058        let (adapter, device, queue) =
5059            request_working_adapter_and_device(&instance, None, "strata_render_wgpu_device")?;
5060        let is_software = adapter.get_info().device_type == wgpu::DeviceType::Cpu;
5061        let mut renderer = Self::from_device(Arc::new(device), Arc::new(queue), color_format);
5062        renderer.is_software_adapter = is_software;
5063        Ok(renderer)
5064    }
5065
5066    /// Returns `true` when this renderer was initialized on a CPU software rasterizer (WARP / Lavapipe).
5067    #[inline]
5068    pub fn is_software_adapter(&self) -> bool {
5069        self.is_software_adapter
5070    }
5071
5072    /// Creates a `Wgpu3DRenderer` bound to an existing `wgpu::Device` & `wgpu::Queue` (e.g., from a window surface).
5073    pub fn from_device(
5074        device: Arc<wgpu::Device>,
5075        queue: Arc<wgpu::Queue>,
5076        color_format: wgpu::TextureFormat,
5077    ) -> Self {
5078        let camera_buffer = device.create_buffer(&wgpu::BufferDescriptor {
5079            label: Some("strata_3d_camera_uniforms"),
5080            size: std::mem::size_of::<GpuCameraUniforms>() as u64,
5081            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
5082            mapped_at_creation: false,
5083        });
5084
5085        let initial_instances = 1024usize;
5086        let instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
5087            label: Some("strata_3d_tile_instances"),
5088            size: (initial_instances * std::mem::size_of::<GpuTileInstance>()) as u64,
5089            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
5090            mapped_at_creation: false,
5091        });
5092
5093        let slab = GpuTileSlabAllocator::new(&device, 262_144);
5094        let atlas_layers = MAX_ATLAS_LAYERS.min(device.limits().max_texture_array_layers.max(1));
5095        let atlas = GpuImageryAtlas::new(&device, &queue, atlas_layers, color_format);
5096
5097        let terrain_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
5098            label: Some("strata_3d_terrain_sampler"),
5099            mag_filter: wgpu::FilterMode::Linear,
5100            min_filter: wgpu::FilterMode::Linear,
5101            mipmap_filter: wgpu::FilterMode::Linear,
5102            address_mode_u: wgpu::AddressMode::ClampToEdge,
5103            address_mode_v: wgpu::AddressMode::ClampToEdge,
5104            ..Default::default()
5105        });
5106
5107        let env_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
5108            label: Some("strata_3d_env_sampler"),
5109            mag_filter: wgpu::FilterMode::Linear,
5110            min_filter: wgpu::FilterMode::Linear,
5111            mipmap_filter: wgpu::FilterMode::Linear,
5112            address_mode_u: wgpu::AddressMode::Repeat,
5113            address_mode_v: wgpu::AddressMode::ClampToEdge,
5114            ..Default::default()
5115        });
5116        let cloud_noise_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
5117            label: Some("strata_3d_cloud_noise_sampler"),
5118            mag_filter: wgpu::FilterMode::Linear,
5119            min_filter: wgpu::FilterMode::Linear,
5120            mipmap_filter: wgpu::FilterMode::Nearest,
5121            address_mode_u: wgpu::AddressMode::Repeat,
5122            address_mode_v: wgpu::AddressMode::Repeat,
5123            ..Default::default()
5124        });
5125        let land_mask_view = create_rgba8_2d_view(
5126            &device,
5127            &queue,
5128            "strata_env_land_fallback",
5129            1,
5130            1,
5131            &[255, 255, 255, 255],
5132        );
5133        let cloud_map_view = create_cloud_density_r8_view(
5134            &device,
5135            &queue,
5136            "strata_env_cloud_fallback",
5137            1,
5138            1,
5139            &[255, 255, 255, 0],
5140        );
5141        let cloud_noise_view = create_cloud_noise_lut_view(&device, &queue);
5142        let moon_view = create_rgba8_2d_view(
5143            &device,
5144            &queue,
5145            "strata_env_moon_fallback",
5146            1,
5147            1,
5148            &[190, 190, 190, 255],
5149        );
5150        let black_face = Arc::new(vec![0u8, 0, 0, 0]);
5151        let skybox_cube_view = create_rgba8_cube_view(
5152            &device,
5153            &queue,
5154            "strata_env_skybox_fallback",
5155            1,
5156            &[
5157                Arc::clone(&black_face),
5158                Arc::clone(&black_face),
5159                Arc::clone(&black_face),
5160                Arc::clone(&black_face),
5161                Arc::clone(&black_face),
5162                black_face,
5163            ],
5164            wgpu::TextureFormat::Rgba8Unorm,
5165        );
5166        let star_capacity = 64usize;
5167        let star_buffer = device.create_buffer(&wgpu::BufferDescriptor {
5168            label: Some("strata_3d_stars"),
5169            size: (star_capacity * std::mem::size_of::<GpuStar>()) as u64,
5170            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
5171            mapped_at_creation: false,
5172        });
5173        let env_state = GpuEnvironmentState {
5174            land_mask_id_rev: None,
5175            cloud_map_id_rev: None,
5176            moon_tex_id_rev: None,
5177            skybox_cube_id_rev: None,
5178            stars_ptr: 0,
5179            stars_len: 0,
5180            land_mask_view,
5181            cloud_map_view,
5182            cloud_noise_view,
5183            moon_view,
5184            skybox_cube_view,
5185            env_sampler,
5186            cloud_noise_sampler,
5187            star_buffer,
5188            star_capacity,
5189            star_count: 0,
5190        };
5191
5192        // Sky + Moon + Sun + Milky Way pass
5193        let sky_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
5194            label: Some("strata_3d_sky_wgsl"),
5195            source: wgpu::ShaderSource::Wgsl(SKY_WGSL.into()),
5196        });
5197        let sky_bind_group_layout =
5198            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
5199                label: Some("strata_3d_sky_bgl"),
5200                entries: &[
5201                    wgpu::BindGroupLayoutEntry {
5202                        binding: 0,
5203                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5204                        ty: wgpu::BindingType::Buffer {
5205                            ty: wgpu::BufferBindingType::Uniform,
5206                            has_dynamic_offset: false,
5207                            min_binding_size: None,
5208                        },
5209                        count: None,
5210                    },
5211                    wgpu::BindGroupLayoutEntry {
5212                        binding: 1,
5213                        visibility: wgpu::ShaderStages::FRAGMENT,
5214                        ty: wgpu::BindingType::Texture {
5215                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
5216                            view_dimension: wgpu::TextureViewDimension::D2,
5217                            multisampled: false,
5218                        },
5219                        count: None,
5220                    },
5221                    wgpu::BindGroupLayoutEntry {
5222                        binding: 2,
5223                        visibility: wgpu::ShaderStages::FRAGMENT,
5224                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
5225                        count: None,
5226                    },
5227                    wgpu::BindGroupLayoutEntry {
5228                        binding: 3,
5229                        visibility: wgpu::ShaderStages::FRAGMENT,
5230                        ty: wgpu::BindingType::Texture {
5231                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
5232                            view_dimension: wgpu::TextureViewDimension::Cube,
5233                            multisampled: false,
5234                        },
5235                        count: None,
5236                    },
5237                ],
5238            });
5239        let sky_bind_group = Self::create_sky_bind_group(
5240            &device,
5241            &sky_bind_group_layout,
5242            &camera_buffer,
5243            &env_state.moon_view,
5244            &env_state.env_sampler,
5245            &env_state.skybox_cube_view,
5246        );
5247        let sky_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
5248            label: Some("strata_3d_sky_pl"),
5249            bind_group_layouts: &[&sky_bind_group_layout],
5250            push_constant_ranges: &[],
5251        });
5252        let make_sky_pipeline = |label: &str, blend: Option<wgpu::BlendState>| {
5253            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
5254                label: Some(label),
5255                layout: Some(&sky_layout),
5256                vertex: wgpu::VertexState {
5257                    module: &sky_shader,
5258                    entry_point: Some("vs_sky"),
5259                    buffers: &[],
5260                    compilation_options: Default::default(),
5261                },
5262                fragment: Some(wgpu::FragmentState {
5263                    module: &sky_shader,
5264                    entry_point: Some("fs_sky"),
5265                    targets: &[Some(wgpu::ColorTargetState {
5266                        format: color_format,
5267                        blend,
5268                        write_mask: wgpu::ColorWrites::ALL,
5269                    })],
5270                    compilation_options: Default::default(),
5271                }),
5272                primitive: wgpu::PrimitiveState::default(),
5273                depth_stencil: Some(wgpu::DepthStencilState {
5274                    format: wgpu::TextureFormat::Depth32Float,
5275                    depth_write_enabled: false,
5276                    depth_compare: wgpu::CompareFunction::LessEqual,
5277                    stencil: wgpu::StencilState::default(),
5278                    bias: wgpu::DepthBiasState::default(),
5279                }),
5280                multisample: wgpu::MultisampleState::default(),
5281                multiview: None,
5282                cache: None,
5283            })
5284        };
5285        let sky_pipeline = make_sky_pipeline(
5286            "strata_3d_sky_pipeline",
5287            Some(wgpu::BlendState::ALPHA_BLENDING),
5288        );
5289        let sky_opaque_pipeline = make_sky_pipeline("strata_3d_sky_opaque_pipeline", None);
5290
5291        // Scientific J2000 starfield pass
5292        let star_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
5293            label: Some("strata_3d_stars_wgsl"),
5294            source: wgpu::ShaderSource::Wgsl(STARS_WGSL.into()),
5295        });
5296        let star_bind_group_layout =
5297            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
5298                label: Some("strata_3d_stars_bgl"),
5299                entries: &[
5300                    wgpu::BindGroupLayoutEntry {
5301                        binding: 0,
5302                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5303                        ty: wgpu::BindingType::Buffer {
5304                            ty: wgpu::BufferBindingType::Uniform,
5305                            has_dynamic_offset: false,
5306                            min_binding_size: None,
5307                        },
5308                        count: None,
5309                    },
5310                    wgpu::BindGroupLayoutEntry {
5311                        binding: 1,
5312                        visibility: wgpu::ShaderStages::VERTEX,
5313                        ty: wgpu::BindingType::Buffer {
5314                            ty: wgpu::BufferBindingType::Storage { read_only: true },
5315                            has_dynamic_offset: false,
5316                            min_binding_size: None,
5317                        },
5318                        count: None,
5319                    },
5320                ],
5321            });
5322        let star_bind_group = Self::create_star_bind_group(
5323            &device,
5324            &star_bind_group_layout,
5325            &camera_buffer,
5326            &env_state.star_buffer,
5327        );
5328        let star_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
5329            label: Some("strata_3d_stars_pl"),
5330            bind_group_layouts: &[&star_bind_group_layout],
5331            push_constant_ranges: &[],
5332        });
5333        let star_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
5334            label: Some("strata_3d_star_pipeline"),
5335            layout: Some(&star_layout),
5336            vertex: wgpu::VertexState {
5337                module: &star_shader,
5338                entry_point: Some("vs_star"),
5339                buffers: &[],
5340                compilation_options: Default::default(),
5341            },
5342            fragment: Some(wgpu::FragmentState {
5343                module: &star_shader,
5344                entry_point: Some("fs_star"),
5345                targets: &[Some(wgpu::ColorTargetState {
5346                    format: color_format,
5347                    blend: Some(wgpu::BlendState {
5348                        color: wgpu::BlendComponent {
5349                            src_factor: wgpu::BlendFactor::One,
5350                            dst_factor: wgpu::BlendFactor::One,
5351                            operation: wgpu::BlendOperation::Add,
5352                        },
5353                        alpha: wgpu::BlendComponent {
5354                            src_factor: wgpu::BlendFactor::One,
5355                            dst_factor: wgpu::BlendFactor::One,
5356                            operation: wgpu::BlendOperation::Add,
5357                        },
5358                    }),
5359                    write_mask: wgpu::ColorWrites::ALL,
5360                })],
5361                compilation_options: Default::default(),
5362            }),
5363            primitive: wgpu::PrimitiveState::default(),
5364            depth_stencil: Some(wgpu::DepthStencilState {
5365                format: wgpu::TextureFormat::Depth32Float,
5366                depth_write_enabled: false,
5367                depth_compare: wgpu::CompareFunction::LessEqual,
5368                stencil: wgpu::StencilState::default(),
5369                bias: wgpu::DepthBiasState::default(),
5370            }),
5371            multisample: wgpu::MultisampleState::default(),
5372            multiview: None,
5373            cache: None,
5374        });
5375
5376        // 3D global cloud shell pipeline + static icosphere
5377        let cloud_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
5378            label: Some("strata_3d_cloud_shell_wgsl"),
5379            source: wgpu::ShaderSource::Wgsl(CLOUD_SHELL_WGSL.into()),
5380        });
5381        let cloud_bind_group_layout =
5382            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
5383                label: Some("strata_3d_cloud_bgl"),
5384                entries: &[
5385                    wgpu::BindGroupLayoutEntry {
5386                        binding: 0,
5387                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5388                        ty: wgpu::BindingType::Buffer {
5389                            ty: wgpu::BufferBindingType::Uniform,
5390                            has_dynamic_offset: false,
5391                            min_binding_size: None,
5392                        },
5393                        count: None,
5394                    },
5395                    wgpu::BindGroupLayoutEntry {
5396                        binding: 1,
5397                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5398                        ty: wgpu::BindingType::Texture {
5399                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
5400                            view_dimension: wgpu::TextureViewDimension::D2,
5401                            multisampled: false,
5402                        },
5403                        count: None,
5404                    },
5405                    wgpu::BindGroupLayoutEntry {
5406                        binding: 2,
5407                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5408                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
5409                        count: None,
5410                    },
5411                    wgpu::BindGroupLayoutEntry {
5412                        binding: 3,
5413                        visibility: wgpu::ShaderStages::FRAGMENT,
5414                        ty: wgpu::BindingType::Texture {
5415                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
5416                            view_dimension: wgpu::TextureViewDimension::D2,
5417                            multisampled: false,
5418                        },
5419                        count: None,
5420                    },
5421                    wgpu::BindGroupLayoutEntry {
5422                        binding: 4,
5423                        visibility: wgpu::ShaderStages::FRAGMENT,
5424                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
5425                        count: None,
5426                    },
5427                ],
5428            });
5429        let cloud_bind_group = Self::create_cloud_bind_group(
5430            &device,
5431            &cloud_bind_group_layout,
5432            "strata_3d_cloud_bg",
5433            &camera_buffer,
5434            &env_state.cloud_map_view,
5435            &env_state.env_sampler,
5436            &env_state.cloud_noise_view,
5437            &env_state.cloud_noise_sampler,
5438        );
5439        let cloud_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
5440            label: Some("strata_3d_cloud_pl"),
5441            bind_group_layouts: &[&cloud_bind_group_layout],
5442            push_constant_ranges: &[],
5443        });
5444        let make_cloud_pipeline = |label: &str, cull_mode: Option<wgpu::Face>| {
5445            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
5446                label: Some(label),
5447                layout: Some(&cloud_layout),
5448                vertex: wgpu::VertexState {
5449                    module: &cloud_shader,
5450                    entry_point: Some("vs_cloud"),
5451                    buffers: &[wgpu::VertexBufferLayout {
5452                        array_stride: std::mem::size_of::<RteTileVertex>() as u64,
5453                        step_mode: wgpu::VertexStepMode::Vertex,
5454                        attributes: &[
5455                            wgpu::VertexAttribute {
5456                                format: wgpu::VertexFormat::Float32x4,
5457                                offset: 0,
5458                                shader_location: 0,
5459                            },
5460                            wgpu::VertexAttribute {
5461                                format: wgpu::VertexFormat::Float32x4,
5462                                offset: 16,
5463                                shader_location: 1,
5464                            },
5465                        ],
5466                    }],
5467                    compilation_options: Default::default(),
5468                },
5469                fragment: Some(wgpu::FragmentState {
5470                    module: &cloud_shader,
5471                    entry_point: Some("fs_cloud"),
5472                    targets: &[Some(wgpu::ColorTargetState {
5473                        format: color_format,
5474                        blend: Some(wgpu::BlendState::ALPHA_BLENDING),
5475                        write_mask: wgpu::ColorWrites::ALL,
5476                    })],
5477                    compilation_options: Default::default(),
5478                }),
5479                primitive: wgpu::PrimitiveState {
5480                    topology: wgpu::PrimitiveTopology::TriangleList,
5481                    cull_mode,
5482                    front_face: wgpu::FrontFace::Ccw,
5483                    ..Default::default()
5484                },
5485                depth_stencil: Some(wgpu::DepthStencilState {
5486                    format: wgpu::TextureFormat::Depth32Float,
5487                    depth_write_enabled: false,
5488                    depth_compare: wgpu::CompareFunction::LessEqual,
5489                    stencil: wgpu::StencilState::default(),
5490                    bias: wgpu::DepthBiasState::default(),
5491                }),
5492                multisample: wgpu::MultisampleState::default(),
5493                multiview: None,
5494                cache: None,
5495            })
5496        };
5497        let cloud_pipeline =
5498            make_cloud_pipeline("strata_3d_cloud_pipeline", Some(wgpu::Face::Back));
5499        let cloud_inside_pipeline =
5500            make_cloud_pipeline("strata_3d_cloud_inside_pipeline", Some(wgpu::Face::Front));
5501        let cloud_twosided_pipeline =
5502            make_cloud_pipeline("strata_3d_cloud_twosided_pipeline", None);
5503        let (ico_v, ico_i) = build_unit_icosphere(4);
5504        let cloud_vbuf = device.create_buffer(&wgpu::BufferDescriptor {
5505            label: Some("strata_3d_cloud_vb"),
5506            size: (ico_v.len() * std::mem::size_of::<RteTileVertex>()) as u64,
5507            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
5508            mapped_at_creation: false,
5509        });
5510        queue.write_buffer(&cloud_vbuf, 0, bytemuck::cast_slice(&ico_v));
5511        let cloud_ibuf = device.create_buffer(&wgpu::BufferDescriptor {
5512            label: Some("strata_3d_cloud_ib"),
5513            size: (ico_i.len() * 4) as u64,
5514            usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
5515            mapped_at_creation: false,
5516        });
5517        queue.write_buffer(&cloud_ibuf, 0, bytemuck::cast_slice(&ico_i));
5518        let cloud_index_count = ico_i.len() as u32;
5519
5520        // Terrain vertex-pulling pipeline
5521        let terrain_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
5522            label: Some("strata_3d_terrain_pull_wgsl"),
5523            source: wgpu::ShaderSource::Wgsl(TERRAIN_PULL_WGSL.into()),
5524        });
5525        let terrain_bind_group_layout =
5526            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
5527                label: Some("strata_3d_terrain_bgl"),
5528                entries: &[
5529                    wgpu::BindGroupLayoutEntry {
5530                        binding: 0,
5531                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5532                        ty: wgpu::BindingType::Buffer {
5533                            ty: wgpu::BufferBindingType::Uniform,
5534                            has_dynamic_offset: false,
5535                            min_binding_size: None,
5536                        },
5537                        count: None,
5538                    },
5539                    wgpu::BindGroupLayoutEntry {
5540                        binding: 1,
5541                        visibility: wgpu::ShaderStages::VERTEX,
5542                        ty: wgpu::BindingType::Buffer {
5543                            ty: wgpu::BufferBindingType::Storage { read_only: true },
5544                            has_dynamic_offset: false,
5545                            min_binding_size: None,
5546                        },
5547                        count: None,
5548                    },
5549                    wgpu::BindGroupLayoutEntry {
5550                        binding: 2,
5551                        visibility: wgpu::ShaderStages::VERTEX,
5552                        ty: wgpu::BindingType::Buffer {
5553                            ty: wgpu::BufferBindingType::Storage { read_only: true },
5554                            has_dynamic_offset: false,
5555                            min_binding_size: None,
5556                        },
5557                        count: None,
5558                    },
5559                    wgpu::BindGroupLayoutEntry {
5560                        binding: 3,
5561                        visibility: wgpu::ShaderStages::FRAGMENT,
5562                        ty: wgpu::BindingType::Texture {
5563                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
5564                            view_dimension: wgpu::TextureViewDimension::D2Array,
5565                            multisampled: false,
5566                        },
5567                        count: None,
5568                    },
5569                    wgpu::BindGroupLayoutEntry {
5570                        binding: 4,
5571                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5572                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
5573                        count: None,
5574                    },
5575                    wgpu::BindGroupLayoutEntry {
5576                        binding: 5,
5577                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5578                        ty: wgpu::BindingType::Texture {
5579                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
5580                            view_dimension: wgpu::TextureViewDimension::D2,
5581                            multisampled: false,
5582                        },
5583                        count: None,
5584                    },
5585                    wgpu::BindGroupLayoutEntry {
5586                        binding: 6,
5587                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5588                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
5589                        count: None,
5590                    },
5591                ],
5592            });
5593        let terrain_bind_group = Self::create_terrain_bind_group(
5594            &device,
5595            &terrain_bind_group_layout,
5596            &camera_buffer,
5597            &slab.buffer,
5598            &instance_buffer,
5599            &atlas.view,
5600            &terrain_sampler,
5601            &env_state.land_mask_view,
5602            &env_state.env_sampler,
5603        );
5604        let shadow_ocean_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
5605            label: Some("strata_3d_shadow_ocean_bgl"),
5606            entries: &[
5607                wgpu::BindGroupLayoutEntry {
5608                    binding: 0,
5609                    visibility: wgpu::ShaderStages::FRAGMENT,
5610                    ty: wgpu::BindingType::Texture {
5611                        sample_type: wgpu::TextureSampleType::Depth,
5612                        view_dimension: wgpu::TextureViewDimension::D2,
5613                        multisampled: false,
5614                    },
5615                    count: None,
5616                },
5617                wgpu::BindGroupLayoutEntry {
5618                    binding: 1,
5619                    visibility: wgpu::ShaderStages::FRAGMENT,
5620                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
5621                    count: None,
5622                },
5623                wgpu::BindGroupLayoutEntry {
5624                    binding: 2,
5625                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5626                    ty: wgpu::BindingType::Buffer {
5627                        ty: wgpu::BufferBindingType::Uniform,
5628                        has_dynamic_offset: false,
5629                        min_binding_size: None,
5630                    },
5631                    count: None,
5632                },
5633                wgpu::BindGroupLayoutEntry {
5634                    binding: 3,
5635                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5636                    ty: wgpu::BindingType::Texture {
5637                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
5638                        view_dimension: wgpu::TextureViewDimension::D2,
5639                        multisampled: false,
5640                    },
5641                    count: None,
5642                },
5643                wgpu::BindGroupLayoutEntry {
5644                    binding: 4,
5645                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5646                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
5647                    count: None,
5648                },
5649            ],
5650        });
5651        let shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
5652            label: Some("strata_3d_shadow_cmp_sampler"),
5653            address_mode_u: wgpu::AddressMode::ClampToEdge,
5654            address_mode_v: wgpu::AddressMode::ClampToEdge,
5655            address_mode_w: wgpu::AddressMode::ClampToEdge,
5656            mag_filter: wgpu::FilterMode::Linear,
5657            min_filter: wgpu::FilterMode::Linear,
5658            compare: Some(wgpu::CompareFunction::LessEqual),
5659            ..Default::default()
5660        });
5661        let shadow_fallback_tex = device.create_texture(&wgpu::TextureDescriptor {
5662            label: Some("strata_3d_shadow_fallback_1x1"),
5663            size: wgpu::Extent3d {
5664                width: 1,
5665                height: 1,
5666                depth_or_array_layers: 1,
5667            },
5668            mip_level_count: 1,
5669            sample_count: 1,
5670            dimension: wgpu::TextureDimension::D2,
5671            format: wgpu::TextureFormat::Depth32Float,
5672            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
5673            view_formats: &[],
5674        });
5675        let shadow_fallback_view = shadow_fallback_tex.create_view(&wgpu::TextureViewDescriptor::default());
5676        // Clear 1x1 fallback depth texture to 1.0 once so comparisons always pass when shadows are off.
5677        {
5678            let mut init_enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
5679                label: Some("strata_3d_shadow_fallback_init"),
5680            });
5681            let _ = init_enc.begin_render_pass(&wgpu::RenderPassDescriptor {
5682                label: Some("strata_3d_shadow_fallback_clear"),
5683                color_attachments: &[],
5684                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
5685                    view: &shadow_fallback_view,
5686                    depth_ops: Some(wgpu::Operations {
5687                        load: wgpu::LoadOp::Clear(1.0),
5688                        store: wgpu::StoreOp::Store,
5689                    }),
5690                    stencil_ops: None,
5691                }),
5692                timestamp_writes: None,
5693                occlusion_query_set: None,
5694            });
5695            queue.submit(Some(init_enc.finish()));
5696        }
5697
5698        let ocean_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
5699            label: Some("strata_3d_ocean_uniforms"),
5700            size: std::mem::size_of::<GpuOceanUniforms>() as u64,
5701            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
5702            mapped_at_creation: false,
5703        });
5704        queue.write_buffer(
5705            &ocean_uniform_buffer,
5706            0,
5707            bytemuck::bytes_of(&GpuOceanUniforms::disabled()),
5708        );
5709        let coastal_sdf_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
5710            label: Some("strata_3d_coastal_sdf_sampler"),
5711            address_mode_u: wgpu::AddressMode::ClampToEdge,
5712            address_mode_v: wgpu::AddressMode::ClampToEdge,
5713            address_mode_w: wgpu::AddressMode::ClampToEdge,
5714            mag_filter: wgpu::FilterMode::Linear,
5715            min_filter: wgpu::FilterMode::Linear,
5716            ..Default::default()
5717        });
5718        let coastal_sdf_fallback_tex = device.create_texture(&wgpu::TextureDescriptor {
5719            label: Some("strata_3d_coastal_sdf_fallback_1x1"),
5720            size: wgpu::Extent3d {
5721                width: 1,
5722                height: 1,
5723                depth_or_array_layers: 1,
5724            },
5725            mip_level_count: 1,
5726            sample_count: 1,
5727            dimension: wgpu::TextureDimension::D2,
5728            format: wgpu::TextureFormat::Rgba8Unorm,
5729            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
5730            view_formats: &[],
5731        });
5732        queue.write_texture(
5733            wgpu::TexelCopyTextureInfo {
5734                texture: &coastal_sdf_fallback_tex,
5735                mip_level: 0,
5736                origin: wgpu::Origin3d::ZERO,
5737                aspect: wgpu::TextureAspect::All,
5738            },
5739            &[255u8, 255, 128, 128],
5740            wgpu::TexelCopyBufferLayout {
5741                offset: 0,
5742                bytes_per_row: Some(4),
5743                rows_per_image: Some(1),
5744            },
5745            wgpu::Extent3d {
5746                width: 1,
5747                height: 1,
5748                depth_or_array_layers: 1,
5749            },
5750        );
5751        let coastal_sdf_fallback_view =
5752            coastal_sdf_fallback_tex.create_view(&wgpu::TextureViewDescriptor::default());
5753        let shadow_ocean_bind_group = Self::create_shadow_ocean_bind_group(
5754            &device,
5755            &shadow_ocean_bgl,
5756            &shadow_fallback_view,
5757            &shadow_sampler,
5758            &ocean_uniform_buffer,
5759            &coastal_sdf_fallback_view,
5760            &coastal_sdf_sampler,
5761        );
5762
5763        let terrain_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
5764            label: Some("strata_3d_terrain_pl"),
5765            bind_group_layouts: &[&terrain_bind_group_layout, &shadow_ocean_bgl],
5766            push_constant_ranges: &[],
5767        });
5768        let make_terrain_pipeline = |label: &str, blend: Option<wgpu::BlendState>| {
5769            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
5770                label: Some(label),
5771                layout: Some(&terrain_layout),
5772                vertex: wgpu::VertexState {
5773                    module: &terrain_shader,
5774                    entry_point: Some("vs_terrain"),
5775                    buffers: &[],
5776                    compilation_options: Default::default(),
5777                },
5778                fragment: Some(wgpu::FragmentState {
5779                    module: &terrain_shader,
5780                    entry_point: Some(if blend.is_none() {
5781                        "fs_terrain_opaque"
5782                    } else {
5783                        "fs_terrain"
5784                    }),
5785                    targets: &[Some(wgpu::ColorTargetState {
5786                        format: color_format,
5787                        blend,
5788                        write_mask: wgpu::ColorWrites::ALL,
5789                    })],
5790                    compilation_options: Default::default(),
5791                }),
5792                primitive: wgpu::PrimitiveState {
5793                    topology: wgpu::PrimitiveTopology::TriangleList,
5794                    cull_mode: Some(wgpu::Face::Back),
5795                    front_face: wgpu::FrontFace::Ccw,
5796                    ..Default::default()
5797                },
5798                depth_stencil: Some(wgpu::DepthStencilState {
5799                    format: wgpu::TextureFormat::Depth32Float,
5800                    depth_write_enabled: true,
5801                    depth_compare: wgpu::CompareFunction::LessEqual,
5802                    stencil: wgpu::StencilState::default(),
5803                    bias: wgpu::DepthBiasState::default(),
5804                }),
5805                multisample: wgpu::MultisampleState::default(),
5806                multiview: None,
5807                cache: None,
5808            })
5809        };
5810        let terrain_pipeline = make_terrain_pipeline(
5811            "strata_3d_terrain_pipeline",
5812            Some(wgpu::BlendState::ALPHA_BLENDING),
5813        );
5814        let terrain_opaque_pipeline =
5815            make_terrain_pipeline("strata_3d_terrain_opaque_pipeline", None);
5816
5817        let terrain_shadow_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
5818            label: Some("strata_3d_terrain_shadow_wgsl"),
5819            source: wgpu::ShaderSource::Wgsl(TERRAIN_SHADOW_WGSL.into()),
5820        });
5821        let terrain_shadow_layout =
5822            device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
5823                label: Some("strata_3d_terrain_shadow_pl"),
5824                bind_group_layouts: &[&terrain_bind_group_layout],
5825                push_constant_ranges: &[],
5826            });
5827        let terrain_shadow_pipeline =
5828            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
5829                label: Some("strata_3d_terrain_shadow_pipeline"),
5830                layout: Some(&terrain_shadow_layout),
5831                vertex: wgpu::VertexState {
5832                    module: &terrain_shadow_shader,
5833                    entry_point: Some("vs_terrain_shadow"),
5834                    buffers: &[],
5835                    compilation_options: Default::default(),
5836                },
5837                fragment: None,
5838                primitive: wgpu::PrimitiveState {
5839                    topology: wgpu::PrimitiveTopology::TriangleList,
5840                    cull_mode: None,
5841                    front_face: wgpu::FrontFace::Ccw,
5842                    ..Default::default()
5843                },
5844                depth_stencil: Some(wgpu::DepthStencilState {
5845                    format: wgpu::TextureFormat::Depth32Float,
5846                    depth_write_enabled: true,
5847                    depth_compare: wgpu::CompareFunction::LessEqual,
5848                    stencil: wgpu::StencilState::default(),
5849                    bias: wgpu::DepthBiasState {
5850                        constant: 2,
5851                        slope_scale: 2.0,
5852                        clamp: 0.0,
5853                    },
5854                }),
5855                multisample: wgpu::MultisampleState::default(),
5856                multiview: None,
5857                cache: None,
5858            });
5859
5860        // Dynamic RTC mesh pipeline (buildings, entities, fallback meshes)
5861        let dynamic_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
5862            label: Some("strata_3d_dynamic_wgsl"),
5863            source: wgpu::ShaderSource::Wgsl(DYNAMIC_MESH_WGSL.into()),
5864        });
5865        let align = device.limits().min_uniform_buffer_offset_alignment.max(256);
5866        let dyn_size = std::mem::size_of::<GpuDynamicUniforms>() as u32;
5867        let dynamic_uniform_stride = dyn_size.div_ceil(align) * align;
5868        let dynamic_uniform_capacity = 64usize;
5869        let dynamic_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
5870            label: Some("strata_3d_dynamic_uniforms"),
5871            size: (dynamic_uniform_capacity * dynamic_uniform_stride as usize) as u64,
5872            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
5873            mapped_at_creation: false,
5874        });
5875        let dynamic_bind_group_layout =
5876            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
5877                label: Some("strata_3d_dynamic_bgl"),
5878                entries: &[
5879                    wgpu::BindGroupLayoutEntry {
5880                        binding: 0,
5881                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5882                        ty: wgpu::BindingType::Buffer {
5883                            ty: wgpu::BufferBindingType::Uniform,
5884                            has_dynamic_offset: false,
5885                            min_binding_size: None,
5886                        },
5887                        count: None,
5888                    },
5889                    wgpu::BindGroupLayoutEntry {
5890                        binding: 1,
5891                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5892                        ty: wgpu::BindingType::Buffer {
5893                            ty: wgpu::BufferBindingType::Uniform,
5894                            has_dynamic_offset: true,
5895                            min_binding_size: std::num::NonZeroU64::new(std::mem::size_of::<
5896                                GpuDynamicUniforms,
5897                            >(
5898                            )
5899                                as u64),
5900                        },
5901                        count: None,
5902                    },
5903                ],
5904            });
5905        let dynamic_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
5906            label: Some("strata_3d_dynamic_bg"),
5907            layout: &dynamic_bind_group_layout,
5908            entries: &[
5909                wgpu::BindGroupEntry {
5910                    binding: 0,
5911                    resource: camera_buffer.as_entire_binding(),
5912                },
5913                wgpu::BindGroupEntry {
5914                    binding: 1,
5915                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
5916                        buffer: &dynamic_uniform_buffer,
5917                        offset: 0,
5918                        size: std::num::NonZeroU64::new(
5919                            std::mem::size_of::<GpuDynamicUniforms>() as u64
5920                        ),
5921                    }),
5922                },
5923            ],
5924        });
5925        let dynamic_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
5926            label: Some("strata_3d_dynamic_pl"),
5927            bind_group_layouts: &[&dynamic_bind_group_layout],
5928            push_constant_ranges: &[],
5929        });
5930        let dynamic_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
5931            label: Some("strata_3d_dynamic_pipeline"),
5932            layout: Some(&dynamic_layout),
5933            vertex: wgpu::VertexState {
5934                module: &dynamic_shader,
5935                entry_point: Some("vs_dynamic"),
5936                buffers: &[wgpu::VertexBufferLayout {
5937                    array_stride: std::mem::size_of::<RteTileVertex>() as u64,
5938                    step_mode: wgpu::VertexStepMode::Vertex,
5939                    attributes: &[
5940                        wgpu::VertexAttribute {
5941                            format: wgpu::VertexFormat::Float32x4,
5942                            offset: 0,
5943                            shader_location: 0,
5944                        },
5945                        wgpu::VertexAttribute {
5946                            format: wgpu::VertexFormat::Float32x4,
5947                            offset: 16,
5948                            shader_location: 1,
5949                        },
5950                    ],
5951                }],
5952                compilation_options: Default::default(),
5953            },
5954            fragment: Some(wgpu::FragmentState {
5955                module: &dynamic_shader,
5956                entry_point: Some("fs_dynamic"),
5957                targets: &[Some(wgpu::ColorTargetState {
5958                    format: color_format,
5959                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
5960                    write_mask: wgpu::ColorWrites::ALL,
5961                })],
5962                compilation_options: Default::default(),
5963            }),
5964            primitive: wgpu::PrimitiveState {
5965                topology: wgpu::PrimitiveTopology::TriangleList,
5966                cull_mode: None,
5967                front_face: wgpu::FrontFace::Ccw,
5968                ..Default::default()
5969            },
5970            depth_stencil: Some(wgpu::DepthStencilState {
5971                format: wgpu::TextureFormat::Depth32Float,
5972                depth_write_enabled: true,
5973                depth_compare: wgpu::CompareFunction::LessEqual,
5974                stencil: wgpu::StencilState::default(),
5975                bias: wgpu::DepthBiasState::default(),
5976            }),
5977            multisample: wgpu::MultisampleState::default(),
5978            multiview: None,
5979            cache: None,
5980        });
5981
5982        // Hardware-instanced geodetic 3D object pipeline (storage buffer + double-single RTE + 3x3 cofactor normals)
5983        let geo_object_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
5984            label: Some("strata_3d_geo_object_wgsl"),
5985            source: wgpu::ShaderSource::Wgsl(GEO_OBJECT_WGSL.into()),
5986        });
5987        let geo_instance_capacity = 256usize;
5988        let geo_instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
5989            label: Some("strata_3d_geo_instances"),
5990            size: (geo_instance_capacity * std::mem::size_of::<GpuGeoInstance>()) as u64,
5991            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
5992            mapped_at_creation: false,
5993        });
5994        let geo_object_bind_group_layout =
5995            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
5996                label: Some("strata_3d_geo_object_bgl"),
5997                entries: &[
5998                    wgpu::BindGroupLayoutEntry {
5999                        binding: 0,
6000                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
6001                        ty: wgpu::BindingType::Buffer {
6002                            ty: wgpu::BufferBindingType::Uniform,
6003                            has_dynamic_offset: false,
6004                            min_binding_size: None,
6005                        },
6006                        count: None,
6007                    },
6008                    wgpu::BindGroupLayoutEntry {
6009                        binding: 1,
6010                        visibility: wgpu::ShaderStages::VERTEX,
6011                        ty: wgpu::BindingType::Buffer {
6012                            ty: wgpu::BufferBindingType::Storage { read_only: true },
6013                            has_dynamic_offset: false,
6014                            min_binding_size: None,
6015                        },
6016                        count: None,
6017                    },
6018                ],
6019            });
6020        let geo_object_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
6021            label: Some("strata_3d_geo_object_bg"),
6022            layout: &geo_object_bind_group_layout,
6023            entries: &[
6024                wgpu::BindGroupEntry {
6025                    binding: 0,
6026                    resource: camera_buffer.as_entire_binding(),
6027                },
6028                wgpu::BindGroupEntry {
6029                    binding: 1,
6030                    resource: geo_instance_buffer.as_entire_binding(),
6031                },
6032            ],
6033        });
6034        let geo_tex_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
6035            label: Some("strata_3d_geo_tex_bgl"),
6036            entries: &[
6037                wgpu::BindGroupLayoutEntry {
6038                    binding: 0,
6039                    visibility: wgpu::ShaderStages::FRAGMENT,
6040                    ty: wgpu::BindingType::Texture {
6041                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
6042                        view_dimension: wgpu::TextureViewDimension::D2,
6043                        multisampled: false,
6044                    },
6045                    count: None,
6046                },
6047                wgpu::BindGroupLayoutEntry {
6048                    binding: 1,
6049                    visibility: wgpu::ShaderStages::FRAGMENT,
6050                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
6051                    count: None,
6052                },
6053            ],
6054        });
6055        let geo_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
6056            label: Some("strata_3d_geo_albedo_sampler"),
6057            address_mode_u: wgpu::AddressMode::Repeat,
6058            address_mode_v: wgpu::AddressMode::Repeat,
6059            mag_filter: wgpu::FilterMode::Linear,
6060            min_filter: wgpu::FilterMode::Linear,
6061            ..Default::default()
6062        });
6063        let default_geo_tex = device.create_texture(&wgpu::TextureDescriptor {
6064            label: Some("strata_3d_geo_default_1x1_white"),
6065            size: wgpu::Extent3d {
6066                width: 1,
6067                height: 1,
6068                depth_or_array_layers: 1,
6069            },
6070            mip_level_count: 1,
6071            sample_count: 1,
6072            dimension: wgpu::TextureDimension::D2,
6073            format: wgpu::TextureFormat::Rgba8Unorm,
6074            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
6075            view_formats: &[],
6076        });
6077        queue.write_texture(
6078            wgpu::TexelCopyTextureInfo {
6079                texture: &default_geo_tex,
6080                mip_level: 0,
6081                origin: wgpu::Origin3d::ZERO,
6082                aspect: wgpu::TextureAspect::All,
6083            },
6084            &[255u8, 255, 255, 255],
6085            wgpu::TexelCopyBufferLayout {
6086                offset: 0,
6087                bytes_per_row: Some(4),
6088                rows_per_image: Some(1),
6089            },
6090            wgpu::Extent3d {
6091                width: 1,
6092                height: 1,
6093                depth_or_array_layers: 1,
6094            },
6095        );
6096        let default_geo_view = default_geo_tex.create_view(&Default::default());
6097        let geo_default_tex_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
6098            label: Some("strata_3d_geo_default_tex_bg"),
6099            layout: &geo_tex_bgl,
6100            entries: &[
6101                wgpu::BindGroupEntry {
6102                    binding: 0,
6103                    resource: wgpu::BindingResource::TextureView(&default_geo_view),
6104                },
6105                wgpu::BindGroupEntry {
6106                    binding: 1,
6107                    resource: wgpu::BindingResource::Sampler(&geo_sampler),
6108                },
6109            ],
6110        });
6111        let geo_object_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
6112            label: Some("strata_3d_geo_object_pl"),
6113            bind_group_layouts: &[&geo_object_bind_group_layout, &shadow_ocean_bgl, &geo_tex_bgl],
6114            push_constant_ranges: &[],
6115        });
6116        let make_geo_pipeline = |label: &str, depth_write_enabled: bool, blend: Option<wgpu::BlendState>| {
6117            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
6118                label: Some(label),
6119                layout: Some(&geo_object_layout),
6120                vertex: wgpu::VertexState {
6121                    module: &geo_object_shader,
6122                    entry_point: Some("vs_geo_object"),
6123                    buffers: &[wgpu::VertexBufferLayout {
6124                        array_stride: std::mem::size_of::<GpuGeoVertex>() as u64,
6125                        step_mode: wgpu::VertexStepMode::Vertex,
6126                        attributes: &[
6127                            wgpu::VertexAttribute {
6128                                format: wgpu::VertexFormat::Float32x4,
6129                                offset: 0,
6130                                shader_location: 0,
6131                            },
6132                            wgpu::VertexAttribute {
6133                                format: wgpu::VertexFormat::Float32x4,
6134                                offset: 16,
6135                                shader_location: 1,
6136                            },
6137                            wgpu::VertexAttribute {
6138                                format: wgpu::VertexFormat::Float32x4,
6139                                offset: 32,
6140                                shader_location: 2,
6141                            },
6142                        ],
6143                    }],
6144                    compilation_options: Default::default(),
6145                },
6146                fragment: Some(wgpu::FragmentState {
6147                    module: &geo_object_shader,
6148                    entry_point: Some("fs_geo_object"),
6149                    targets: &[Some(wgpu::ColorTargetState {
6150                        format: color_format,
6151                        blend,
6152                        write_mask: wgpu::ColorWrites::ALL,
6153                    })],
6154                    compilation_options: Default::default(),
6155                }),
6156                primitive: wgpu::PrimitiveState {
6157                    topology: wgpu::PrimitiveTopology::TriangleList,
6158                    cull_mode: None,
6159                    front_face: wgpu::FrontFace::Ccw,
6160                    ..Default::default()
6161                },
6162                depth_stencil: Some(wgpu::DepthStencilState {
6163                    format: wgpu::TextureFormat::Depth32Float,
6164                    depth_write_enabled,
6165                    depth_compare: wgpu::CompareFunction::LessEqual,
6166                    stencil: wgpu::StencilState::default(),
6167                    bias: wgpu::DepthBiasState::default(),
6168                }),
6169                multisample: wgpu::MultisampleState::default(),
6170                multiview: None,
6171                cache: None,
6172            })
6173        };
6174        let geo_object_pipeline =
6175            make_geo_pipeline("strata_3d_geo_object_pipeline", true, None);
6176        let geo_object_transparent_pipeline = make_geo_pipeline(
6177            "strata_3d_geo_object_transparent_pipeline",
6178            false,
6179            Some(wgpu::BlendState::ALPHA_BLENDING),
6180        );
6181        let geo_shadow_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
6182            label: Some("strata_3d_geo_shadow_wgsl"),
6183            source: wgpu::ShaderSource::Wgsl(GEO_SHADOW_WGSL.into()),
6184        });
6185        let geo_shadow_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
6186            label: Some("strata_3d_geo_shadow_pl"),
6187            bind_group_layouts: &[&geo_object_bind_group_layout],
6188            push_constant_ranges: &[],
6189        });
6190        let geo_shadow_pipeline =
6191            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
6192                label: Some("strata_3d_geo_shadow_pipeline"),
6193                layout: Some(&geo_shadow_layout),
6194                vertex: wgpu::VertexState {
6195                    module: &geo_shadow_shader,
6196                    entry_point: Some("vs_geo_shadow"),
6197                    buffers: &[wgpu::VertexBufferLayout {
6198                        array_stride: std::mem::size_of::<GpuGeoVertex>() as u64,
6199                        step_mode: wgpu::VertexStepMode::Vertex,
6200                        attributes: &[
6201                            wgpu::VertexAttribute {
6202                                format: wgpu::VertexFormat::Float32x4,
6203                                offset: 0,
6204                                shader_location: 0,
6205                            },
6206                            wgpu::VertexAttribute {
6207                                format: wgpu::VertexFormat::Float32x4,
6208                                offset: 16,
6209                                shader_location: 1,
6210                            },
6211                        ],
6212                    }],
6213                    compilation_options: Default::default(),
6214                },
6215                fragment: None,
6216                primitive: wgpu::PrimitiveState {
6217                    topology: wgpu::PrimitiveTopology::TriangleList,
6218                    cull_mode: None,
6219                    front_face: wgpu::FrontFace::Ccw,
6220                    ..Default::default()
6221                },
6222                depth_stencil: Some(wgpu::DepthStencilState {
6223                    format: wgpu::TextureFormat::Depth32Float,
6224                    depth_write_enabled: true,
6225                    depth_compare: wgpu::CompareFunction::LessEqual,
6226                    stencil: wgpu::StencilState::default(),
6227                    bias: wgpu::DepthBiasState {
6228                        constant: 2,
6229                        slope_scale: 2.0,
6230                        clamp: 0.0,
6231                    },
6232                }),
6233                multisample: wgpu::MultisampleState::default(),
6234                multiview: None,
6235                cache: None,
6236            });
6237
6238        // GPU-instanced 2D camera-local toroidal particle volume pipeline (rain, snow, custom 2D sprites)
6239        let particle_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
6240            label: Some("strata_3d_particle_volume_wgsl"),
6241            source: wgpu::ShaderSource::Wgsl(PARTICLE_VOLUME_WGSL.into()),
6242        });
6243        let ubo_align = device.limits().min_uniform_buffer_offset_alignment.max(256);
6244        let particle_u_size = std::mem::size_of::<GpuParticleLayerUniforms>() as u32;
6245        let particle_uniform_stride = particle_u_size.div_ceil(ubo_align) * ubo_align;
6246        let particle_uniform_capacity = 16usize;
6247        let particle_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
6248            label: Some("strata_3d_particle_uniforms"),
6249            size: (particle_uniform_capacity as u64) * (particle_uniform_stride as u64),
6250            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
6251            mapped_at_creation: false,
6252        });
6253        let particle_common_bgl =
6254            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
6255                label: Some("strata_3d_particle_common_bgl"),
6256                entries: &[
6257                    wgpu::BindGroupLayoutEntry {
6258                        binding: 0,
6259                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
6260                        ty: wgpu::BindingType::Buffer {
6261                            ty: wgpu::BufferBindingType::Uniform,
6262                            has_dynamic_offset: false,
6263                            min_binding_size: None,
6264                        },
6265                        count: None,
6266                    },
6267                    wgpu::BindGroupLayoutEntry {
6268                        binding: 1,
6269                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
6270                        ty: wgpu::BindingType::Buffer {
6271                            ty: wgpu::BufferBindingType::Uniform,
6272                            has_dynamic_offset: true,
6273                            min_binding_size: std::num::NonZeroU64::new(particle_u_size as u64),
6274                        },
6275                        count: None,
6276                    },
6277                ],
6278            });
6279        let particle_common_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
6280            label: Some("strata_3d_particle_common_bg"),
6281            layout: &particle_common_bgl,
6282            entries: &[
6283                wgpu::BindGroupEntry {
6284                    binding: 0,
6285                    resource: camera_buffer.as_entire_binding(),
6286                },
6287                wgpu::BindGroupEntry {
6288                    binding: 1,
6289                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
6290                        buffer: &particle_uniform_buffer,
6291                        offset: 0,
6292                        size: std::num::NonZeroU64::new(particle_u_size as u64),
6293                    }),
6294                },
6295            ],
6296        });
6297        let particle_tex_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
6298            label: Some("strata_3d_particle_tex_bgl"),
6299            entries: &[
6300                wgpu::BindGroupLayoutEntry {
6301                    binding: 0,
6302                    visibility: wgpu::ShaderStages::FRAGMENT,
6303                    ty: wgpu::BindingType::Texture {
6304                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
6305                        view_dimension: wgpu::TextureViewDimension::D2,
6306                        multisampled: false,
6307                    },
6308                    count: None,
6309                },
6310                wgpu::BindGroupLayoutEntry {
6311                    binding: 1,
6312                    visibility: wgpu::ShaderStages::FRAGMENT,
6313                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
6314                    count: None,
6315                },
6316            ],
6317        });
6318        let particle_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
6319            label: Some("strata_3d_particle_sampler"),
6320            address_mode_u: wgpu::AddressMode::ClampToEdge,
6321            address_mode_v: wgpu::AddressMode::ClampToEdge,
6322            mag_filter: wgpu::FilterMode::Linear,
6323            min_filter: wgpu::FilterMode::Linear,
6324            ..Default::default()
6325        });
6326        let default_p_tex = device.create_texture(&wgpu::TextureDescriptor {
6327            label: Some("strata_3d_particle_default_1x1"),
6328            size: wgpu::Extent3d {
6329                width: 1,
6330                height: 1,
6331                depth_or_array_layers: 1,
6332            },
6333            mip_level_count: 1,
6334            sample_count: 1,
6335            dimension: wgpu::TextureDimension::D2,
6336            format: wgpu::TextureFormat::Rgba8Unorm,
6337            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
6338            view_formats: &[],
6339        });
6340        queue.write_texture(
6341            wgpu::TexelCopyTextureInfo {
6342                texture: &default_p_tex,
6343                mip_level: 0,
6344                origin: wgpu::Origin3d::ZERO,
6345                aspect: wgpu::TextureAspect::All,
6346            },
6347            &[255u8, 255, 255, 255],
6348            wgpu::TexelCopyBufferLayout {
6349                offset: 0,
6350                bytes_per_row: Some(4),
6351                rows_per_image: Some(1),
6352            },
6353            wgpu::Extent3d {
6354                width: 1,
6355                height: 1,
6356                depth_or_array_layers: 1,
6357            },
6358        );
6359        let default_p_view = default_p_tex.create_view(&Default::default());
6360        let particle_default_tex_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
6361            label: Some("strata_3d_particle_default_tex_bg"),
6362            layout: &particle_tex_bgl,
6363            entries: &[
6364                wgpu::BindGroupEntry {
6365                    binding: 0,
6366                    resource: wgpu::BindingResource::TextureView(&default_p_view),
6367                },
6368                wgpu::BindGroupEntry {
6369                    binding: 1,
6370                    resource: wgpu::BindingResource::Sampler(&particle_sampler),
6371                },
6372            ],
6373        });
6374        let particle_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
6375            label: Some("strata_3d_particle_pl"),
6376            bind_group_layouts: &[&particle_common_bgl, &particle_tex_bgl],
6377            push_constant_ranges: &[],
6378        });
6379        let particle_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
6380            label: Some("strata_3d_particle_pipeline"),
6381            layout: Some(&particle_layout),
6382            vertex: wgpu::VertexState {
6383                module: &particle_shader,
6384                entry_point: Some("vs_particle"),
6385                buffers: &[],
6386                compilation_options: Default::default(),
6387            },
6388            fragment: Some(wgpu::FragmentState {
6389                module: &particle_shader,
6390                entry_point: Some("fs_particle"),
6391                targets: &[Some(wgpu::ColorTargetState {
6392                    format: color_format,
6393                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
6394                    write_mask: wgpu::ColorWrites::ALL,
6395                })],
6396                compilation_options: Default::default(),
6397            }),
6398            primitive: wgpu::PrimitiveState {
6399                topology: wgpu::PrimitiveTopology::TriangleList,
6400                cull_mode: None,
6401                front_face: wgpu::FrontFace::Ccw,
6402                ..Default::default()
6403            },
6404            depth_stencil: Some(wgpu::DepthStencilState {
6405                format: wgpu::TextureFormat::Depth32Float,
6406                depth_write_enabled: false,
6407                depth_compare: wgpu::CompareFunction::LessEqual,
6408                stencil: wgpu::StencilState::default(),
6409                bias: wgpu::DepthBiasState::default(),
6410            }),
6411            multisample: wgpu::MultisampleState::default(),
6412            multiview: None,
6413            cache: None,
6414        });
6415
6416        // 2D overlay composite pipeline
6417        let overlay_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
6418            label: Some("strata_2d_overlay_wgsl"),
6419            source: wgpu::ShaderSource::Wgsl(OVERLAY_COMPOSITE_WGSL.into()),
6420        });
6421        let overlay_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
6422            label: Some("strata_2d_overlay_sampler"),
6423            mag_filter: wgpu::FilterMode::Linear,
6424            min_filter: wgpu::FilterMode::Linear,
6425            ..Default::default()
6426        });
6427        let overlay_bind_group_layout =
6428            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
6429                label: Some("strata_2d_overlay_bgl"),
6430                entries: &[
6431                    wgpu::BindGroupLayoutEntry {
6432                        binding: 0,
6433                        visibility: wgpu::ShaderStages::FRAGMENT,
6434                        ty: wgpu::BindingType::Texture {
6435                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
6436                            view_dimension: wgpu::TextureViewDimension::D2,
6437                            multisampled: false,
6438                        },
6439                        count: None,
6440                    },
6441                    wgpu::BindGroupLayoutEntry {
6442                        binding: 1,
6443                        visibility: wgpu::ShaderStages::FRAGMENT,
6444                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
6445                        count: None,
6446                    },
6447                ],
6448            });
6449        let overlay_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
6450            label: Some("strata_2d_overlay_pl"),
6451            bind_group_layouts: &[&overlay_bind_group_layout],
6452            push_constant_ranges: &[],
6453        });
6454        let overlay_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
6455            label: Some("strata_2d_overlay_pipeline"),
6456            layout: Some(&overlay_layout),
6457            vertex: wgpu::VertexState {
6458                module: &overlay_shader,
6459                entry_point: Some("vs_overlay"),
6460                buffers: &[],
6461                compilation_options: Default::default(),
6462            },
6463            fragment: Some(wgpu::FragmentState {
6464                module: &overlay_shader,
6465                entry_point: Some("fs_overlay"),
6466                targets: &[Some(wgpu::ColorTargetState {
6467                    format: color_format,
6468                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
6469                    write_mask: wgpu::ColorWrites::ALL,
6470                })],
6471                compilation_options: Default::default(),
6472            }),
6473            primitive: wgpu::PrimitiveState::default(),
6474            depth_stencil: None,
6475            multisample: wgpu::MultisampleState::default(),
6476            multiview: None,
6477            cache: None,
6478        });
6479        let overlay_main_pass_pipeline =
6480            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
6481                label: Some("strata_2d_overlay_main_pass_pipeline"),
6482                layout: Some(&overlay_layout),
6483                vertex: wgpu::VertexState {
6484                    module: &overlay_shader,
6485                    entry_point: Some("vs_overlay"),
6486                    buffers: &[],
6487                    compilation_options: Default::default(),
6488                },
6489                fragment: Some(wgpu::FragmentState {
6490                    module: &overlay_shader,
6491                    entry_point: Some("fs_overlay"),
6492                    targets: &[Some(wgpu::ColorTargetState {
6493                        format: color_format,
6494                        blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
6495                        write_mask: wgpu::ColorWrites::ALL,
6496                    })],
6497                    compilation_options: Default::default(),
6498                }),
6499                primitive: wgpu::PrimitiveState::default(),
6500                depth_stencil: Some(wgpu::DepthStencilState {
6501                    format: wgpu::TextureFormat::Depth32Float,
6502                    depth_write_enabled: false,
6503                    depth_compare: wgpu::CompareFunction::Always,
6504                    stencil: wgpu::StencilState::default(),
6505                    bias: wgpu::DepthBiasState::default(),
6506                }),
6507                multisample: wgpu::MultisampleState::default(),
6508                multiview: None,
6509                cache: None,
6510            });
6511        let scene_blit_pipeline =
6512            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
6513                label: Some("strata_cached_3d_scene_blit_pipeline"),
6514                layout: Some(&overlay_layout),
6515                vertex: wgpu::VertexState {
6516                    module: &overlay_shader,
6517                    entry_point: Some("vs_overlay"),
6518                    buffers: &[],
6519                    compilation_options: Default::default(),
6520                },
6521                fragment: Some(wgpu::FragmentState {
6522                    module: &overlay_shader,
6523                    entry_point: Some("fs_overlay"),
6524                    targets: &[Some(wgpu::ColorTargetState {
6525                        format: color_format,
6526                        blend: None,
6527                        write_mask: wgpu::ColorWrites::ALL,
6528                    })],
6529                    compilation_options: Default::default(),
6530                }),
6531                primitive: wgpu::PrimitiveState::default(),
6532                depth_stencil: None,
6533                multisample: wgpu::MultisampleState::default(),
6534                multiview: None,
6535                cache: None,
6536            });
6537        let timestamp_profiler = if device
6538            .features()
6539            .contains(wgpu::Features::TIMESTAMP_QUERY)
6540        {
6541            Some(GpuTimestampProfiler::new(&device, &queue))
6542        } else {
6543            None
6544        };
6545
6546        Self {
6547            device,
6548            queue,
6549            color_format,
6550            camera_buffer,
6551            sky_pipeline,
6552            sky_opaque_pipeline,
6553            sky_bind_group_layout,
6554            sky_bind_group,
6555            star_pipeline,
6556            star_bind_group_layout,
6557            star_bind_group,
6558            cloud_pipeline,
6559            cloud_inside_pipeline,
6560            cloud_twosided_pipeline,
6561            cloud_bind_group_layout,
6562            cloud_bind_group,
6563            cloud_vbuf,
6564            cloud_ibuf,
6565            cloud_index_count,
6566            env_state,
6567            terrain_pipeline,
6568            terrain_opaque_pipeline,
6569            terrain_shadow_pipeline,
6570            terrain_bind_group_layout,
6571            terrain_bind_group,
6572            terrain_sampler,
6573            shadow_ocean_bgl,
6574            shadow_ocean_bind_group,
6575            shadow_sampler,
6576            _shadow_fallback_tex: shadow_fallback_tex,
6577            shadow_fallback_view,
6578            shadow_target: None,
6579            ocean_uniform_buffer,
6580            coastal_sdf_sampler,
6581            _coastal_sdf_fallback_tex: coastal_sdf_fallback_tex,
6582            coastal_sdf_fallback_view,
6583            coastal_sdf_cached: None,
6584            instance_buffer,
6585            instance_capacity: initial_instances,
6586            slab,
6587            atlas,
6588            topologies: HashMap::new(),
6589            dynamic_pipeline,
6590            dynamic_bind_group_layout,
6591            dynamic_uniform_buffer,
6592            dynamic_uniform_capacity,
6593            dynamic_uniform_stride,
6594            dynamic_bind_group,
6595            dynamic_meshes: HashMap::new(),
6596            geo_object_pipeline,
6597            geo_object_transparent_pipeline,
6598            geo_shadow_pipeline,
6599            geo_object_bind_group_layout,
6600            geo_object_bind_group,
6601            geo_tex_bgl,
6602            geo_sampler,
6603            geo_default_tex_bg,
6604            geo_instance_buffer,
6605            geo_instance_capacity,
6606            geo_meshes: HashMap::new(),
6607            geo_textures: HashMap::new(),
6608            particle_pipeline,
6609            particle_common_bgl,
6610            particle_tex_bgl,
6611            particle_sampler,
6612            particle_uniform_buffer,
6613            particle_uniform_capacity,
6614            particle_uniform_stride,
6615            particle_common_bind_group,
6616            particle_default_tex_bg,
6617            particle_textures: HashMap::new(),
6618            overlay_pipeline,
6619            overlay_main_pass_pipeline,
6620            scene_blit_pipeline,
6621            overlay_bind_group_layout,
6622            overlay_sampler,
6623            depth_target: None,
6624            offscreen: None,
6625            timestamp_profiler,
6626            frame_index: 0,
6627            last_geometry_rev: 0,
6628            last_terrain_frame: None,
6629            cached_fallback_frames: HashMap::new(),
6630            is_software_adapter: false,
6631        }
6632    }
6633
6634    pub fn device(&self) -> &Arc<wgpu::Device> {
6635        &self.device
6636    }
6637
6638    pub fn queue(&self) -> &Arc<wgpu::Queue> {
6639        &self.queue
6640    }
6641
6642    pub fn color_format(&self) -> wgpu::TextureFormat {
6643        self.color_format
6644    }
6645
6646    /// Number of currently cached GPU geodetic object mesh buffers.
6647    pub fn cached_geo_mesh_count(&self) -> usize {
6648        self.geo_meshes.len()
6649    }
6650
6651    /// Number of currently cached GPU geodetic object albedo textures.
6652    pub fn cached_geo_texture_count(&self) -> usize {
6653        self.geo_textures.len()
6654    }
6655
6656    /// Polls any completed asynchronous GPU timestamp query readbacks without stalling.
6657    pub fn poll_gpu_timestamps(&mut self) {
6658        if let Some(ref mut profiler) = self.timestamp_profiler {
6659            profiler.poll_ready(&self.device);
6660        }
6661    }
6662
6663    /// Returns the most recently resolved hardware GPU pass timings (or `supported: false`
6664    /// when `wgpu::Features::TIMESTAMP_QUERY` is unavailable on the active adapter).
6665    pub fn last_gpu_pass_timings(&self) -> GpuPassTimings {
6666        self.timestamp_profiler
6667            .as_ref()
6668            .map(|p| p.last_timings)
6669            .unwrap_or_default()
6670    }
6671
6672    /// Total GPU buffer, texture atlas, and render-target memory allocated by this 3D renderer.
6673    pub fn gpu_memory_bytes(&self) -> u64 {
6674        let mut bytes = self.camera_buffer.size()
6675            + self.instance_buffer.size()
6676            + self.ocean_uniform_buffer.size()
6677            + self.dynamic_uniform_buffer.size()
6678            + self.geo_instance_buffer.size()
6679            + self.particle_uniform_buffer.size()
6680            + self.env_state.star_buffer.size()
6681            + self.cloud_vbuf.size()
6682            + self.cloud_ibuf.size()
6683            + self.slab.buffer.size()
6684            + (ATLAS_TILE_SIZE as u64)
6685                * (ATLAS_TILE_SIZE as u64)
6686                * 4
6687                * (self.atlas.layer_owner.len() as u64);
6688
6689        for topo in self.topologies.values() {
6690            bytes += topo.buffer.size();
6691        }
6692        for dm in self.dynamic_meshes.values() {
6693            bytes += dm.vbuf.size() + dm.ibuf.size();
6694        }
6695        for gm in self.geo_meshes.values() {
6696            bytes += gm.vbuf.size() + gm.ibuf.size();
6697        }
6698        for gt in self.geo_textures.values() {
6699            bytes += (gt.width as u64) * (gt.height as u64) * 4;
6700        }
6701        for pt in self.particle_textures.values() {
6702            bytes += (pt.width as u64) * (pt.height as u64) * 4;
6703        }
6704        if let Some((sz, _, _)) = self.shadow_target {
6705            bytes += (sz as u64) * (sz as u64) * 4;
6706        }
6707        if let Some((_, _, w, h, _, _)) = self.coastal_sdf_cached {
6708            bytes += (w as u64) * (h as u64) * 4;
6709        }
6710        if let Some((w, h, _)) = self.depth_target {
6711            bytes += (w as u64) * (h as u64) * 4;
6712        }
6713        if let Some(ref off) = self.offscreen {
6714            bytes += (off.width as u64) * (off.height as u64) * 8
6715                + (off.padded_bytes_per_row as u64) * (off.height as u64);
6716        }
6717        bytes
6718    }
6719
6720    fn ensure_geo_texture(
6721        &mut self,
6722        tex: &crate::scene3d::RetainedTileTexture,
6723        seq: u64,
6724    ) -> Option<(u64, bool)> {
6725        if tex.width == 0
6726            || tex.height == 0
6727            || tex.rgba8.len() < (tex.width as usize) * (tex.height as usize) * 4
6728        {
6729            return None;
6730        }
6731        let need_upload = match self.geo_textures.get_mut(&tex.id) {
6732            Some(existing) => {
6733                existing.last_used_seq = seq;
6734                if existing.revision == tex.revision
6735                    && existing.width == tex.width
6736                    && existing.height == tex.height
6737                {
6738                    return Some((tex.id, existing.has_alpha));
6739                }
6740                true
6741            }
6742            None => true,
6743        };
6744        if need_upload {
6745            let byte_len = (tex.width as usize) * (tex.height as usize) * 4;
6746            let bytes = &tex.rgba8[..byte_len];
6747            let has_alpha = bytes.chunks_exact(4).any(|px| px[3] < 255);
6748            let gpu_tex = self.device.create_texture(&wgpu::TextureDescriptor {
6749                label: Some("strata_3d_geo_albedo_tex"),
6750                size: wgpu::Extent3d {
6751                    width: tex.width,
6752                    height: tex.height,
6753                    depth_or_array_layers: 1,
6754                },
6755                mip_level_count: 1,
6756                sample_count: 1,
6757                dimension: wgpu::TextureDimension::D2,
6758                format: wgpu::TextureFormat::Rgba8Unorm,
6759                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
6760                view_formats: &[],
6761            });
6762            self.queue.write_texture(
6763                wgpu::TexelCopyTextureInfo {
6764                    texture: &gpu_tex,
6765                    mip_level: 0,
6766                    origin: wgpu::Origin3d::ZERO,
6767                    aspect: wgpu::TextureAspect::All,
6768                },
6769                bytes,
6770                wgpu::TexelCopyBufferLayout {
6771                    offset: 0,
6772                    bytes_per_row: Some(tex.width * 4),
6773                    rows_per_image: Some(tex.height),
6774                },
6775                wgpu::Extent3d {
6776                    width: tex.width,
6777                    height: tex.height,
6778                    depth_or_array_layers: 1,
6779                },
6780            );
6781            let view = gpu_tex.create_view(&Default::default());
6782            let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
6783                label: Some("strata_3d_geo_albedo_bg"),
6784                layout: &self.geo_tex_bgl,
6785                entries: &[
6786                    wgpu::BindGroupEntry {
6787                        binding: 0,
6788                        resource: wgpu::BindingResource::TextureView(&view),
6789                    },
6790                    wgpu::BindGroupEntry {
6791                        binding: 1,
6792                        resource: wgpu::BindingResource::Sampler(&self.geo_sampler),
6793                    },
6794                ],
6795            });
6796            self.geo_textures.insert(
6797                tex.id,
6798                CachedGeoTexture {
6799                    revision: tex.revision,
6800                    width: tex.width,
6801                    height: tex.height,
6802                    has_alpha,
6803                    _texture: gpu_tex,
6804                    bind_group,
6805                    last_used_seq: seq,
6806                },
6807            );
6808            return Some((tex.id, has_alpha));
6809        }
6810        None
6811    }
6812
6813    #[allow(clippy::too_many_arguments)]
6814    fn create_cloud_bind_group(
6815        device: &wgpu::Device,
6816        layout: &wgpu::BindGroupLayout,
6817        label: &str,
6818        camera_buffer: &wgpu::Buffer,
6819        cloud_view: &wgpu::TextureView,
6820        cloud_sampler: &wgpu::Sampler,
6821        noise_view: &wgpu::TextureView,
6822        noise_sampler: &wgpu::Sampler,
6823    ) -> wgpu::BindGroup {
6824        device.create_bind_group(&wgpu::BindGroupDescriptor {
6825            label: Some(label),
6826            layout,
6827            entries: &[
6828                wgpu::BindGroupEntry {
6829                    binding: 0,
6830                    resource: camera_buffer.as_entire_binding(),
6831                },
6832                wgpu::BindGroupEntry {
6833                    binding: 1,
6834                    resource: wgpu::BindingResource::TextureView(cloud_view),
6835                },
6836                wgpu::BindGroupEntry {
6837                    binding: 2,
6838                    resource: wgpu::BindingResource::Sampler(cloud_sampler),
6839                },
6840                wgpu::BindGroupEntry {
6841                    binding: 3,
6842                    resource: wgpu::BindingResource::TextureView(noise_view),
6843                },
6844                wgpu::BindGroupEntry {
6845                    binding: 4,
6846                    resource: wgpu::BindingResource::Sampler(noise_sampler),
6847                },
6848            ],
6849        })
6850    }
6851
6852    fn create_sky_bind_group(
6853        device: &wgpu::Device,
6854        layout: &wgpu::BindGroupLayout,
6855        camera_buffer: &wgpu::Buffer,
6856        moon_view: &wgpu::TextureView,
6857        sampler: &wgpu::Sampler,
6858        skybox_cube_view: &wgpu::TextureView,
6859    ) -> wgpu::BindGroup {
6860        device.create_bind_group(&wgpu::BindGroupDescriptor {
6861            label: Some("strata_3d_sky_bg"),
6862            layout,
6863            entries: &[
6864                wgpu::BindGroupEntry {
6865                    binding: 0,
6866                    resource: camera_buffer.as_entire_binding(),
6867                },
6868                wgpu::BindGroupEntry {
6869                    binding: 1,
6870                    resource: wgpu::BindingResource::TextureView(moon_view),
6871                },
6872                wgpu::BindGroupEntry {
6873                    binding: 2,
6874                    resource: wgpu::BindingResource::Sampler(sampler),
6875                },
6876                wgpu::BindGroupEntry {
6877                    binding: 3,
6878                    resource: wgpu::BindingResource::TextureView(skybox_cube_view),
6879                },
6880            ],
6881        })
6882    }
6883
6884    fn create_star_bind_group(
6885        device: &wgpu::Device,
6886        layout: &wgpu::BindGroupLayout,
6887        camera_buffer: &wgpu::Buffer,
6888        star_buffer: &wgpu::Buffer,
6889    ) -> wgpu::BindGroup {
6890        device.create_bind_group(&wgpu::BindGroupDescriptor {
6891            label: Some("strata_3d_stars_bg"),
6892            layout,
6893            entries: &[
6894                wgpu::BindGroupEntry {
6895                    binding: 0,
6896                    resource: camera_buffer.as_entire_binding(),
6897                },
6898                wgpu::BindGroupEntry {
6899                    binding: 1,
6900                    resource: star_buffer.as_entire_binding(),
6901                },
6902            ],
6903        })
6904    }
6905
6906    #[allow(clippy::too_many_arguments)]
6907    fn create_shadow_ocean_bind_group(
6908        device: &wgpu::Device,
6909        layout: &wgpu::BindGroupLayout,
6910        shadow_view: &wgpu::TextureView,
6911        shadow_sampler: &wgpu::Sampler,
6912        ocean_buffer: &wgpu::Buffer,
6913        coastal_sdf_view: &wgpu::TextureView,
6914        coastal_sdf_sampler: &wgpu::Sampler,
6915    ) -> wgpu::BindGroup {
6916        device.create_bind_group(&wgpu::BindGroupDescriptor {
6917            label: Some("strata_3d_shadow_ocean_bg"),
6918            layout,
6919            entries: &[
6920                wgpu::BindGroupEntry {
6921                    binding: 0,
6922                    resource: wgpu::BindingResource::TextureView(shadow_view),
6923                },
6924                wgpu::BindGroupEntry {
6925                    binding: 1,
6926                    resource: wgpu::BindingResource::Sampler(shadow_sampler),
6927                },
6928                wgpu::BindGroupEntry {
6929                    binding: 2,
6930                    resource: ocean_buffer.as_entire_binding(),
6931                },
6932                wgpu::BindGroupEntry {
6933                    binding: 3,
6934                    resource: wgpu::BindingResource::TextureView(coastal_sdf_view),
6935                },
6936                wgpu::BindGroupEntry {
6937                    binding: 4,
6938                    resource: wgpu::BindingResource::Sampler(coastal_sdf_sampler),
6939                },
6940            ],
6941        })
6942    }
6943
6944    fn sync_shadow_and_ocean_resources(
6945        &mut self,
6946        shadows_active: bool,
6947        shadow_size: u32,
6948        ocean_opt: Option<&RetainedOceanSurface>,
6949    ) {
6950        let mut need_rebind = false;
6951        let clamped_shadow = shadow_size.clamp(512, 4096);
6952        if shadows_active {
6953            let needs_alloc = match self.shadow_target {
6954                Some((sz, _, _)) => sz != clamped_shadow,
6955                None => true,
6956            };
6957            if needs_alloc {
6958                let tex = self.device.create_texture(&wgpu::TextureDescriptor {
6959                    label: Some("strata_3d_shadow_map"),
6960                    size: wgpu::Extent3d {
6961                        width: clamped_shadow,
6962                        height: clamped_shadow,
6963                        depth_or_array_layers: 1,
6964                    },
6965                    mip_level_count: 1,
6966                    sample_count: 1,
6967                    dimension: wgpu::TextureDimension::D2,
6968                    format: wgpu::TextureFormat::Depth32Float,
6969                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT
6970                        | wgpu::TextureUsages::TEXTURE_BINDING,
6971                    view_formats: &[],
6972                });
6973                let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
6974                self.shadow_target = Some((clamped_shadow, tex, view));
6975                need_rebind = true;
6976            }
6977        }
6978
6979        let mut has_sdf = false;
6980        if let Some(ocean) = ocean_opt {
6981            if ocean.enabled && ocean.coastal_shoaling {
6982                if let Some(ref sdf) = ocean.coastal_sdf {
6983                    let expected_bytes = (sdf.width as usize)
6984                        .saturating_mul(sdf.height as usize)
6985                        .saturating_mul(4);
6986                    if sdf.width > 0 && sdf.height > 0 && sdf.rgba8.len() == expected_bytes {
6987                        has_sdf = true;
6988                        let needs_upload = match self.coastal_sdf_cached {
6989                            Some((id, rev, w, h, _, _)) => {
6990                                id != sdf.id || rev != sdf.revision || w != sdf.width || h != sdf.height
6991                            }
6992                            None => true,
6993                        };
6994                        if needs_upload {
6995                            let same_dims = match self.coastal_sdf_cached {
6996                                Some((_, _, w, h, _, _)) => w == sdf.width && h == sdf.height,
6997                                None => false,
6998                            };
6999                            if same_dims {
7000                                if let Some((id, rev, w, h, ref tex, _)) = self.coastal_sdf_cached.as_mut() {
7001                                    self.queue.write_texture(
7002                                        wgpu::TexelCopyTextureInfo {
7003                                            texture: tex,
7004                                            mip_level: 0,
7005                                            origin: wgpu::Origin3d::ZERO,
7006                                            aspect: wgpu::TextureAspect::All,
7007                                        },
7008                                        &sdf.rgba8,
7009                                        wgpu::TexelCopyBufferLayout {
7010                                            offset: 0,
7011                                            bytes_per_row: Some(*w * 4),
7012                                            rows_per_image: Some(*h),
7013                                        },
7014                                        wgpu::Extent3d {
7015                                            width: *w,
7016                                            height: *h,
7017                                            depth_or_array_layers: 1,
7018                                        },
7019                                    );
7020                                    *id = sdf.id;
7021                                    *rev = sdf.revision;
7022                                }
7023                            } else {
7024                                let tex = self.device.create_texture(&wgpu::TextureDescriptor {
7025                                    label: Some("strata_3d_coastal_sdf_tex"),
7026                                    size: wgpu::Extent3d {
7027                                        width: sdf.width,
7028                                        height: sdf.height,
7029                                        depth_or_array_layers: 1,
7030                                    },
7031                                    mip_level_count: 1,
7032                                    sample_count: 1,
7033                                    dimension: wgpu::TextureDimension::D2,
7034                                    format: wgpu::TextureFormat::Rgba8Unorm,
7035                                    usage: wgpu::TextureUsages::TEXTURE_BINDING
7036                                        | wgpu::TextureUsages::COPY_DST,
7037                                    view_formats: &[],
7038                                });
7039                                self.queue.write_texture(
7040                                    wgpu::TexelCopyTextureInfo {
7041                                        texture: &tex,
7042                                        mip_level: 0,
7043                                        origin: wgpu::Origin3d::ZERO,
7044                                        aspect: wgpu::TextureAspect::All,
7045                                    },
7046                                    &sdf.rgba8,
7047                                    wgpu::TexelCopyBufferLayout {
7048                                        offset: 0,
7049                                        bytes_per_row: Some(sdf.width * 4),
7050                                        rows_per_image: Some(sdf.height),
7051                                    },
7052                                    wgpu::Extent3d {
7053                                        width: sdf.width,
7054                                        height: sdf.height,
7055                                        depth_or_array_layers: 1,
7056                                    },
7057                                );
7058                                let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
7059                                self.coastal_sdf_cached =
7060                                    Some((sdf.id, sdf.revision, sdf.width, sdf.height, tex, view));
7061                                need_rebind = true;
7062                            }
7063                        }
7064                    }
7065                }
7066            }
7067            let gpu_ocean = GpuOceanUniforms::from_retained(ocean, has_sdf);
7068            self.queue.write_buffer(
7069                &self.ocean_uniform_buffer,
7070                0,
7071                bytemuck::bytes_of(&gpu_ocean),
7072            );
7073        } else {
7074            self.queue.write_buffer(
7075                &self.ocean_uniform_buffer,
7076                0,
7077                bytemuck::bytes_of(&GpuOceanUniforms::disabled()),
7078            );
7079        }
7080
7081        if need_rebind {
7082            let shadow_view = self
7083                .shadow_target
7084                .as_ref()
7085                .map(|(_, _, v)| v)
7086                .unwrap_or(&self.shadow_fallback_view);
7087            let sdf_view = self
7088                .coastal_sdf_cached
7089                .as_ref()
7090                .map(|(_, _, _, _, _, v)| v)
7091                .unwrap_or(&self.coastal_sdf_fallback_view);
7092            self.shadow_ocean_bind_group = Self::create_shadow_ocean_bind_group(
7093                &self.device,
7094                &self.shadow_ocean_bgl,
7095                shadow_view,
7096                &self.shadow_sampler,
7097                &self.ocean_uniform_buffer,
7098                sdf_view,
7099                &self.coastal_sdf_sampler,
7100            );
7101        }
7102    }
7103
7104    fn create_terrain_bind_group(
7105        device: &wgpu::Device,
7106        layout: &wgpu::BindGroupLayout,
7107        camera_buffer: &wgpu::Buffer,
7108        slab_buffer: &wgpu::Buffer,
7109        instance_buffer: &wgpu::Buffer,
7110        atlas_view: &wgpu::TextureView,
7111        sampler: &wgpu::Sampler,
7112        land_mask_view: &wgpu::TextureView,
7113        env_wrap_sampler: &wgpu::Sampler,
7114    ) -> wgpu::BindGroup {
7115        device.create_bind_group(&wgpu::BindGroupDescriptor {
7116            label: Some("strata_3d_terrain_bg"),
7117            layout,
7118            entries: &[
7119                wgpu::BindGroupEntry {
7120                    binding: 0,
7121                    resource: camera_buffer.as_entire_binding(),
7122                },
7123                wgpu::BindGroupEntry {
7124                    binding: 1,
7125                    resource: slab_buffer.as_entire_binding(),
7126                },
7127                wgpu::BindGroupEntry {
7128                    binding: 2,
7129                    resource: instance_buffer.as_entire_binding(),
7130                },
7131                wgpu::BindGroupEntry {
7132                    binding: 3,
7133                    resource: wgpu::BindingResource::TextureView(atlas_view),
7134                },
7135                wgpu::BindGroupEntry {
7136                    binding: 4,
7137                    resource: wgpu::BindingResource::Sampler(sampler),
7138                },
7139                wgpu::BindGroupEntry {
7140                    binding: 5,
7141                    resource: wgpu::BindingResource::TextureView(land_mask_view),
7142                },
7143                wgpu::BindGroupEntry {
7144                    binding: 6,
7145                    resource: wgpu::BindingResource::Sampler(env_wrap_sampler),
7146                },
7147            ],
7148        })
7149    }
7150
7151    fn upload_environment_assets(&mut self, env: &RetainedEnvironmentAssets) -> bool {
7152        let perf = gpu_perf_logging_enabled();
7153        let mut terrain_rebind = false;
7154
7155        if let Some(ref land) = env.land_mask {
7156            let key = Some((land.id, land.revision));
7157            if self.env_state.land_mask_id_rev != key {
7158                let t0 = std::time::Instant::now();
7159                self.env_state.land_mask_view = create_rgba8_2d_view_opts(
7160                    &self.device,
7161                    &self.queue,
7162                    "strata_env_land_mask",
7163                    land.width,
7164                    land.height,
7165                    &land.rgba8,
7166                    MipGenMode::LinearBox,
7167                );
7168                if perf {
7169                    eprintln!("[perf] env land_mask {}x{} -> {:.2}ms", land.width, land.height, t0.elapsed().as_secs_f64() * 1000.0);
7170                }
7171                self.env_state.land_mask_id_rev = key;
7172                terrain_rebind = true;
7173            }
7174        }
7175
7176        if let Some(ref clouds) = env.cloud_map {
7177            let key = Some((clouds.id, clouds.revision));
7178            if self.env_state.cloud_map_id_rev != key {
7179                let t0 = std::time::Instant::now();
7180                self.env_state.cloud_map_view = create_cloud_density_r8_view(
7181                    &self.device,
7182                    &self.queue,
7183                    "strata_env_cloud_map",
7184                    clouds.width,
7185                    clouds.height,
7186                    &clouds.rgba8,
7187                );
7188                if perf {
7189                    eprintln!("[perf] env cloud_map {}x{} -> {:.2}ms", clouds.width, clouds.height, t0.elapsed().as_secs_f64() * 1000.0);
7190                }
7191                self.env_state.cloud_map_id_rev = key;
7192                self.cloud_bind_group = Self::create_cloud_bind_group(
7193                    &self.device,
7194                    &self.cloud_bind_group_layout,
7195                    "strata_3d_cloud_bg",
7196                    &self.camera_buffer,
7197                    &self.env_state.cloud_map_view,
7198                    &self.env_state.env_sampler,
7199                    &self.env_state.cloud_noise_view,
7200                    &self.env_state.cloud_noise_sampler,
7201                );
7202            }
7203        }
7204
7205        let mut sky_rebind = false;
7206
7207        if let Some(ref moon) = env.moon_texture {
7208            let key = Some((moon.id, moon.revision));
7209            if self.env_state.moon_tex_id_rev != key {
7210                let t0 = std::time::Instant::now();
7211                self.env_state.moon_view = create_rgba8_2d_view(
7212                    &self.device,
7213                    &self.queue,
7214                    "strata_env_moon_tex",
7215                    moon.width,
7216                    moon.height,
7217                    &moon.rgba8,
7218                );
7219                if perf {
7220                    eprintln!("[perf] env moon {}x{} -> {:.2}ms", moon.width, moon.height, t0.elapsed().as_secs_f64() * 1000.0);
7221                }
7222                self.env_state.moon_tex_id_rev = key;
7223                sky_rebind = true;
7224            }
7225        }
7226
7227        match &env.skybox_cubemap {
7228            Some(cube) => {
7229                let key = Some((cube.id, cube.revision));
7230                if self.env_state.skybox_cube_id_rev != key {
7231                    let t0 = std::time::Instant::now();
7232                    self.env_state.skybox_cube_view = create_rgba8_cube_view(
7233                        &self.device,
7234                        &self.queue,
7235                        "strata_env_skybox_cube",
7236                        cube.face_size,
7237                        &cube.faces_rgba8,
7238                        wgpu::TextureFormat::Rgba8Unorm,
7239                    );
7240                    if perf {
7241                        eprintln!("[perf] env skybox 6x{} -> {:.2}ms", cube.face_size, t0.elapsed().as_secs_f64() * 1000.0);
7242                    }
7243                    self.env_state.skybox_cube_id_rev = key;
7244                    sky_rebind = true;
7245                }
7246            }
7247            None => {
7248                if self.env_state.skybox_cube_id_rev.is_some() {
7249                    let black_face = Arc::new(vec![0u8, 0, 0, 0]);
7250                    self.env_state.skybox_cube_view = create_rgba8_cube_view(
7251                        &self.device,
7252                        &self.queue,
7253                        "strata_env_skybox_fallback",
7254                        1,
7255                        &[
7256                            Arc::clone(&black_face),
7257                            Arc::clone(&black_face),
7258                            Arc::clone(&black_face),
7259                            Arc::clone(&black_face),
7260                            Arc::clone(&black_face),
7261                            black_face,
7262                        ],
7263                        wgpu::TextureFormat::Rgba8Unorm,
7264                    );
7265                    self.env_state.skybox_cube_id_rev = None;
7266                    sky_rebind = true;
7267                }
7268            }
7269        }
7270
7271        if sky_rebind {
7272            self.sky_bind_group = Self::create_sky_bind_group(
7273                &self.device,
7274                &self.sky_bind_group_layout,
7275                &self.camera_buffer,
7276                &self.env_state.moon_view,
7277                &self.env_state.env_sampler,
7278                &self.env_state.skybox_cube_view,
7279            );
7280        }
7281
7282        if let Some(ref stars) = env.stars {
7283            let ptr = Arc::as_ptr(stars) as usize;
7284            let len = stars.len();
7285            if self.env_state.stars_ptr != ptr || self.env_state.stars_len != len {
7286                let gpu_stars: Vec<GpuStar> = stars
7287                    .iter()
7288                    .map(|s: &RetainedStar| GpuStar {
7289                        icrf_dir_mag: [s.icrf_dir[0], s.icrf_dir[1], s.icrf_dir[2], s.vmag],
7290                        color: s.color,
7291                    })
7292                    .collect();
7293                if gpu_stars.len() > self.env_state.star_capacity {
7294                    let new_cap = gpu_stars.len().next_power_of_two().max(64);
7295                    self.env_state.star_buffer =
7296                        self.device.create_buffer(&wgpu::BufferDescriptor {
7297                            label: Some("strata_3d_stars_grown"),
7298                            size: (new_cap * std::mem::size_of::<GpuStar>()) as u64,
7299                            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
7300                            mapped_at_creation: false,
7301                        });
7302                    self.env_state.star_capacity = new_cap;
7303                    self.star_bind_group = Self::create_star_bind_group(
7304                        &self.device,
7305                        &self.star_bind_group_layout,
7306                        &self.camera_buffer,
7307                        &self.env_state.star_buffer,
7308                    );
7309                }
7310                if !gpu_stars.is_empty() {
7311                    self.queue.write_buffer(
7312                        &self.env_state.star_buffer,
7313                        0,
7314                        bytemuck::cast_slice(&gpu_stars),
7315                    );
7316                }
7317                self.env_state.stars_ptr = ptr;
7318                self.env_state.stars_len = len;
7319                self.env_state.star_count = gpu_stars.len() as u32;
7320            }
7321        }
7322
7323        terrain_rebind
7324    }
7325
7326    fn ensure_topology(&mut self, grid_res: u32, has_skirts: bool) -> (wgpu::Buffer, u32) {
7327        if let Some(cached) = self.topologies.get(&(grid_res, has_skirts)) {
7328            return (cached.buffer.clone(), cached.index_count);
7329        }
7330        let indices = build_terrain_grid_indices(grid_res, has_skirts);
7331        let count = indices.len() as u32;
7332        let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
7333            label: Some("strata_3d_grid_topology"),
7334            size: (indices.len() * 4) as u64,
7335            usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
7336            mapped_at_creation: false,
7337        });
7338        if !indices.is_empty() {
7339            self.queue
7340                .write_buffer(&buffer, 0, bytemuck::cast_slice(&indices));
7341        }
7342        self.topologies.insert(
7343            (grid_res, has_skirts),
7344            CachedIndexTopology {
7345                buffer: buffer.clone(),
7346                index_count: count,
7347            },
7348        );
7349        (buffer, count)
7350    }
7351
7352    fn ensure_depth_view(&mut self, width: u32, height: u32) -> wgpu::TextureView {
7353        if let Some((w, h, view)) = &self.depth_target {
7354            if *w == width && *h == height {
7355                return view.clone();
7356            }
7357        }
7358        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
7359            label: Some("strata_3d_depth"),
7360            size: wgpu::Extent3d {
7361                width: width.max(1),
7362                height: height.max(1),
7363                depth_or_array_layers: 1,
7364            },
7365            mip_level_count: 1,
7366            sample_count: 1,
7367            dimension: wgpu::TextureDimension::D2,
7368            format: wgpu::TextureFormat::Depth32Float,
7369            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
7370            view_formats: &[],
7371        });
7372        let view = tex.create_view(&Default::default());
7373        self.depth_target = Some((width, height, view.clone()));
7374        view
7375    }
7376
7377    /// Creates an RGBA `wgpu::BindGroup` for compositing a 2D UI HUD texture over a 3D frame.
7378    pub fn create_overlay_bind_group(&self, overlay_view: &wgpu::TextureView) -> wgpu::BindGroup {
7379        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
7380            label: Some("strata_2d_overlay_bg"),
7381            layout: &self.overlay_bind_group_layout,
7382            entries: &[
7383                wgpu::BindGroupEntry {
7384                    binding: 0,
7385                    resource: wgpu::BindingResource::TextureView(overlay_view),
7386                },
7387                wgpu::BindGroupEntry {
7388                    binding: 1,
7389                    resource: wgpu::BindingResource::Sampler(&self.overlay_sampler),
7390                },
7391            ],
7392        })
7393    }
7394
7395    /// Draws `scene` (or its [`RetainedScene3D`] / [`RetainedTerrainFrame`]) directly into `target_view`.
7396    ///
7397    /// When `viewport` is `Some([x, y, w, h])`, restricts rendering to that sub-rectangle of the
7398    /// render target and uses `w/h` as the projection aspect ratio.
7399    pub fn render_scene_to_view(
7400        &mut self,
7401        scene: &Scene3D,
7402        target_view: &wgpu::TextureView,
7403        target_width: u32,
7404        target_height: u32,
7405        viewport: Option<[f32; 4]>,
7406        unlimited_upload_budget: bool,
7407    ) {
7408        self.render_scene_and_overlay_to_view(
7409            scene,
7410            target_view,
7411            target_width,
7412            target_height,
7413            viewport,
7414            unlimited_upload_budget,
7415            None,
7416        );
7417    }
7418
7419    /// Draws `scene` and optionally composites the cached 2D HUD `overlay_bind_group` into
7420    /// `target_view` using a single `CommandEncoder` and a single `queue.submit`.
7421    pub fn render_scene_and_overlay_to_view(
7422        &mut self,
7423        scene: &Scene3D,
7424        target_view: &wgpu::TextureView,
7425        target_width: u32,
7426        target_height: u32,
7427        viewport: Option<[f32; 4]>,
7428        unlimited_upload_budget: bool,
7429        overlay_bind_group: Option<&wgpu::BindGroup>,
7430    ) {
7431        self.render_scene_to_view_internal(
7432            scene,
7433            target_view,
7434            target_width,
7435            target_height,
7436            viewport,
7437            unlimited_upload_budget,
7438            true,
7439            false,
7440            overlay_bind_group,
7441        );
7442    }
7443
7444    /// Renders `scene` into `target_view` inside `viewport` without clearing prior color pixels,
7445    /// allowing previously rendered 2D UI layers behind the 3D viewport to remain intact.
7446    pub fn render_scene_preserving_color_to_view(
7447        &mut self,
7448        scene: &Scene3D,
7449        target_view: &wgpu::TextureView,
7450        target_width: u32,
7451        target_height: u32,
7452        viewport: Option<[f32; 4]>,
7453        unlimited_upload_budget: bool,
7454    ) {
7455        self.render_scene_to_view_internal(
7456            scene,
7457            target_view,
7458            target_width,
7459            target_height,
7460            viewport,
7461            unlimited_upload_budget,
7462            false,
7463            true,
7464            None,
7465        );
7466    }
7467
7468    /// Renders multiple 3D viewports (`(viewport_rect, scene)`) sequentially into `target_view`
7469    /// without clearing prior viewports, and composites `overlay_bind_group` once on the final pass.
7470    pub fn render_viewports_and_overlay_to_view(
7471        &mut self,
7472        viewports: &[([f32; 4], &Scene3D)],
7473        target_view: &wgpu::TextureView,
7474        target_width: u32,
7475        target_height: u32,
7476        unlimited_upload_budget: bool,
7477        overlay_bind_group: Option<&wgpu::BindGroup>,
7478    ) {
7479        if viewports.is_empty() {
7480            if let Some(ov_bg) = overlay_bind_group {
7481                self.composite_overlay_to_view(target_view, ov_bg);
7482            }
7483            return;
7484        }
7485        let multi = viewports.len() > 1;
7486        for (idx, &(vp, scene)) in viewports.iter().enumerate() {
7487            let is_first = idx == 0;
7488            let is_last = idx + 1 == viewports.len();
7489            self.render_scene_to_view_internal(
7490                scene,
7491                target_view,
7492                target_width,
7493                target_height,
7494                Some(vp),
7495                unlimited_upload_budget,
7496                is_first,
7497                multi,
7498                if is_last { overlay_bind_group } else { None },
7499            );
7500        }
7501    }
7502
7503    #[allow(clippy::too_many_arguments)]
7504    fn render_scene_to_view_internal(
7505        &mut self,
7506        scene: &Scene3D,
7507        target_view: &wgpu::TextureView,
7508        target_width: u32,
7509        target_height: u32,
7510        viewport: Option<[f32; 4]>,
7511        unlimited_upload_budget: bool,
7512        clear_color_target: bool,
7513        multi_viewport_mode: bool,
7514        overlay_bind_group: Option<&wgpu::BindGroup>,
7515    ) {
7516        let perf = gpu_perf_logging_enabled();
7517        let t_start = std::time::Instant::now();
7518        let mut t_env = 0.0f64;
7519        let mut t_slab = 0.0f64;
7520        let mut t_atlas = 0.0f64;
7521        let mut t_inst = 0.0f64;
7522        let mut t_dyn = 0.0f64;
7523
7524        self.frame_index += 1;
7525        let frame_idx = self.frame_index;
7526        let mesh_budget = usize::MAX;
7527        let tex_budget = if unlimited_upload_budget || frame_idx <= 2 {
7528            usize::MAX
7529        } else {
7530            DEFAULT_TEXTURE_UPLOAD_BUDGET
7531        };
7532
7533        let vp_w_u32 = viewport
7534            .map(|v| v[2].max(1.0).round() as u32)
7535            .unwrap_or_else(|| target_width.max(1));
7536        let vp_h_u32 = viewport
7537            .map(|v| v[3].max(1.0).round() as u32)
7538            .unwrap_or_else(|| target_height.max(1));
7539
7540        let (cam, terrain_frame_opt) = if let Some(retained) = scene.retained_handle() {
7541            let terrain = retained.snapshot_terrain();
7542            let cam = retained.camera();
7543            (cam, terrain)
7544        } else if let Some(terrain) = scene.retained_terrain() {
7545            (terrain.camera, Some(Arc::clone(terrain)))
7546        } else {
7547            let scene_key = (scene as *const Scene3D as usize, vp_w_u32, vp_h_u32);
7548            let frame = if let Some((seq, existing)) = self.cached_fallback_frames.get_mut(&scene_key)
7549            {
7550                *seq = frame_idx;
7551                Arc::clone(existing)
7552            } else {
7553                let built = Arc::new(fallback_frame_from_scene3d(
7554                    scene,
7555                    vp_w_u32 as f32,
7556                    vp_h_u32 as f32,
7557                ));
7558                self.cached_fallback_frames
7559                    .insert(scene_key, (frame_idx, Arc::clone(&built)));
7560                built
7561            };
7562            (frame.camera, Some(frame))
7563        };
7564
7565        // 1. Update camera uniform buffer unconditionally (O(1) tiny uniform write).
7566        let vp_w = viewport
7567            .map(|v| v[2])
7568            .unwrap_or_else(|| target_width.max(1) as f32)
7569            .max(1.0);
7570        let vp_h = viewport
7571            .map(|v| v[3])
7572            .unwrap_or_else(|| target_height.max(1) as f32)
7573            .max(1.0);
7574        let (light_vp_rte, shadow_radius_m, shadows_active) =
7575            compute_shadow_light_vp_rte(&cam, cam.shadow_map_size);
7576        let gpu_cam = GpuCameraUniforms::from_retained(
7577            &cam,
7578            vp_w,
7579            vp_h,
7580            light_vp_rte,
7581            shadow_radius_m,
7582            shadows_active,
7583        );
7584        self.queue
7585            .write_buffer(&self.camera_buffer, 0, bytemuck::bytes_of(&gpu_cam));
7586
7587        // 2. Upload incremental tile meshes/textures, environment assets, and prepare draw instances.
7588        let mut draw_count = 0usize;
7589        let mut all_terrain_opaque = true;
7590        let mut terrain_batches: Vec<((u32, bool), std::ops::Range<u32>)> = Vec::new();
7591        let mut dynamic_draws: Vec<(u64, [f64; 3], [f32; 4], bool)> = Vec::new();
7592        let mut geo_opaque_batches: Vec<(u64, Option<u64>, std::ops::Range<u32>)> = Vec::new();
7593        let mut geo_transparent_batches: Vec<(u64, Option<u64>, std::ops::Range<u32>)> = Vec::new();
7594        let mut staged_geo_instances: Vec<GpuGeoInstance> = Vec::new();
7595
7596        if let Some(frame) = terrain_frame_opt.as_ref() {
7597            let frame_changed = frame.geometry_revision != self.last_geometry_rev
7598                || self
7599                    .last_terrain_frame
7600                    .as_ref()
7601                    .map(|p| !Arc::ptr_eq(p, frame))
7602                    .unwrap_or(true);
7603            let _ = frame_changed;
7604            self.last_geometry_rev = frame.geometry_revision;
7605            self.last_terrain_frame = Some(Arc::clone(frame));
7606
7607            let tp0 = std::time::Instant::now();
7608            let env_dirty = if let Some(ref env) = frame.environment {
7609                self.upload_environment_assets(env)
7610            } else {
7611                false
7612            };
7613            t_env = tp0.elapsed().as_secs_f64() * 1000.0;
7614
7615            let tp1 = std::time::Instant::now();
7616            let (bg_dirty, mesh_deferred) = self.slab.upload_meshes(
7617                &self.device,
7618                &self.queue,
7619                &frame.meshes,
7620                frame_idx,
7621                mesh_budget,
7622            );
7623            t_slab = tp1.elapsed().as_secs_f64() * 1000.0;
7624
7625            let tp2 = std::time::Instant::now();
7626            let tex_deferred = self
7627                .atlas
7628                .upload_textures(&self.queue, &frame.textures, frame_idx, tex_budget);
7629            t_atlas = tp2.elapsed().as_secs_f64() * 1000.0;
7630
7631            if mesh_deferred || tex_deferred {
7632                if let Some(retained) = scene.retained_handle() {
7633                    retained.request_gpu_continuation();
7634                }
7635            }
7636
7637            let tp3 = std::time::Instant::now();
7638            let mut tagged_instances: Vec<((u32, bool), GpuTileInstance)> =
7639                Vec::with_capacity(frame.instances.len());
7640            for inst in &frame.instances {
7641                let Some((base_v, grid_res, has_skirts)) =
7642                    self.slab.resident_slot(inst.key, inst.mesh_revision)
7643                else {
7644                    continue;
7645                };
7646                let (cx_hi, cx_lo) = split_f64_to_f32(inst.center_ecef[0]);
7647                let (cy_hi, cy_lo) = split_f64_to_f32(inst.center_ecef[1]);
7648                let (cz_hi, cz_lo) = split_f64_to_f32(inst.center_ecef[2]);
7649                let tex_layer = self.atlas.layer_for(inst.texture_id, inst.texture_revision);
7650                let night_layer = self
7651                    .atlas
7652                    .layer_for(inst.night_texture_id, inst.night_texture_revision);
7653                let eff_tint = if inst.texture_id.is_some() && tex_layer == 0 {
7654                    [0.14, 0.19, 0.27, 1.0]
7655                } else {
7656                    inst.tint
7657                };
7658                if eff_tint[3] < 0.999 {
7659                    all_terrain_opaque = false;
7660                }
7661                tagged_instances.push((
7662                    (grid_res, has_skirts),
7663                    GpuTileInstance {
7664                        center_high: [cx_hi, cy_hi, cz_hi, 0.0],
7665                        center_low: [cx_lo, cy_lo, cz_lo, 0.0],
7666                        uv_rect: inst.uv_rect,
7667                        night_uv_rect: inst.night_uv_rect,
7668                        tint: eff_tint,
7669                        tile_meta: [base_v, tex_layer, u32::from(inst.unlit), night_layer],
7670                    },
7671                ));
7672            }
7673            tagged_instances.sort_by_key(|(topo, _)| *topo);
7674            let mut instances_gpu: Vec<GpuTileInstance> =
7675                Vec::with_capacity(tagged_instances.len());
7676            for (topo, gpu_inst) in tagged_instances {
7677                let idx = instances_gpu.len() as u32;
7678                instances_gpu.push(gpu_inst);
7679                if let Some((last_topo, range)) = terrain_batches.last_mut() {
7680                    if *last_topo == topo && range.end == idx {
7681                        range.end = idx + 1;
7682                        continue;
7683                    }
7684                }
7685                terrain_batches.push((topo, idx..(idx + 1)));
7686            }
7687
7688            let mut instance_resized = false;
7689            if instances_gpu.len() > self.instance_capacity {
7690                let new_cap = instances_gpu.len().next_power_of_two().max(1024);
7691                self.instance_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
7692                    label: Some("strata_3d_tile_instances_grown"),
7693                    size: (new_cap * std::mem::size_of::<GpuTileInstance>()) as u64,
7694                    usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
7695                    mapped_at_creation: false,
7696                });
7697                self.instance_capacity = new_cap;
7698                instance_resized = true;
7699            }
7700            if bg_dirty || instance_resized || env_dirty {
7701                self.terrain_bind_group = Self::create_terrain_bind_group(
7702                    &self.device,
7703                    &self.terrain_bind_group_layout,
7704                    &self.camera_buffer,
7705                    &self.slab.buffer,
7706                    &self.instance_buffer,
7707                    &self.atlas.view,
7708                    &self.terrain_sampler,
7709                    &self.env_state.land_mask_view,
7710                    &self.env_state.env_sampler,
7711                );
7712            }
7713            if !instances_gpu.is_empty() {
7714                self.queue.write_buffer(
7715                    &self.instance_buffer,
7716                    0,
7717                    bytemuck::cast_slice(&instances_gpu),
7718                );
7719                draw_count = instances_gpu.len();
7720            }
7721            t_inst = tp3.elapsed().as_secs_f64() * 1000.0;
7722
7723            let tp4 = std::time::Instant::now();
7724            for dm in &frame.dynamic_meshes {
7725                if dm.vertices.is_empty() || dm.indices.is_empty() {
7726                    continue;
7727                }
7728                let vb_bytes: &[u8] = bytemuck::cast_slice(&dm.vertices);
7729                let ib_bytes: &[u8] = bytemuck::cast_slice(&dm.indices);
7730                let mut need_recreate = true;
7731                if let Some(existing) = self.dynamic_meshes.get_mut(&dm.id) {
7732                    existing.last_used_seq = frame_idx;
7733                    if existing.revision == dm.revision {
7734                        need_recreate = false;
7735                    } else if existing.vbuf.size() >= vb_bytes.len() as u64
7736                        && existing.ibuf.size() >= ib_bytes.len() as u64
7737                    {
7738                        self.queue.write_buffer(&existing.vbuf, 0, vb_bytes);
7739                        self.queue.write_buffer(&existing.ibuf, 0, ib_bytes);
7740                        existing.revision = dm.revision;
7741                        existing.index_count = dm.indices.len() as u32;
7742                        need_recreate = false;
7743                    }
7744                }
7745                if need_recreate {
7746                    let vbuf = self.device.create_buffer(&wgpu::BufferDescriptor {
7747                        label: Some("strata_3d_dyn_vb"),
7748                        size: (vb_bytes.len() as u64).next_power_of_two().max(256),
7749                        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
7750                        mapped_at_creation: false,
7751                    });
7752                    self.queue.write_buffer(&vbuf, 0, vb_bytes);
7753                    let ibuf = self.device.create_buffer(&wgpu::BufferDescriptor {
7754                        label: Some("strata_3d_dyn_ib"),
7755                        size: (ib_bytes.len() as u64).next_power_of_two().max(64),
7756                        usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
7757                        mapped_at_creation: false,
7758                    });
7759                    self.queue.write_buffer(&ibuf, 0, ib_bytes);
7760                    self.dynamic_meshes.insert(
7761                        dm.id,
7762                        CachedDynamicGpuMesh {
7763                            revision: dm.revision,
7764                            vbuf,
7765                            ibuf,
7766                            index_count: dm.indices.len() as u32,
7767                            last_used_seq: frame_idx,
7768                        },
7769                    );
7770                }
7771                dynamic_draws.push((dm.id, dm.anchor_ecef, dm.color, dm.unlit));
7772            }
7773
7774            for asset in frame.geo_mesh_assets.iter() {
7775                if asset.vertices.is_empty() || asset.indices.is_empty() {
7776                    continue;
7777                }
7778                let asset_tex_id = asset
7779                    .albedo_texture
7780                    .as_deref()
7781                    .and_then(|tex| self.ensure_geo_texture(tex, frame_idx))
7782                    .map(|(tid, _)| tid);
7783                let mut need_upload = true;
7784                if let Some(existing) = self.geo_meshes.get_mut(&asset.id) {
7785                    existing.last_used_seq = frame_idx;
7786                    existing.albedo_tex_id = asset_tex_id;
7787                    if existing.revision == asset.revision {
7788                        need_upload = false;
7789                    }
7790                }
7791                if need_upload {
7792                    let mut packed_verts: Vec<GpuGeoVertex> =
7793                        Vec::with_capacity(asset.vertices.len());
7794                    let mut has_vertex_alpha = false;
7795                    let vcols = asset.vertex_colors.as_deref();
7796                    for (vi, v) in asset.vertices.iter().enumerate() {
7797                        let c = vcols
7798                            .and_then(|cols| cols.get(vi).copied())
7799                            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
7800                        if c[3] < 0.999 {
7801                            has_vertex_alpha = true;
7802                        }
7803                        packed_verts.push(GpuGeoVertex {
7804                            pos_u: v.pos_u,
7805                            norm_v: v.norm_v,
7806                            color: c,
7807                        });
7808                    }
7809                    let vb_bytes: &[u8] = bytemuck::cast_slice(&packed_verts);
7810                    let ib_bytes: &[u8] = bytemuck::cast_slice(&asset.indices);
7811                    let mut need_recreate = true;
7812                    if let Some(existing) = self.geo_meshes.get_mut(&asset.id) {
7813                        if existing.vbuf.size() >= vb_bytes.len() as u64
7814                            && existing.ibuf.size() >= ib_bytes.len() as u64
7815                        {
7816                            self.queue.write_buffer(&existing.vbuf, 0, vb_bytes);
7817                            self.queue.write_buffer(&existing.ibuf, 0, ib_bytes);
7818                            existing.revision = asset.revision;
7819                            existing.index_count = asset.indices.len() as u32;
7820                            existing.has_vertex_alpha = has_vertex_alpha;
7821                            existing.albedo_tex_id = asset_tex_id;
7822                            existing.last_used_seq = frame_idx;
7823                            need_recreate = false;
7824                        }
7825                    }
7826                    if need_recreate {
7827                        let vbuf = self.device.create_buffer(&wgpu::BufferDescriptor {
7828                            label: Some("strata_3d_geo_vb"),
7829                            size: (vb_bytes.len() as u64).next_power_of_two().max(256),
7830                            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
7831                            mapped_at_creation: false,
7832                        });
7833                        self.queue.write_buffer(&vbuf, 0, vb_bytes);
7834                        let ibuf = self.device.create_buffer(&wgpu::BufferDescriptor {
7835                            label: Some("strata_3d_geo_ib"),
7836                            size: (ib_bytes.len() as u64).next_power_of_two().max(64),
7837                            usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
7838                            mapped_at_creation: false,
7839                        });
7840                        self.queue.write_buffer(&ibuf, 0, ib_bytes);
7841                        self.geo_meshes.insert(
7842                            asset.id,
7843                            CachedGeoGpuMesh {
7844                                revision: asset.revision,
7845                                vbuf,
7846                                ibuf,
7847                                index_count: asset.indices.len() as u32,
7848                                has_vertex_alpha,
7849                                albedo_tex_id: asset_tex_id,
7850                                last_used_seq: frame_idx,
7851                            },
7852                        );
7853                    }
7854                }
7855            }
7856
7857            if !frame.geo_instances.is_empty() {
7858                let mut opaque_items: Vec<(u64, Option<u64>, GpuGeoInstance)> =
7859                    Vec::with_capacity(frame.geo_instances.len());
7860                let mut transparent_items: Vec<(f64, u64, Option<u64>, GpuGeoInstance)> =
7861                    Vec::new();
7862
7863                for inst in frame.geo_instances.iter() {
7864                    let inst_tex_info = inst
7865                        .albedo_texture
7866                        .as_deref()
7867                        .and_then(|tex| self.ensure_geo_texture(tex, frame_idx));
7868                    let Some((mesh_has_alpha, mesh_tex_id)) =
7869                        self.geo_meshes.get_mut(&inst.mesh_id).map(|m| {
7870                            m.last_used_seq = frame_idx;
7871                            (m.has_vertex_alpha, m.albedo_tex_id)
7872                        })
7873                    else {
7874                        continue;
7875                    };
7876                    let (eff_tex_id, tex_has_alpha) = if let Some((tid, t_alpha)) = inst_tex_info {
7877                        (Some(tid), t_alpha)
7878                    } else if let Some(tid) = mesh_tex_id {
7879                        let t_alpha = self
7880                            .geo_textures
7881                            .get_mut(&tid)
7882                            .map(|t| {
7883                                t.last_used_seq = frame_idx;
7884                                t.has_alpha
7885                            })
7886                            .unwrap_or(false);
7887                        (Some(tid), t_alpha)
7888                    } else {
7889                        (None, false)
7890                    };
7891
7892                    let (ax_hi, ax_lo) = split_f64_to_f32(inst.anchor_ecef[0]);
7893                    let (ay_hi, ay_lo) = split_f64_to_f32(inst.anchor_ecef[1]);
7894                    let (az_hi, az_lo) = split_f64_to_f32(inst.anchor_ecef[2]);
7895                    let gpu_inst = GpuGeoInstance {
7896                        anchor_high: [ax_hi, ay_hi, az_hi, 0.0],
7897                        anchor_low: [ax_lo, ay_lo, az_lo, 0.0],
7898                        col0: [
7899                            inst.model_cols[0][0],
7900                            inst.model_cols[0][1],
7901                            inst.model_cols[0][2],
7902                            inst.roughness,
7903                        ],
7904                        col1: [
7905                            inst.model_cols[1][0],
7906                            inst.model_cols[1][1],
7907                            inst.model_cols[1][2],
7908                            inst.metalness,
7909                        ],
7910                        col2: [
7911                            inst.model_cols[2][0],
7912                            inst.model_cols[2][1],
7913                            inst.model_cols[2][2],
7914                            if inst.unlit { 1.0 } else { 0.0 },
7915                        ],
7916                        base_color: inst.base_color,
7917                        emissive: [
7918                            inst.emissive_rgb[0],
7919                            inst.emissive_rgb[1],
7920                            inst.emissive_rgb[2],
7921                            inst.accent_mix,
7922                        ],
7923                    };
7924                    let is_transparent =
7925                        inst.base_color[3] < 0.999 || mesh_has_alpha || tex_has_alpha;
7926                    if !is_transparent {
7927                        opaque_items.push((inst.mesh_id, eff_tex_id, gpu_inst));
7928                    } else {
7929                        let dx = inst.anchor_ecef[0] - cam.eye_ecef[0];
7930                        let dy = inst.anchor_ecef[1] - cam.eye_ecef[1];
7931                        let dz = inst.anchor_ecef[2] - cam.eye_ecef[2];
7932                        let dist_sq = dx * dx + dy * dy + dz * dz;
7933                        transparent_items.push((dist_sq, inst.mesh_id, eff_tex_id, gpu_inst));
7934                    }
7935                }
7936
7937                opaque_items.sort_by_key(|(mesh_id, tex_id, _)| (*mesh_id, *tex_id));
7938                // Sort transparent instances back-to-front (largest distance from camera eye first).
7939                transparent_items.sort_by(|a, b| b.0.total_cmp(&a.0));
7940                staged_geo_instances.reserve(opaque_items.len() + transparent_items.len());
7941
7942                let push_batches =
7943                    |items: Vec<(u64, Option<u64>, GpuGeoInstance)>,
7944                     staged: &mut Vec<GpuGeoInstance>,
7945                     batches: &mut Vec<(u64, Option<u64>, std::ops::Range<u32>)>| {
7946                        for (mesh_id, tex_id, gpu_inst) in items {
7947                            let idx = staged.len() as u32;
7948                            staged.push(gpu_inst);
7949                            if let Some((last_id, last_tex, range)) = batches.last_mut() {
7950                                if *last_id == mesh_id && *last_tex == tex_id && range.end == idx {
7951                                    range.end = idx + 1;
7952                                    continue;
7953                                }
7954                            }
7955                            batches.push((mesh_id, tex_id, idx..(idx + 1)));
7956                        }
7957                    };
7958                push_batches(
7959                    opaque_items,
7960                    &mut staged_geo_instances,
7961                    &mut geo_opaque_batches,
7962                );
7963                let sorted_transparent: Vec<(u64, Option<u64>, GpuGeoInstance)> = transparent_items
7964                    .into_iter()
7965                    .map(|(_, mid, tid, gi)| (mid, tid, gi))
7966                    .collect();
7967                push_batches(
7968                    sorted_transparent,
7969                    &mut staged_geo_instances,
7970                    &mut geo_transparent_batches,
7971                );
7972            }
7973
7974            // Evict deleted/unreferenced geo meshes, geo textures, dynamic meshes, and fallback scenes
7975            // after a 32-frame grace window (prevents VRAM leaks while allowing multi-viewport sharing).
7976            const GEO_CACHE_EVICT_FRAMES: u64 = 32;
7977            self.geo_meshes
7978                .retain(|_, m| frame_idx.saturating_sub(m.last_used_seq) <= GEO_CACHE_EVICT_FRAMES);
7979            self.geo_textures
7980                .retain(|_, t| frame_idx.saturating_sub(t.last_used_seq) <= GEO_CACHE_EVICT_FRAMES);
7981            self.dynamic_meshes
7982                .retain(|_, m| frame_idx.saturating_sub(m.last_used_seq) <= GEO_CACHE_EVICT_FRAMES);
7983            self.cached_fallback_frames
7984                .retain(|_, (seq, _)| frame_idx.saturating_sub(*seq) <= GEO_CACHE_EVICT_FRAMES);
7985
7986            t_dyn = tp4.elapsed().as_secs_f64() * 1000.0;
7987        }
7988
7989        if !staged_geo_instances.is_empty() {
7990            if staged_geo_instances.len() > self.geo_instance_capacity {
7991                let new_cap = staged_geo_instances.len().next_power_of_two().max(256);
7992                self.geo_instance_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
7993                    label: Some("strata_3d_geo_instances_grown"),
7994                    size: (new_cap * std::mem::size_of::<GpuGeoInstance>()) as u64,
7995                    usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
7996                    mapped_at_creation: false,
7997                });
7998                self.geo_instance_capacity = new_cap;
7999                self.geo_object_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
8000                    label: Some("strata_3d_geo_object_bg_grown"),
8001                    layout: &self.geo_object_bind_group_layout,
8002                    entries: &[
8003                        wgpu::BindGroupEntry {
8004                            binding: 0,
8005                            resource: self.camera_buffer.as_entire_binding(),
8006                        },
8007                        wgpu::BindGroupEntry {
8008                            binding: 1,
8009                            resource: self.geo_instance_buffer.as_entire_binding(),
8010                        },
8011                    ],
8012                });
8013            }
8014            self.queue.write_buffer(
8015                &self.geo_instance_buffer,
8016                0,
8017                bytemuck::cast_slice(&staged_geo_instances),
8018            );
8019        }
8020
8021        if !dynamic_draws.is_empty() {
8022            let stride = self.dynamic_uniform_stride as usize;
8023            if dynamic_draws.len() > self.dynamic_uniform_capacity {
8024                let new_cap = dynamic_draws.len().next_power_of_two().max(64);
8025                self.dynamic_uniform_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
8026                    label: Some("strata_3d_dynamic_uniforms_grown"),
8027                    size: (new_cap * stride) as u64,
8028                    usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
8029                    mapped_at_creation: false,
8030                });
8031                self.dynamic_uniform_capacity = new_cap;
8032                self.dynamic_bind_group =
8033                    self.device.create_bind_group(&wgpu::BindGroupDescriptor {
8034                        label: Some("strata_3d_dynamic_bg_grown"),
8035                        layout: &self.dynamic_bind_group_layout,
8036                        entries: &[
8037                            wgpu::BindGroupEntry {
8038                                binding: 0,
8039                                resource: self.camera_buffer.as_entire_binding(),
8040                            },
8041                            wgpu::BindGroupEntry {
8042                                binding: 1,
8043                                resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
8044                                    buffer: &self.dynamic_uniform_buffer,
8045                                    offset: 0,
8046                                    size: std::num::NonZeroU64::new(std::mem::size_of::<
8047                                        GpuDynamicUniforms,
8048                                    >(
8049                                    )
8050                                        as u64),
8051                                }),
8052                            },
8053                        ],
8054                    });
8055            }
8056            let mut staged = vec![0u8; dynamic_draws.len() * stride];
8057            for (i, (_, anchor, color, unlit)) in dynamic_draws.iter().enumerate() {
8058                let (ax_hi, ax_lo) = split_f64_to_f32(anchor[0]);
8059                let (ay_hi, ay_lo) = split_f64_to_f32(anchor[1]);
8060                let (az_hi, az_lo) = split_f64_to_f32(anchor[2]);
8061                let dyn_u = GpuDynamicUniforms {
8062                    anchor_high: [ax_hi, ay_hi, az_hi, 0.0],
8063                    anchor_low: [ax_lo, ay_lo, az_lo, 0.0],
8064                    color: *color,
8065                    dyn_meta: [u32::from(*unlit), 0, 0, 0],
8066                };
8067                let bytes = bytemuck::bytes_of(&dyn_u);
8068                staged[i * stride..i * stride + bytes.len()].copy_from_slice(bytes);
8069            }
8070            self.queue
8071                .write_buffer(&self.dynamic_uniform_buffer, 0, &staged);
8072        }
8073
8074        let mut particle_draws: Vec<(u32, Option<u64>)> = Vec::new();
8075        if let Some(frame) = terrain_frame_opt.as_ref() {
8076            if !frame.particle_layers.is_empty() {
8077                for tex in frame.particle_textures.iter() {
8078                    if tex.width == 0
8079                        || tex.height == 0
8080                        || tex.rgba8.len() < (tex.width as usize) * (tex.height as usize) * 4
8081                    {
8082                        continue;
8083                    }
8084                    let need_upload = match self.particle_textures.get(&tex.id) {
8085                        Some(cached) => {
8086                            cached.revision != tex.revision
8087                                || cached.width != tex.width
8088                                || cached.height != tex.height
8089                        }
8090                        None => true,
8091                    };
8092                    if need_upload {
8093                        let gpu_tex = self.device.create_texture(&wgpu::TextureDescriptor {
8094                            label: Some("strata_3d_particle_sprite_tex"),
8095                            size: wgpu::Extent3d {
8096                                width: tex.width,
8097                                height: tex.height,
8098                                depth_or_array_layers: 1,
8099                            },
8100                            mip_level_count: 1,
8101                            sample_count: 1,
8102                            dimension: wgpu::TextureDimension::D2,
8103                            format: wgpu::TextureFormat::Rgba8Unorm,
8104                            usage: wgpu::TextureUsages::TEXTURE_BINDING
8105                                | wgpu::TextureUsages::COPY_DST,
8106                            view_formats: &[],
8107                        });
8108                        self.queue.write_texture(
8109                            wgpu::TexelCopyTextureInfo {
8110                                texture: &gpu_tex,
8111                                mip_level: 0,
8112                                origin: wgpu::Origin3d::ZERO,
8113                                aspect: wgpu::TextureAspect::All,
8114                            },
8115                            &tex.rgba8[..(tex.width as usize) * (tex.height as usize) * 4],
8116                            wgpu::TexelCopyBufferLayout {
8117                                offset: 0,
8118                                bytes_per_row: Some(tex.width * 4),
8119                                rows_per_image: Some(tex.height),
8120                            },
8121                            wgpu::Extent3d {
8122                                width: tex.width,
8123                                height: tex.height,
8124                                depth_or_array_layers: 1,
8125                            },
8126                        );
8127                        let view = gpu_tex.create_view(&Default::default());
8128                        let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
8129                            label: Some("strata_3d_particle_sprite_bg"),
8130                            layout: &self.particle_tex_bgl,
8131                            entries: &[
8132                                wgpu::BindGroupEntry {
8133                                    binding: 0,
8134                                    resource: wgpu::BindingResource::TextureView(&view),
8135                                },
8136                                wgpu::BindGroupEntry {
8137                                    binding: 1,
8138                                    resource: wgpu::BindingResource::Sampler(
8139                                        &self.particle_sampler,
8140                                    ),
8141                                },
8142                            ],
8143                        });
8144                        self.particle_textures.insert(
8145                            tex.id,
8146                            CachedParticleTexture {
8147                                revision: tex.revision,
8148                                width: tex.width,
8149                                height: tex.height,
8150                                _texture: gpu_tex,
8151                                bind_group: bg,
8152                            },
8153                        );
8154                    }
8155                }
8156
8157                let norm3 = |v: [f32; 3], fallback: [f32; 3]| -> [f32; 3] {
8158                    let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
8159                    if l > 1e-6 {
8160                        [v[0] / l, v[1] / l, v[2] / l]
8161                    } else {
8162                        fallback
8163                    }
8164                };
8165                let cam_right = norm3(
8166                    [cam.view_rot[0][0], cam.view_rot[1][0], cam.view_rot[2][0]],
8167                    [1.0, 0.0, 0.0],
8168                );
8169                let cam_up = norm3(
8170                    [cam.view_rot[0][1], cam.view_rot[1][1], cam.view_rot[2][1]],
8171                    [0.0, 1.0, 0.0],
8172                );
8173                let meters_per_px_at_1m = 2.0 / (vp_h * cam.proj[1][1].abs().max(0.05));
8174
8175                let active_layers: Vec<&RetainedParticleLayer> = frame
8176                    .particle_layers
8177                    .iter()
8178                    .filter(|l| l.particle_count > 0 && l.color[3] > 0.002)
8179                    .collect();
8180                if !active_layers.is_empty() {
8181                    let stride = self.particle_uniform_stride as usize;
8182                    if active_layers.len() > self.particle_uniform_capacity {
8183                        let new_cap = active_layers.len().next_power_of_two().max(16);
8184                        let u_size = std::mem::size_of::<GpuParticleLayerUniforms>() as u64;
8185                        self.particle_uniform_buffer =
8186                            self.device.create_buffer(&wgpu::BufferDescriptor {
8187                                label: Some("strata_3d_particle_uniforms_grown"),
8188                                size: (new_cap * stride) as u64,
8189                                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
8190                                mapped_at_creation: false,
8191                            });
8192                        self.particle_uniform_capacity = new_cap;
8193                        self.particle_common_bind_group =
8194                            self.device.create_bind_group(&wgpu::BindGroupDescriptor {
8195                                label: Some("strata_3d_particle_common_bg_grown"),
8196                                layout: &self.particle_common_bgl,
8197                                entries: &[
8198                                    wgpu::BindGroupEntry {
8199                                        binding: 0,
8200                                        resource: self.camera_buffer.as_entire_binding(),
8201                                    },
8202                                    wgpu::BindGroupEntry {
8203                                        binding: 1,
8204                                        resource: wgpu::BindingResource::Buffer(
8205                                            wgpu::BufferBinding {
8206                                                buffer: &self.particle_uniform_buffer,
8207                                                offset: 0,
8208                                                size: std::num::NonZeroU64::new(u_size),
8209                                            },
8210                                        ),
8211                                    },
8212                                ],
8213                            });
8214                    }
8215                    let mut staged = vec![0u8; active_layers.len() * stride];
8216                    for (i, layer) in active_layers.iter().enumerate() {
8217                        let (sprite_mode, tex_id_opt) = match layer.sprite {
8218                            RetainedParticleSprite::Textured(tid) => (0u32, Some(tid)),
8219                            RetainedParticleSprite::ProceduralStreak => (1u32, None),
8220                            RetainedParticleSprite::ProceduralSnowflake => (2u32, None),
8221                            RetainedParticleSprite::ProceduralPellet => (3u32, None),
8222                            RetainedParticleSprite::ProceduralCurtain => (4u32, None),
8223                        };
8224                        let billboard_mode = match layer.billboard {
8225                            RetainedParticleBillboard::VelocityAligned => 0u32,
8226                            RetainedParticleBillboard::CameraFacing => 1u32,
8227                        };
8228                        let gpu_u = GpuParticleLayerUniforms {
8229                            basis_east: [
8230                                layer.basis_east[0],
8231                                layer.basis_east[1],
8232                                layer.basis_east[2],
8233                                layer.wrapped_phase[0],
8234                            ],
8235                            basis_north: [
8236                                layer.basis_north[0],
8237                                layer.basis_north[1],
8238                                layer.basis_north[2],
8239                                layer.wrapped_phase[1],
8240                            ],
8241                            basis_up: [
8242                                layer.basis_up[0],
8243                                layer.basis_up[1],
8244                                layer.basis_up[2],
8245                                layer.wrapped_phase[2],
8246                            ],
8247                            forward_bias: [
8248                                layer.forward_bias_world[0],
8249                                layer.forward_bias_world[1],
8250                                layer.forward_bias_world[2],
8251                                0.0,
8252                            ],
8253                            cam_right_mpx: [
8254                                cam_right[0],
8255                                cam_right[1],
8256                                cam_right[2],
8257                                meters_per_px_at_1m,
8258                            ],
8259                            cam_up_pad: [cam_up[0], cam_up[1], cam_up[2], 0.0],
8260                            altitude_bounds: layer.altitude_bounds,
8261                            volume_params: layer.volume_params,
8262                            motion_params: layer.motion_params,
8263                            size_params: layer.size_params,
8264                            flutter_clamp: layer.flutter_clamp,
8265                            color: layer.color,
8266                            meta: [sprite_mode, billboard_mode, layer.seed, layer.particle_count],
8267                        };
8268                        let bytes = bytemuck::bytes_of(&gpu_u);
8269                        staged[i * stride..i * stride + bytes.len()].copy_from_slice(bytes);
8270                        particle_draws.push((layer.particle_count, tex_id_opt));
8271                    }
8272                    self.queue
8273                        .write_buffer(&self.particle_uniform_buffer, 0, &staged);
8274                }
8275            }
8276        }
8277
8278        let ocean_opt = terrain_frame_opt.as_ref().and_then(|f| f.ocean.as_deref());
8279        self.sync_shadow_and_ocean_resources(shadows_active, cam.shadow_map_size, ocean_opt);
8280
8281        let topology_batches: Vec<(wgpu::Buffer, u32, std::ops::Range<u32>)> = terrain_batches
8282            .into_iter()
8283            .filter_map(|((g, s), range)| {
8284                let (buf, cnt) = self.ensure_topology(g, s);
8285                if cnt > 0 && !range.is_empty() {
8286                    Some((buf, cnt, range))
8287                } else {
8288                    None
8289                }
8290            })
8291            .collect();
8292        let depth_view = self.ensure_depth_view(target_width.max(1), target_height.max(1));
8293
8294        let clear_op = if !clear_color_target {
8295            wgpu::LoadOp::Load
8296        } else if multi_viewport_mode {
8297            wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)
8298        } else {
8299            match cam.background {
8300                Background3D::Transparent => wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
8301                Background3D::Solid(c) => wgpu::LoadOp::Clear(wgpu::Color {
8302                    r: c.r() as f64,
8303                    g: c.g() as f64,
8304                    b: c.b() as f64,
8305                    a: c.a() as f64,
8306                }),
8307                Background3D::VerticalGradient { .. } => wgpu::LoadOp::Clear(wgpu::Color::BLACK),
8308            }
8309        };
8310
8311        let tp_pass = std::time::Instant::now();
8312        let ts_slot = self
8313            .timestamp_profiler
8314            .as_mut()
8315            .and_then(|p| p.acquire_idle_slot(&self.device));
8316        let mut encoder = self
8317            .device
8318            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
8319                label: Some("strata_3d_render_encoder"),
8320            });
8321
8322        // Opt-in directional shadow map pass for 2.5D mountains & opaque 3D objects (0.00 ms when off).
8323        let mut wrote_shadow_ts = false;
8324        if shadows_active && (draw_count > 0 || !geo_opaque_batches.is_empty()) {
8325            if let Some((_, _, ref shadow_view)) = self.shadow_target {
8326                let shadow_ts = ts_slot.and_then(|slot_idx| {
8327                    self.timestamp_profiler.as_ref().map(|p| {
8328                        wrote_shadow_ts = true;
8329                        wgpu::RenderPassTimestampWrites {
8330                            query_set: &p.slots[slot_idx].query_set,
8331                            beginning_of_pass_write_index: Some(0),
8332                            end_of_pass_write_index: Some(1),
8333                        }
8334                    })
8335                });
8336                let mut spass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
8337                    label: Some("strata_3d_shadow_pass"),
8338                    color_attachments: &[],
8339                    depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
8340                        view: shadow_view,
8341                        depth_ops: Some(wgpu::Operations {
8342                            load: wgpu::LoadOp::Clear(1.0),
8343                            store: wgpu::StoreOp::Store,
8344                        }),
8345                        stencil_ops: None,
8346                    }),
8347                    timestamp_writes: shadow_ts,
8348                    occlusion_query_set: None,
8349                });
8350                if !topology_batches.is_empty() {
8351                    spass.set_pipeline(&self.terrain_shadow_pipeline);
8352                    spass.set_bind_group(0, &self.terrain_bind_group, &[]);
8353                    for (idx_buf, idx_count, range) in &topology_batches {
8354                        spass.set_index_buffer(idx_buf.slice(..), wgpu::IndexFormat::Uint32);
8355                        spass.draw_indexed(0..*idx_count, 0, range.clone());
8356                    }
8357                }
8358                if !geo_opaque_batches.is_empty() {
8359                    spass.set_pipeline(&self.geo_shadow_pipeline);
8360                    spass.set_bind_group(0, &self.geo_object_bind_group, &[]);
8361                    for (mesh_id, _, range) in &geo_opaque_batches {
8362                        let Some(gpu_mesh) = self.geo_meshes.get(mesh_id) else {
8363                            continue;
8364                        };
8365                        spass.set_vertex_buffer(0, gpu_mesh.vbuf.slice(..));
8366                        spass.set_index_buffer(gpu_mesh.ibuf.slice(..), wgpu::IndexFormat::Uint32);
8367                        spass.draw_indexed(0..gpu_mesh.index_count, 0, range.clone());
8368                    }
8369                }
8370            }
8371        }
8372
8373        {
8374            let main_ts = ts_slot.and_then(|slot_idx| {
8375                self.timestamp_profiler.as_ref().map(|p| {
8376                    wgpu::RenderPassTimestampWrites {
8377                        query_set: &p.slots[slot_idx].query_set,
8378                        beginning_of_pass_write_index: Some(2),
8379                        end_of_pass_write_index: Some(3),
8380                    }
8381                })
8382            });
8383            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
8384                label: Some("strata_3d_main_pass"),
8385                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
8386                    view: target_view,
8387                    resolve_target: None,
8388                    ops: wgpu::Operations {
8389                        load: clear_op,
8390                        store: wgpu::StoreOp::Store,
8391                    },
8392                })],
8393                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
8394                    view: &depth_view,
8395                    depth_ops: Some(wgpu::Operations {
8396                        load: wgpu::LoadOp::Clear(1.0),
8397                        store: wgpu::StoreOp::Discard,
8398                    }),
8399                    stencil_ops: None,
8400                }),
8401                timestamp_writes: main_ts,
8402                occlusion_query_set: None,
8403            });
8404
8405            if let Some([vx, vy, vw, vh]) = viewport {
8406                let x = vx.max(0.0).min((target_width.saturating_sub(1)) as f32);
8407                let y = vy.max(0.0).min((target_height.saturating_sub(1)) as f32);
8408                let max_w = (target_width as f32 - x).max(1.0);
8409                let max_h = (target_height as f32 - y).max(1.0);
8410                let w = vw.max(1.0).min(max_w);
8411                let h = vh.max(1.0).min(max_h);
8412                let xi = (x.floor() as u32).min(target_width.saturating_sub(1));
8413                let yi = (y.floor() as u32).min(target_height.saturating_sub(1));
8414                let wi = (w.round() as u32)
8415                    .max(1)
8416                    .min(target_width.saturating_sub(xi).max(1));
8417                let hi = (h.round() as u32)
8418                    .max(1)
8419                    .min(target_height.saturating_sub(yi).max(1));
8420                pass.set_viewport(x, y, w, h, 0.0, 1.0);
8421                pass.set_scissor_rect(xi, yi, wi, hi);
8422            }
8423
8424            let terrain_first = draw_count > 0
8425                && all_terrain_opaque
8426                && !matches!(cam.background, Background3D::Transparent);
8427
8428            if terrain_first && !topology_batches.is_empty() {
8429                pass.set_pipeline(&self.terrain_opaque_pipeline);
8430                pass.set_bind_group(0, &self.terrain_bind_group, &[]);
8431                pass.set_bind_group(1, &self.shadow_ocean_bind_group, &[]);
8432                for (idx_buf, idx_count, range) in &topology_batches {
8433                    pass.set_index_buffer(idx_buf.slice(..), wgpu::IndexFormat::Uint32);
8434                    pass.draw_indexed(0..*idx_count, 0, range.clone());
8435                }
8436            }
8437
8438            let need_scissored_solid_bg = (multi_viewport_mode || !clear_color_target)
8439                && matches!(cam.background, Background3D::Solid(_));
8440            if need_scissored_solid_bg
8441                || matches!(cam.background, Background3D::VerticalGradient { .. })
8442                || cam.stars_visible
8443                || cam.sun_visible
8444                || cam.moon_visible
8445                || cam.realistic_25d_sky > 0.001
8446            {
8447                let grad_opaque = match cam.background {
8448                    Background3D::VerticalGradient { top, bottom } => {
8449                        (multi_viewport_mode || !clear_color_target)
8450                            && top.a() >= 0.999
8451                            && bottom.a() >= 0.999
8452                    }
8453                    Background3D::Solid(c) => c.a() >= 0.999,
8454                    Background3D::Transparent => false,
8455                };
8456                let sky_opaque = grad_opaque
8457                    || cam.stars_visible
8458                    || cam.sun_visible
8459                    || cam.moon_visible
8460                    || cam.realistic_25d_sky > 0.001;
8461                pass.set_pipeline(if sky_opaque {
8462                    &self.sky_opaque_pipeline
8463                } else {
8464                    &self.sky_pipeline
8465                });
8466                pass.set_bind_group(0, &self.sky_bind_group, &[]);
8467                pass.draw(0..3, 0..1);
8468            }
8469
8470            if cam.stars_visible
8471                && cam.stars_intensity > 0.001
8472                && self.env_state.star_count > 0
8473                && (cam.local_25d_blend < 0.85 || cam.night_stars_25d > 0.001)
8474            {
8475                pass.set_pipeline(&self.star_pipeline);
8476                pass.set_bind_group(0, &self.star_bind_group, &[]);
8477                pass.draw(0..6, 0..self.env_state.star_count);
8478            }
8479
8480            if !terrain_first && !topology_batches.is_empty() {
8481                pass.set_pipeline(&self.terrain_pipeline);
8482                pass.set_bind_group(0, &self.terrain_bind_group, &[]);
8483                pass.set_bind_group(1, &self.shadow_ocean_bind_group, &[]);
8484                for (idx_buf, idx_count, range) in &topology_batches {
8485                    pass.set_index_buffer(idx_buf.slice(..), wgpu::IndexFormat::Uint32);
8486                    pass.draw_indexed(0..*idx_count, 0, range.clone());
8487                }
8488            }
8489
8490            if !geo_opaque_batches.is_empty() {
8491                pass.set_pipeline(&self.geo_object_pipeline);
8492                pass.set_bind_group(0, &self.geo_object_bind_group, &[]);
8493                pass.set_bind_group(1, &self.shadow_ocean_bind_group, &[]);
8494                for (mesh_id, tex_id_opt, range) in &geo_opaque_batches {
8495                    let Some(gpu_mesh) = self.geo_meshes.get(mesh_id) else {
8496                        continue;
8497                    };
8498                    let tex_bg = tex_id_opt
8499                        .and_then(|tid| self.geo_textures.get(&tid))
8500                        .map(|t| &t.bind_group)
8501                        .unwrap_or(&self.geo_default_tex_bg);
8502                    pass.set_bind_group(2, tex_bg, &[]);
8503                    pass.set_vertex_buffer(0, gpu_mesh.vbuf.slice(..));
8504                    pass.set_index_buffer(gpu_mesh.ibuf.slice(..), wgpu::IndexFormat::Uint32);
8505                    pass.draw_indexed(0..gpu_mesh.index_count, 0, range.clone());
8506                }
8507            }
8508
8509            if (cam.cloud_layer_opacity > 0.004 || cam.local_cloud_opacity > 0.004)
8510                && self.cloud_index_count > 0
8511            {
8512                let eye_r2 = cam.eye_ecef[0] * cam.eye_ecef[0]
8513                    + cam.eye_ecef[1] * cam.eye_ecef[1]
8514                    + cam.eye_ecef[2] * cam.eye_ecef[2];
8515                let cloud_pl = if eye_r2 > 6_396_000.0 * 6_396_000.0 {
8516                    &self.cloud_pipeline
8517                } else if eye_r2 < 6_390_000.0 * 6_390_000.0 {
8518                    &self.cloud_inside_pipeline
8519                } else {
8520                    &self.cloud_twosided_pipeline
8521                };
8522                pass.set_pipeline(cloud_pl);
8523                pass.set_bind_group(0, &self.cloud_bind_group, &[]);
8524                pass.set_vertex_buffer(0, self.cloud_vbuf.slice(..));
8525                pass.set_index_buffer(self.cloud_ibuf.slice(..), wgpu::IndexFormat::Uint32);
8526                pass.draw_indexed(0..self.cloud_index_count, 0, 0..1);
8527            }
8528
8529            if !dynamic_draws.is_empty() {
8530                pass.set_pipeline(&self.dynamic_pipeline);
8531                for (i, (id, _, _, _)) in dynamic_draws.iter().enumerate() {
8532                    let Some(gpu_mesh) = self.dynamic_meshes.get(id) else {
8533                        continue;
8534                    };
8535                    let offset = (i as u32) * self.dynamic_uniform_stride;
8536                    pass.set_bind_group(0, &self.dynamic_bind_group, &[offset]);
8537                    pass.set_vertex_buffer(0, gpu_mesh.vbuf.slice(..));
8538                    pass.set_index_buffer(gpu_mesh.ibuf.slice(..), wgpu::IndexFormat::Uint32);
8539                    pass.draw_indexed(0..gpu_mesh.index_count, 0, 0..1);
8540                }
8541            }
8542
8543            if !geo_transparent_batches.is_empty() {
8544                pass.set_pipeline(&self.geo_object_transparent_pipeline);
8545                pass.set_bind_group(0, &self.geo_object_bind_group, &[]);
8546                pass.set_bind_group(1, &self.shadow_ocean_bind_group, &[]);
8547                for (mesh_id, tex_id_opt, range) in &geo_transparent_batches {
8548                    let Some(gpu_mesh) = self.geo_meshes.get(mesh_id) else {
8549                        continue;
8550                    };
8551                    let tex_bg = tex_id_opt
8552                        .and_then(|tid| self.geo_textures.get(&tid))
8553                        .map(|t| &t.bind_group)
8554                        .unwrap_or(&self.geo_default_tex_bg);
8555                    pass.set_bind_group(2, tex_bg, &[]);
8556                    pass.set_vertex_buffer(0, gpu_mesh.vbuf.slice(..));
8557                    pass.set_index_buffer(gpu_mesh.ibuf.slice(..), wgpu::IndexFormat::Uint32);
8558                    pass.draw_indexed(0..gpu_mesh.index_count, 0, range.clone());
8559                }
8560            }
8561
8562            if !particle_draws.is_empty() {
8563                pass.set_pipeline(&self.particle_pipeline);
8564                for (i, (count, tex_id_opt)) in particle_draws.iter().enumerate() {
8565                    let offset = (i as u32) * self.particle_uniform_stride;
8566                    pass.set_bind_group(0, &self.particle_common_bind_group, &[offset]);
8567                    let tex_bg = tex_id_opt
8568                        .and_then(|tid| self.particle_textures.get(&tid))
8569                        .map(|c| &c.bind_group)
8570                        .unwrap_or(&self.particle_default_tex_bg);
8571                    pass.set_bind_group(1, tex_bg, &[]);
8572                    pass.draw(0..6, 0..*count);
8573                }
8574            }
8575
8576            if let Some(ov_bg) = overlay_bind_group {
8577                if viewport.is_some() {
8578                    let tw = target_width.max(1);
8579                    let th = target_height.max(1);
8580                    pass.set_viewport(0.0, 0.0, tw as f32, th as f32, 0.0, 1.0);
8581                    pass.set_scissor_rect(0, 0, tw, th);
8582                }
8583                pass.set_pipeline(&self.overlay_main_pass_pipeline);
8584                pass.set_bind_group(0, ov_bg, &[]);
8585                pass.draw(0..3, 0..1);
8586            }
8587        }
8588        let tp_sub = std::time::Instant::now();
8589        if let (Some(slot_idx), Some(ref mut profiler)) = (ts_slot, self.timestamp_profiler.as_mut())
8590        {
8591            profiler.slots[slot_idx].wrote_shadow = wrote_shadow_ts;
8592            profiler.slots[slot_idx].wrote_main = true;
8593            profiler.resolve_and_copy(slot_idx, &mut encoder);
8594        }
8595        self.queue.submit(Some(encoder.finish()));
8596        if let (Some(slot_idx), Some(ref mut profiler)) = (ts_slot, self.timestamp_profiler.as_mut())
8597        {
8598            profiler.begin_async_map(slot_idx);
8599        }
8600        if perf {
8601            let tot = t_start.elapsed().as_secs_f64() * 1000.0;
8602            if tot > 3.0 {
8603                eprintln!(
8604                    "[perf] render_scene_to_view tot={:.2}ms (env={:.2} slab={:.2} atlas={:.2} inst={:.2} dyn={:.2} rec={:.2} sub={:.2})",
8605                    tot,
8606                    t_env,
8607                    t_slab,
8608                    t_atlas,
8609                    t_inst,
8610                    t_dyn,
8611                    tp_sub.duration_since(tp_pass).as_secs_f64() * 1000.0,
8612                    tp_sub.elapsed().as_secs_f64() * 1000.0
8613                );
8614            }
8615        }
8616    }
8617
8618    fn record_overlay_pass(
8619        &self,
8620        encoder: &mut wgpu::CommandEncoder,
8621        target_view: &wgpu::TextureView,
8622        overlay_bind_group: &wgpu::BindGroup,
8623    ) {
8624        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
8625            label: Some("strata_2d_overlay_pass"),
8626            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
8627                view: target_view,
8628                resolve_target: None,
8629                ops: wgpu::Operations {
8630                    load: wgpu::LoadOp::Load,
8631                    store: wgpu::StoreOp::Store,
8632                },
8633            })],
8634            depth_stencil_attachment: None,
8635            timestamp_writes: None,
8636            occlusion_query_set: None,
8637        });
8638        pass.set_pipeline(&self.overlay_pipeline);
8639        pass.set_bind_group(0, overlay_bind_group, &[]);
8640        pass.draw(0..3, 0..1);
8641    }
8642
8643    /// Composites a GPU 2D UI HUD overlay bind group on top of `target_view` (preserving alpha).
8644    pub fn composite_overlay_to_view(
8645        &self,
8646        target_view: &wgpu::TextureView,
8647        overlay_bind_group: &wgpu::BindGroup,
8648    ) {
8649        let mut encoder = self
8650            .device
8651            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
8652                label: Some("strata_2d_overlay_encoder"),
8653            });
8654        self.record_overlay_pass(&mut encoder, target_view, overlay_bind_group);
8655        self.queue.submit(Some(encoder.finish()));
8656    }
8657
8658    /// Blits a cached offscreen 3D scene color attachment into `target_view` and composites
8659    /// an optional 2D UI overlay on top in a single lightweight fullscreen render pass.
8660    pub fn composite_cached_scene_and_overlay_to_view(
8661        &mut self,
8662        target_view: &wgpu::TextureView,
8663        cached_scene_bind_group: &wgpu::BindGroup,
8664        overlay_bind_group: Option<&wgpu::BindGroup>,
8665    ) {
8666        let ts_slot = self
8667            .timestamp_profiler
8668            .as_mut()
8669            .and_then(|p| p.acquire_idle_slot(&self.device));
8670        let mut encoder = self
8671            .device
8672            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
8673                label: Some("strata_cached_3d_composite_encoder"),
8674            });
8675        {
8676            let ov_ts = ts_slot.and_then(|slot_idx| {
8677                self.timestamp_profiler.as_ref().map(|p| {
8678                    wgpu::RenderPassTimestampWrites {
8679                        query_set: &p.slots[slot_idx].query_set,
8680                        beginning_of_pass_write_index: Some(4),
8681                        end_of_pass_write_index: Some(5),
8682                    }
8683                })
8684            });
8685            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
8686                label: Some("strata_cached_3d_composite_pass"),
8687                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
8688                    view: target_view,
8689                    resolve_target: None,
8690                    ops: wgpu::Operations {
8691                        load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
8692                        store: wgpu::StoreOp::Store,
8693                    },
8694                })],
8695                depth_stencil_attachment: None,
8696                timestamp_writes: ov_ts,
8697                occlusion_query_set: None,
8698            });
8699            pass.set_pipeline(&self.scene_blit_pipeline);
8700            pass.set_bind_group(0, cached_scene_bind_group, &[]);
8701            pass.draw(0..3, 0..1);
8702            if let Some(ov_bg) = overlay_bind_group {
8703                pass.set_pipeline(&self.overlay_pipeline);
8704                pass.set_bind_group(0, ov_bg, &[]);
8705                pass.draw(0..3, 0..1);
8706            }
8707        }
8708        if let (Some(slot_idx), Some(ref mut profiler)) = (ts_slot, self.timestamp_profiler.as_mut())
8709        {
8710            profiler.slots[slot_idx].wrote_overlay = true;
8711            profiler.resolve_and_copy(slot_idx, &mut encoder);
8712        }
8713        self.queue.submit(Some(encoder.finish()));
8714        if let (Some(slot_idx), Some(ref mut profiler)) = (ts_slot, self.timestamp_profiler.as_mut())
8715        {
8716            profiler.begin_async_map(slot_idx);
8717        }
8718    }
8719
8720    /// Renders `scene` into a persistent offscreen texture and performs GPU->CPU readback only
8721    /// when `readback` is `true` (pure GPU timing benchmarks pass `readback = false`).
8722    pub fn render_offscreen(
8723        &mut self,
8724        scene: &Scene3D,
8725        width: u32,
8726        height: u32,
8727        readback: bool,
8728        unlimited_upload_budget: bool,
8729    ) -> Result<Vec<u8>, String> {
8730        let w = width.max(1);
8731        let h = height.max(1);
8732        let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
8733        let unpadded = w * 4;
8734        let padded = unpadded.div_ceil(align) * align;
8735
8736        let recreate = self
8737            .offscreen
8738            .as_ref()
8739            .map(|o| o.width != w || o.height != h || o.format != self.color_format)
8740            .unwrap_or(true);
8741        if recreate {
8742            let color = self.device.create_texture(&wgpu::TextureDescriptor {
8743                label: Some("strata_3d_offscreen_color"),
8744                size: wgpu::Extent3d {
8745                    width: w,
8746                    height: h,
8747                    depth_or_array_layers: 1,
8748                },
8749                mip_level_count: 1,
8750                sample_count: 1,
8751                dimension: wgpu::TextureDimension::D2,
8752                format: self.color_format,
8753                usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
8754                view_formats: &[],
8755            });
8756            let color_view = color.create_view(&Default::default());
8757            let depth = self.device.create_texture(&wgpu::TextureDescriptor {
8758                label: Some("strata_3d_offscreen_depth"),
8759                size: wgpu::Extent3d {
8760                    width: w,
8761                    height: h,
8762                    depth_or_array_layers: 1,
8763                },
8764                mip_level_count: 1,
8765                sample_count: 1,
8766                dimension: wgpu::TextureDimension::D2,
8767                format: wgpu::TextureFormat::Depth32Float,
8768                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
8769                view_formats: &[],
8770            });
8771            let depth_view = depth.create_view(&Default::default());
8772            let rb = self.device.create_buffer(&wgpu::BufferDescriptor {
8773                label: Some("strata_3d_offscreen_readback"),
8774                size: (padded * h) as u64,
8775                usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
8776                mapped_at_creation: false,
8777            });
8778            self.offscreen = Some(OffscreenTarget {
8779                width: w,
8780                height: h,
8781                format: self.color_format,
8782                color,
8783                color_view,
8784                _depth: depth,
8785                depth_view,
8786                readback: rb,
8787                padded_bytes_per_row: padded,
8788            });
8789        }
8790
8791        let target_view = self.offscreen.as_ref().unwrap().color_view.clone();
8792        self.depth_target = Some((w, h, self.offscreen.as_ref().unwrap().depth_view.clone()));
8793        self.render_scene_to_view(scene, &target_view, w, h, None, unlimited_upload_budget);
8794
8795        if !readback {
8796            self.device.poll(wgpu::Maintain::Wait);
8797            return Ok(Vec::new());
8798        }
8799
8800        let off = self.offscreen.as_ref().unwrap();
8801        let mut enc = self
8802            .device
8803            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
8804                label: Some("strata_3d_readback_encoder"),
8805            });
8806        enc.copy_texture_to_buffer(
8807            wgpu::TexelCopyTextureInfo {
8808                texture: &off.color,
8809                mip_level: 0,
8810                origin: wgpu::Origin3d::ZERO,
8811                aspect: wgpu::TextureAspect::All,
8812            },
8813            wgpu::TexelCopyBufferInfo {
8814                buffer: &off.readback,
8815                layout: wgpu::TexelCopyBufferLayout {
8816                    offset: 0,
8817                    bytes_per_row: Some(off.padded_bytes_per_row),
8818                    rows_per_image: Some(h),
8819                },
8820            },
8821            wgpu::Extent3d {
8822                width: w,
8823                height: h,
8824                depth_or_array_layers: 1,
8825            },
8826        );
8827        self.queue.submit(Some(enc.finish()));
8828
8829        let slice = off.readback.slice(..);
8830        let (tx, rx) = std::sync::mpsc::channel();
8831        slice.map_async(wgpu::MapMode::Read, move |res| {
8832            let _ = tx.send(res);
8833        });
8834        self.device.poll(wgpu::Maintain::Wait);
8835        rx.recv()
8836            .map_err(|e| format!("readback recv error: {e}"))?
8837            .map_err(|e| format!("readback map error: {e:?}"))?;
8838
8839        let data = slice.get_mapped_range();
8840        let mut out = vec![0u8; (w * h * 4) as usize];
8841        for row in 0..h as usize {
8842            let src_start = row * off.padded_bytes_per_row as usize;
8843            let dst_start = row * (w as usize * 4);
8844            out[dst_start..dst_start + w as usize * 4]
8845                .copy_from_slice(&data[src_start..src_start + w as usize * 4]);
8846        }
8847        drop(data);
8848        off.readback.unmap();
8849        Ok(out)
8850    }
8851}
8852
8853/// Converts a regular [`Scene3D`] (primitives/custom meshes) into a [`RetainedTerrainFrame`]
8854/// so standard 3D scenes also accelerate seamlessly through [`Wgpu3DRenderer`].
8855pub fn fallback_frame_from_scene3d(
8856    scene: &Scene3D,
8857    viewport_w: f32,
8858    viewport_h: f32,
8859) -> RetainedTerrainFrame {
8860    let camera = retained_camera_from_scene3d(scene, viewport_w, viewport_h);
8861    let mut dynamic_meshes = Vec::new();
8862    for (idx, mesh) in scene.meshes.iter().enumerate() {
8863        if let Some((verts, inds, color, unlit)) = mesh3d_to_rte(mesh) {
8864            dynamic_meshes.push(RetainedDynamicMesh {
8865                id: idx as u64 + 1,
8866                revision: 1,
8867                anchor_ecef: [
8868                    mesh.transform.position[0] as f64,
8869                    mesh.transform.position[1] as f64,
8870                    mesh.transform.position[2] as f64,
8871                ],
8872                vertices: Arc::new(verts),
8873                indices: Arc::new(inds),
8874                color,
8875                unlit,
8876            });
8877        }
8878    }
8879    RetainedTerrainFrame {
8880        camera,
8881        geometry_revision: 1,
8882        meshes: Vec::new(),
8883        instances: Vec::new(),
8884        textures: Vec::new(),
8885        dynamic_meshes,
8886        ..Default::default()
8887    }
8888}
8889
8890fn retained_camera_from_scene3d(
8891    scene: &Scene3D,
8892    width: f32,
8893    height: f32,
8894) -> RetainedCameraUniforms {
8895    let aspect = (width.max(1.0) / height.max(1.0)).max(0.01);
8896    let (eye, target, proj) = match scene.camera {
8897        Camera3D::Perspective {
8898            fov_horizontal_deg,
8899            near,
8900            far,
8901            position,
8902            target,
8903        } => {
8904            let hfov_rad = fov_horizontal_deg.to_radians().max(0.05);
8905            let half_w = (hfov_rad * 0.5).tan();
8906            let vfov_rad = 2.0 * (half_w / aspect).atan();
8907            (
8908                position,
8909                target,
8910                perspective_rh_zo(vfov_rad, aspect, near.max(0.01), far.max(near + 1.0)),
8911            )
8912        }
8913        Camera3D::Orthographic {
8914            left,
8915            right,
8916            top,
8917            bottom,
8918            near,
8919            far,
8920            position,
8921            target,
8922        } => (
8923            position,
8924            target,
8925            ortho_rh_zo(left, right, bottom, top, near, far),
8926        ),
8927    };
8928
8929    let up_hint = scene.camera_up().unwrap_or([0.0, 1.0, 0.0]);
8930    let view_rot = look_rot_rh(eye, target, up_hint);
8931    let view_proj_rte = mul_mat4(proj, view_rot);
8932
8933    let mut sun_dir = [0.577_350_26f32, 0.577_350_26, 0.577_350_26];
8934    let mut sun_color = [1.0f32, 0.98, 0.95];
8935    let mut ambient_color = [0.22f32, 0.24, 0.28];
8936    for light in &scene.lights {
8937        match light {
8938            Light3D::Ambient { color, intensity } => {
8939                ambient_color = [
8940                    color.r() * intensity,
8941                    color.g() * intensity,
8942                    color.b() * intensity,
8943                ];
8944            }
8945            Light3D::Directional {
8946                position,
8947                color,
8948                intensity,
8949                ..
8950            } => {
8951                let len = (position[0] * position[0]
8952                    + position[1] * position[1]
8953                    + position[2] * position[2])
8954                    .sqrt()
8955                    .max(1e-6);
8956                sun_dir = [position[0] / len, position[1] / len, position[2] / len];
8957                sun_color = [
8958                    color.r() * intensity,
8959                    color.g() * intensity,
8960                    color.b() * intensity,
8961                ];
8962            }
8963            Light3D::Point { .. } => {}
8964        }
8965    }
8966
8967    RetainedCameraUniforms {
8968        proj,
8969        view_rot,
8970        view_proj_rte,
8971        eye_ecef: [eye[0] as f64, eye[1] as f64, eye[2] as f64],
8972        sun_dir,
8973        sun_color,
8974        ambient_color,
8975        background: scene.background(),
8976        near: 0.1,
8977        far: 100_000_000.0,
8978        ..Default::default()
8979    }
8980}
8981
8982fn perspective_rh_zo(vfov_rad: f32, aspect: f32, near: f32, far: f32) -> [[f32; 4]; 4] {
8983    let f = 1.0 / (vfov_rad * 0.5).tan();
8984    let nf = 1.0 / (near - far);
8985    [
8986        [f / aspect, 0.0, 0.0, 0.0],
8987        [0.0, f, 0.0, 0.0],
8988        [0.0, 0.0, far * nf, -1.0],
8989        [0.0, 0.0, (far * near) * nf, 0.0],
8990    ]
8991}
8992
8993fn ortho_rh_zo(l: f32, r: f32, b: f32, t: f32, n: f32, f: f32) -> [[f32; 4]; 4] {
8994    let rml = (r - l).max(1e-5);
8995    let tmb = (t - b).max(1e-5);
8996    let fmn = (f - n).max(1e-5);
8997    [
8998        [2.0 / rml, 0.0, 0.0, 0.0],
8999        [0.0, 2.0 / tmb, 0.0, 0.0],
9000        [0.0, 0.0, -1.0 / fmn, 0.0],
9001        [-(r + l) / rml, -(t + b) / tmb, -n / fmn, 1.0],
9002    ]
9003}
9004
9005fn look_rot_rh(eye: [f32; 3], target: [f32; 3], up_hint: [f64; 3]) -> [[f32; 4]; 4] {
9006    let fx = (target[0] - eye[0]) as f64;
9007    let fy = (target[1] - eye[1]) as f64;
9008    let fz = (target[2] - eye[2]) as f64;
9009    let flen = (fx * fx + fy * fy + fz * fz).sqrt().max(1e-9);
9010    let f = [fx / flen, fy / flen, fz / flen];
9011    let mut s = [
9012        f[1] * up_hint[2] - f[2] * up_hint[1],
9013        f[2] * up_hint[0] - f[0] * up_hint[2],
9014        f[0] * up_hint[1] - f[1] * up_hint[0],
9015    ];
9016    let mut slen = (s[0] * s[0] + s[1] * s[1] + s[2] * s[2]).sqrt();
9017    if slen < 1e-6 {
9018        let alt = if f[1].abs() < 0.9 {
9019            [0.0, 1.0, 0.0]
9020        } else {
9021            [1.0, 0.0, 0.0]
9022        };
9023        s = [
9024            f[1] * alt[2] - f[2] * alt[1],
9025            f[2] * alt[0] - f[0] * alt[2],
9026            f[0] * alt[1] - f[1] * alt[0],
9027        ];
9028        slen = (s[0] * s[0] + s[1] * s[1] + s[2] * s[2]).sqrt().max(1e-9);
9029    }
9030    let s = [s[0] / slen, s[1] / slen, s[2] / slen];
9031    let u = [
9032        s[1] * f[2] - s[2] * f[1],
9033        s[2] * f[0] - s[0] * f[2],
9034        s[0] * f[1] - s[1] * f[0],
9035    ];
9036    [
9037        [s[0] as f32, u[0] as f32, -f[0] as f32, 0.0],
9038        [s[1] as f32, u[1] as f32, -f[1] as f32, 0.0],
9039        [s[2] as f32, u[2] as f32, -f[2] as f32, 0.0],
9040        [0.0, 0.0, 0.0, 1.0],
9041    ]
9042}
9043
9044fn mul_mat4(a: [[f32; 4]; 4], b: [[f32; 4]; 4]) -> [[f32; 4]; 4] {
9045    let mut out = [[0.0f32; 4]; 4];
9046    for c in 0..4 {
9047        for r in 0..4 {
9048            out[c][r] =
9049                a[0][r] * b[c][0] + a[1][r] * b[c][1] + a[2][r] * b[c][2] + a[3][r] * b[c][3];
9050        }
9051    }
9052    out
9053}
9054
9055fn mesh3d_to_rte(mesh: &Mesh3D) -> Option<(Vec<RteTileVertex>, Vec<u32>, [f32; 4], bool)> {
9056    let (color, unlit) = match &mesh.material {
9057        Material3D::Standard { color, .. } | Material3D::Physical { color, .. } => {
9058            ([color.r(), color.g(), color.b(), color.a()], false)
9059        }
9060        Material3D::Basic { color } => ([color.r(), color.g(), color.b(), color.a()], true),
9061        Material3D::Textured(tm) => (
9062            [
9063                tm.tint.r(),
9064                tm.tint.g(),
9065                tm.tint.b(),
9066                tm.tint.a() * tm.opacity,
9067            ],
9068            !tm.lit,
9069        ),
9070        Material3D::TexturedBatch(tb) => {
9071            let tint = tb
9072                .draws
9073                .first()
9074                .map(|d| d.material.tint)
9075                .unwrap_or(strata_style::Color::WHITE);
9076            ([tint.r(), tint.g(), tint.b(), tint.a()], false)
9077        }
9078        Material3D::Shader { .. } => ([0.8, 0.8, 0.8, 1.0], false),
9079    };
9080
9081    let scale = mesh.transform.scale;
9082    let map_pos = |x: f32, y: f32, z: f32| [x * scale[0], y * scale[1], z * scale[2]];
9083
9084    match &mesh.geometry {
9085        Geometry3D::Custom { vertices, indices } => {
9086            let mut out_v = Vec::with_capacity(vertices.len() / 6);
9087            for chunk in vertices.chunks_exact(6) {
9088                out_v.push(RteTileVertex::new(
9089                    map_pos(chunk[0], chunk[1], chunk[2]),
9090                    [chunk[3], chunk[4], chunk[5]],
9091                    [0.0, 0.0],
9092                ));
9093            }
9094            Some((out_v, indices.clone(), color, unlit))
9095        }
9096        Geometry3D::CustomTextured { vertices, indices } => {
9097            let mut out_v = Vec::with_capacity(vertices.len() / 8);
9098            for chunk in vertices.chunks_exact(8) {
9099                out_v.push(RteTileVertex::new(
9100                    map_pos(chunk[0], chunk[1], chunk[2]),
9101                    [chunk[3], chunk[4], chunk[5]],
9102                    [chunk[6], chunk[7]],
9103                ));
9104            }
9105            Some((out_v, indices.clone(), color, unlit))
9106        }
9107        Geometry3D::Box {
9108            width,
9109            height,
9110            depth,
9111        } => {
9112            let hw = width * 0.5;
9113            let hh = height * 0.5;
9114            let hd = depth * 0.5;
9115            let corners = [
9116                [-hw, -hh, -hd],
9117                [hw, -hh, -hd],
9118                [hw, hh, -hd],
9119                [-hw, hh, -hd],
9120                [-hw, -hh, hd],
9121                [hw, -hh, hd],
9122                [hw, hh, hd],
9123                [-hw, hh, hd],
9124            ];
9125            let faces: [([usize; 4], [f32; 3]); 6] = [
9126                ([4, 5, 6, 7], [0.0, 0.0, 1.0]),
9127                ([1, 0, 3, 2], [0.0, 0.0, -1.0]),
9128                ([5, 1, 2, 6], [1.0, 0.0, 0.0]),
9129                ([0, 4, 7, 3], [-1.0, 0.0, 0.0]),
9130                ([7, 6, 2, 3], [0.0, 1.0, 0.0]),
9131                ([0, 1, 5, 4], [0.0, -1.0, 0.0]),
9132            ];
9133            let mut verts = Vec::with_capacity(24);
9134            let mut inds = Vec::with_capacity(36);
9135            for (f_idx, (c, n)) in faces.into_iter().enumerate() {
9136                let b = (f_idx * 4) as u32;
9137                verts.push(RteTileVertex::new(
9138                    map_pos(corners[c[0]][0], corners[c[0]][1], corners[c[0]][2]),
9139                    n,
9140                    [0.0, 0.0],
9141                ));
9142                verts.push(RteTileVertex::new(
9143                    map_pos(corners[c[1]][0], corners[c[1]][1], corners[c[1]][2]),
9144                    n,
9145                    [1.0, 0.0],
9146                ));
9147                verts.push(RteTileVertex::new(
9148                    map_pos(corners[c[2]][0], corners[c[2]][1], corners[c[2]][2]),
9149                    n,
9150                    [1.0, 1.0],
9151                ));
9152                verts.push(RteTileVertex::new(
9153                    map_pos(corners[c[3]][0], corners[c[3]][1], corners[c[3]][2]),
9154                    n,
9155                    [0.0, 1.0],
9156                ));
9157                inds.extend_from_slice(&[b, b + 1, b + 2, b, b + 2, b + 3]);
9158            }
9159            Some((verts, inds, color, unlit))
9160        }
9161        Geometry3D::Plane { width, height } => {
9162            let hw = width * 0.5;
9163            let hh = height * 0.5;
9164            let verts = vec![
9165                RteTileVertex::new(map_pos(-hw, 0.0, -hh), [0.0, 1.0, 0.0], [0.0, 0.0]),
9166                RteTileVertex::new(map_pos(hw, 0.0, -hh), [0.0, 1.0, 0.0], [1.0, 0.0]),
9167                RteTileVertex::new(map_pos(hw, 0.0, hh), [0.0, 1.0, 0.0], [1.0, 1.0]),
9168                RteTileVertex::new(map_pos(-hw, 0.0, hh), [0.0, 1.0, 0.0], [0.0, 1.0]),
9169            ];
9170            Some((verts, vec![0, 1, 2, 0, 2, 3], color, unlit))
9171        }
9172        Geometry3D::Sphere {
9173            radius,
9174            width_segments,
9175            height_segments,
9176        } => {
9177            let ws = (*width_segments).max(6);
9178            let hs = (*height_segments).max(4);
9179            let mut verts = Vec::new();
9180            let mut inds = Vec::new();
9181            for iy in 0..=hs {
9182                let v = iy as f32 / hs as f32;
9183                let phi = v * std::f32::consts::PI;
9184                for ix in 0..=ws {
9185                    let u = ix as f32 / ws as f32;
9186                    let theta = u * std::f32::consts::TAU;
9187                    let nx = -phi.sin() * theta.cos();
9188                    let ny = phi.cos();
9189                    let nz = phi.sin() * theta.sin();
9190                    verts.push(RteTileVertex::new(
9191                        map_pos(nx * radius, ny * radius, nz * radius),
9192                        [nx, ny, nz],
9193                        [u, v],
9194                    ));
9195                }
9196            }
9197            for iy in 0..hs {
9198                for ix in 0..ws {
9199                    let a = iy * (ws + 1) + ix;
9200                    let b = a + 1;
9201                    let c = (iy + 1) * (ws + 1) + ix;
9202                    let d = c + 1;
9203                    inds.extend_from_slice(&[a, c, d, a, d, b]);
9204                }
9205            }
9206            Some((verts, inds, color, unlit))
9207        }
9208        Geometry3D::Cylinder {
9209            radius_top,
9210            radius_bottom,
9211            height,
9212            radial_segments,
9213        } => {
9214            let segs = (*radial_segments).max(6);
9215            let hh = height * 0.5;
9216            let mut verts = Vec::new();
9217            let mut inds = Vec::new();
9218            for i in 0..=segs {
9219                let u = i as f32 / segs as f32;
9220                let a = u * std::f32::consts::TAU;
9221                let (sa, ca) = a.sin_cos();
9222                verts.push(RteTileVertex::new(
9223                    map_pos(ca * radius_top, hh, sa * radius_top),
9224                    [ca, 0.0, sa],
9225                    [u, 0.0],
9226                ));
9227                verts.push(RteTileVertex::new(
9228                    map_pos(ca * radius_bottom, -hh, sa * radius_bottom),
9229                    [ca, 0.0, sa],
9230                    [u, 1.0],
9231                ));
9232            }
9233            for i in 0..segs {
9234                let t0 = i * 2;
9235                let b0 = t0 + 1;
9236                let t1 = t0 + 2;
9237                let b1 = t0 + 3;
9238                inds.extend_from_slice(&[t0, b0, b1, t0, b1, t1]);
9239            }
9240            Some((verts, inds, color, unlit))
9241        }
9242    }
9243}
9244
9245// Keep unused collection imports suppressed cleanly if any.
9246#[allow(dead_code)]
9247fn _assert_collections_used(_: BTreeMap<u64, u64>, _: HashSet<u64>) {}