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