Skip to main content

strata_render/
scene3d.rs

1//! Unified 3D Engine: High-level Three.js ergonomics paired seamlessly with low-level Vulkan/OpenGL hardware pipelines.
2
3#![allow(unused_variables)]
4
5use crate::overlay3d::Overlay3D;
6use std::collections::BTreeMap;
7use strata_style::Color;
8
9pub use crate::texture3d::{
10    SamplerDesc, TextureData, TextureDesc, TextureId, TextureStore, UvTransform,
11};
12
13/// 3D Spatial Transformation
14#[derive(Debug, Clone, PartialEq)]
15pub struct Transform3D {
16    pub position: [f32; 3],
17    pub rotation: [f32; 3],
18    pub scale: [f32; 3],
19}
20
21impl Default for Transform3D {
22    fn default() -> Self {
23        Self {
24            position: [0.0, 0.0, 0.0],
25            rotation: [0.0, 0.0, 0.0],
26            scale: [1.0, 1.0, 1.0],
27        }
28    }
29}
30
31impl Transform3D {
32    pub const fn from_position(position: [f32; 3]) -> Self {
33        Self {
34            position,
35            rotation: [0.0, 0.0, 0.0],
36            scale: [1.0, 1.0, 1.0],
37        }
38    }
39}
40
41/// 3D Camera Abstractions
42#[derive(Debug, Clone, PartialEq)]
43pub enum Camera3D {
44    Perspective {
45        /// Horizontal field of view in degrees. The projection matrix derives
46        /// the vertical field of view from the viewport's aspect ratio.
47        fov_horizontal_deg: f32,
48        near: f32,
49        far: f32,
50        position: [f32; 3],
51        target: [f32; 3],
52    },
53    Orthographic {
54        left: f32,
55        right: f32,
56        top: f32,
57        bottom: f32,
58        near: f32,
59        far: f32,
60        position: [f32; 3],
61        target: [f32; 3],
62    },
63}
64
65impl Default for Camera3D {
66    fn default() -> Self {
67        Self::Perspective {
68            fov_horizontal_deg: 60.0,
69            near: 0.1,
70            far: 1000.0,
71            position: [0.0, 2.0, 5.0],
72            target: [0.0, 0.0, 0.0],
73        }
74    }
75}
76
77/// 3D Lighting
78#[derive(Debug, Clone, PartialEq)]
79pub enum Light3D {
80    Ambient {
81        color: Color,
82        intensity: f32,
83    },
84    Directional {
85        position: [f32; 3],
86        color: Color,
87        intensity: f32,
88        cast_shadow: bool,
89    },
90    Point {
91        position: [f32; 3],
92        color: Color,
93        intensity: f32,
94        distance: f32,
95    },
96}
97
98/// 3D Geometry: Supports both parametric Three.js-style primitives and low-level custom vertex buffers.
99#[derive(Debug, Clone, PartialEq)]
100pub enum Geometry3D {
101    Box {
102        width: f32,
103        height: f32,
104        depth: f32,
105    },
106    Sphere {
107        radius: f32,
108        width_segments: u32,
109        height_segments: u32,
110    },
111    Plane {
112        width: f32,
113        height: f32,
114    },
115    Cylinder {
116        radius_top: f32,
117        radius_bottom: f32,
118        height: f32,
119        radial_segments: u32,
120    },
121    Custom {
122        vertices: Vec<f32>,
123        indices: Vec<u32>,
124    },
125    /// Custom vertex buffer with explicit texture coordinates.
126    ///
127    /// `vertices` is an eight-float stride: `x, y, z, nx, ny, nz, u, v`. Use this
128    /// for tile quads, relief walls, and building prisms whose UVs are authored
129    /// per corner rather than derived from the primitive generator.
130    CustomTextured {
131        vertices: Vec<f32>,
132        indices: Vec<u32>,
133    },
134}
135
136/// Textured surface material.
137#[derive(Debug, Clone, PartialEq)]
138pub struct TexturedMaterial3D {
139    /// Texture sampled per fragment.
140    pub texture: TextureId,
141    /// Multiplied with the sampled RGBA before lighting.
142    pub tint: Color,
143    /// Sub-rect of the texture addressed by the mesh UVs.
144    pub uv_transform: UvTransform,
145    /// Whether the surface receives scene lighting. Tiles are usually unlit
146    /// because the imagery already carries shading.
147    pub lit: bool,
148    /// How much of the sampled alpha to honour, 0..=1.
149    pub opacity: f32,
150}
151
152/// One index range of a batched textured mesh, with its own material.
153#[derive(Debug, Clone, PartialEq)]
154pub struct TexturedDraw3D {
155    pub material: TexturedMaterial3D,
156    /// First index in the shared index buffer.
157    pub index_start: u32,
158    /// Number of indices, a multiple of three.
159    pub index_count: u32,
160}
161
162impl TexturedDraw3D {
163    pub fn new(material: TexturedMaterial3D, index_start: u32, index_count: u32) -> Self {
164        Self {
165            material,
166            index_start,
167            index_count,
168        }
169    }
170}
171
172/// A textured mesh with several texture draws sharing one vertex and index
173/// buffer.
174///
175/// Terrain patches each need their own image, but setting up one mesh per patch
176/// repeats the vertex transform for every patch. A batch transforms the shared
177/// buffer once and switches textures per index range.
178#[derive(Debug, Clone, PartialEq, Default)]
179pub struct TexturedBatchMaterial3D {
180    pub draws: Vec<TexturedDraw3D>,
181}
182
183impl TexturedBatchMaterial3D {
184    pub fn new() -> Self {
185        Self::default()
186    }
187
188    pub fn push(&mut self, draw: TexturedDraw3D) -> &mut Self {
189        self.draws.push(draw);
190        self
191    }
192
193    pub fn is_empty(&self) -> bool {
194        self.draws.is_empty()
195    }
196}
197
198impl TexturedMaterial3D {
199    pub fn new(texture: TextureId) -> Self {
200        Self {
201            texture,
202            tint: Color::rgba(255, 255, 255, 255),
203            uv_transform: UvTransform::IDENTITY,
204            lit: false,
205            opacity: 1.0,
206        }
207    }
208
209    pub fn with_uv_transform(mut self, transform: UvTransform) -> Self {
210        self.uv_transform = transform;
211        self
212    }
213
214    pub fn with_tint(mut self, tint: Color) -> Self {
215        self.tint = tint;
216        self
217    }
218}
219
220/// Low-Level Hardware Shader Source
221#[derive(Debug, Clone, PartialEq)]
222pub enum ShaderSource {
223    SpirV(Vec<u32>),
224    Glsl(String),
225    Wgsl(String),
226    Msl(String),
227}
228
229/// 3D Material: Unifies high-level PBR workflows with low-level custom hardware shaders.
230#[derive(Debug, Clone, PartialEq)]
231pub enum Material3D {
232    /// High-Level Physically Based Rendering (PBR) Metallic-Roughness workflow
233    Standard {
234        color: Color,
235        roughness: f32,
236        metalness: f32,
237        emissive: Option<Color>,
238    },
239    /// High-Level PBR with Clearcoat extensions
240    Physical {
241        color: Color,
242        roughness: f32,
243        metalness: f32,
244        clearcoat: f32,
245        transmission: f32,
246    },
247    /// High-Level Unlit flat material
248    Basic { color: Color },
249    /// Low-Level Custom Hardware Shader Material
250    Shader {
251        vertex_shader: Option<ShaderSource>,
252        fragment_shader: Option<ShaderSource>,
253        glsl_fragment: Option<String>,
254        uniforms: BTreeMap<String, f32>,
255    },
256    /// Textured surface sampled from a [`TextureId`].
257    Textured(TexturedMaterial3D),
258    /// Several textured index ranges sharing one vertex buffer.
259    TexturedBatch(TexturedBatchMaterial3D),
260}
261
262impl Default for Material3D {
263    fn default() -> Self {
264        Self::Standard {
265            color: Color::rgba(255, 255, 255, 255),
266            roughness: 0.5,
267            metalness: 0.0,
268            emissive: None,
269        }
270    }
271}
272
273/// A 3D Mesh in the Scene Graph: Seamlessly pairs high-level or low-level geometry with materials.
274#[derive(Debug, Clone, PartialEq)]
275pub struct Mesh3D {
276    pub geometry: Geometry3D,
277    pub material: Material3D,
278    pub transform: Transform3D,
279}
280
281impl Mesh3D {
282    pub fn new(geometry: Geometry3D, material: Material3D) -> Self {
283        Self {
284            geometry,
285            material,
286            transform: Transform3D::default(),
287        }
288    }
289
290    pub fn with_transform(mut self, transform: Transform3D) -> Self {
291        self.transform = transform;
292        self
293    }
294}
295
296/// What the rasterizer fills before any geometry is drawn.
297#[derive(Debug, Clone, Copy, PartialEq, Default)]
298pub enum Background3D {
299    /// Leave the existing framebuffer contents untouched.
300    #[default]
301    Transparent,
302    /// A single colour.
303    Solid(Color),
304    /// A vertical gradient from `top` to `bottom` over the viewport.
305    VerticalGradient { top: Color, bottom: Color },
306}
307
308impl Background3D {
309    /// Returns the colour at a normalized vertical position `t` (0 = top).
310    pub fn color_at(self, t: f32) -> Option<Color> {
311        let t = t.clamp(0.0, 1.0);
312        match self {
313            Self::Transparent => None,
314            Self::Solid(color) => Some(color),
315            Self::VerticalGradient { top, bottom } => {
316                let mix = |a: f32, b: f32| -> u8 {
317                    ((a * (1.0 - t) + b * t) * 255.0).round().clamp(0.0, 255.0) as u8
318                };
319                Some(Color::rgba(
320                    mix(top.r(), bottom.r()),
321                    mix(top.g(), bottom.g()),
322                    mix(top.b(), bottom.b()),
323                    mix(top.a(), bottom.a()),
324                ))
325            }
326        }
327    }
328}
329
330/// An emissive celestial body drawn as a billboard: the sun, the moon, or a
331/// sensor anomaly marker.
332#[derive(Debug, Clone, Copy, PartialEq)]
333pub struct CelestialBody3D {
334    /// Scene-space position of the body centre.
335    pub position: [f64; 3],
336    /// Apparent radius in scene units.
337    pub radius: f64,
338    pub color: Color,
339    /// Soft edge width in pixels; 0 draws a hard disc.
340    pub glow: f32,
341    /// Whether the body participates in depth testing. The sun and stars
342    /// usually do not.
343    pub depth_test: bool,
344}
345
346/// A translucent spherical shell drawn over the surface: clouds, a night arc,
347/// or a coverage wash.
348#[derive(Debug, Clone, Copy, PartialEq)]
349pub struct CloudShell3D {
350    /// Scene-space centre of the shell.
351    pub centre: [f64; 3],
352    /// Radius of the shell in scene units.
353    pub radius: f64,
354    pub color: Color,
355    /// Fraction of the shell that is cloud, 0..=1.
356    pub coverage: f32,
357    /// Shell opacity at full coverage, 0..=1.
358    pub opacity: f32,
359}
360
361impl CloudShell3D {
362    /// Opacity after applying the coverage ramp.
363    ///
364    /// The reference ramps cloud opacity from clear to full as density rises;
365    /// clamping here keeps every consumer on the same curve.
366    pub fn effective_opacity(&self) -> f32 {
367        (self.coverage.clamp(0.0, 1.0) * self.opacity.clamp(0.0, 1.0)).clamp(0.0, 1.0)
368    }
369}
370
371/// Compact, backend-agnostic identifier for a terrain tile in a quadtree or flat-patch pyramid.
372#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
373pub struct TileKeyId {
374    pub level: u8,
375    pub col: u32,
376    pub row: u32,
377    pub face: u8,
378}
379
380impl TileKeyId {
381    #[inline]
382    pub const fn new(level: u8, col: u32, row: u32, face: u8) -> Self {
383        Self {
384            level,
385            col,
386            row,
387            face,
388        }
389    }
390
391    #[inline]
392    pub const fn quadtree(level: u8, col: u32, row: u32) -> Self {
393        Self::new(level, col, row, 0)
394    }
395}
396
397/// Tile-local RTC terrain vertex packed into two `vec4<f32>`s for GPU vertex pulling.
398///
399/// `pos_u = [local_x, local_y, local_z, u]` relative to the tile's `center_ecef`,
400/// `norm_v = [nx, ny, nz, v]`. Using two 16-byte vectors eliminates WGSL `vec3` alignment padding.
401#[repr(C)]
402#[derive(Debug, Clone, Copy, PartialEq)]
403#[cfg_attr(feature = "wgpu-backend", derive(bytemuck::Pod, bytemuck::Zeroable))]
404pub struct RteTileVertex {
405    pub pos_u: [f32; 4],
406    pub norm_v: [f32; 4],
407}
408
409impl RteTileVertex {
410    #[inline]
411    pub const fn new(pos: [f32; 3], normal: [f32; 3], uv: [f32; 2]) -> Self {
412        Self {
413            pos_u: [pos[0], pos[1], pos[2], uv[0]],
414            norm_v: [normal[0], normal[1], normal[2], uv[1]],
415        }
416    }
417
418    #[inline]
419    pub const fn position(self) -> [f32; 3] {
420        [self.pos_u[0], self.pos_u[1], self.pos_u[2]]
421    }
422
423    #[inline]
424    pub const fn normal(self) -> [f32; 3] {
425        [self.norm_v[0], self.norm_v[1], self.norm_v[2]]
426    }
427
428    #[inline]
429    pub const fn uv(self) -> [f32; 2] {
430        [self.pos_u[3], self.norm_v[3]]
431    }
432}
433
434/// Persistent GPU-ready tile geometry computed once per `(TileKeyId, revision)`.
435#[derive(Debug, Clone, PartialEq)]
436pub struct RetainedTileMesh {
437    pub key: TileKeyId,
438    pub revision: u64,
439    pub center_ecef: [f64; 3],
440    pub grid_res: u32,
441    pub has_skirts: bool,
442    pub vertices: std::sync::Arc<Vec<RteTileVertex>>,
443    pub bounding_radius: f32,
444}
445
446/// Persistent GPU-ready tile imagery payload computed once per `(id, revision)`.
447#[derive(Debug, Clone, PartialEq, Eq)]
448pub struct RetainedTileTexture {
449    pub id: u64,
450    pub revision: u64,
451    pub width: u32,
452    pub height: u32,
453    pub rgba8: std::sync::Arc<Vec<u8>>,
454}
455
456/// Lightweight per-frame tile draw instance referencing cached geometry and imagery.
457#[derive(Debug, Clone, PartialEq)]
458pub struct RetainedTileInstance {
459    pub key: TileKeyId,
460    pub mesh_revision: u64,
461    pub center_ecef: [f64; 3],
462    pub texture_id: Option<u64>,
463    pub texture_revision: u64,
464    pub uv_rect: [f32; 4],
465    pub tint: [f32; 4],
466    pub unlit: bool,
467    pub night_texture_id: Option<u64>,
468    pub night_texture_revision: u64,
469    pub night_uv_rect: [f32; 4],
470}
471
472impl Default for RetainedTileInstance {
473    fn default() -> Self {
474        Self {
475            key: TileKeyId::quadtree(0, 0, 0),
476            mesh_revision: 0,
477            center_ecef: [0.0; 3],
478            texture_id: None,
479            texture_revision: 0,
480            uv_rect: [0.0, 0.0, 1.0, 1.0],
481            tint: [1.0, 1.0, 1.0, 1.0],
482            unlit: false,
483            night_texture_id: None,
484            night_texture_revision: 0,
485            night_uv_rect: [0.0, 0.0, 1.0, 1.0],
486        }
487    }
488}
489
490/// Dynamic or non-grid RTC geometry (buildings, vector ribbons, trajectories) anchored in ECEF.
491#[derive(Debug, Clone, PartialEq)]
492pub struct RetainedDynamicMesh {
493    pub id: u64,
494    pub revision: u64,
495    pub anchor_ecef: [f64; 3],
496    pub vertices: std::sync::Arc<Vec<RteTileVertex>>,
497    pub indices: std::sync::Arc<Vec<u32>>,
498    pub color: [f32; 4],
499    pub unlit: bool,
500}
501
502/// Canonical local-space 3D mesh asset uploaded once to GPU VRAM and shared across any number of
503/// [`RetainedGeoInstance`]s.
504///
505/// Vertex coordinates are authored in local model metres (`+X` East, `+Y` North, `+Z` Up).
506#[derive(Debug, Clone, PartialEq)]
507pub struct RetainedMeshAsset {
508    pub id: u64,
509    pub revision: u64,
510    pub vertices: std::sync::Arc<Vec<RteTileVertex>>,
511    pub indices: std::sync::Arc<Vec<u32>>,
512    /// Optional per-vertex RGBA colors (`len == vertices.len()`); `None` defaults to white `[1,1,1,1]`.
513    pub vertex_colors: Option<std::sync::Arc<Vec<[f32; 4]>>>,
514    /// Optional default base-color albedo texture bound when an instance does not specify its own.
515    pub albedo_texture: Option<std::sync::Arc<RetainedTileTexture>>,
516}
517
518/// Hardware-instanced 3D object anchored in double-precision ECEF / morphed planetary space.
519///
520/// `model_cols` is a column-major 3x3 linear transform mapping local model coordinates (`+X`, `+Y`, `+Z`)
521/// to world relative metres (combining scale, local heading/pitch/roll, local ENU basis, and 2D/2.5D
522/// surface morphing).
523#[derive(Debug, Clone, PartialEq)]
524pub struct RetainedGeoInstance {
525    pub mesh_id: u64,
526    pub anchor_ecef: [f64; 3],
527    pub model_cols: [[f32; 3]; 3],
528    pub base_color: [f32; 4],
529    pub emissive_rgb: [f32; 3],
530    pub roughness: f32,
531    pub metalness: f32,
532    pub unlit: bool,
533    /// Optional white-core accent mix (`0.0` default; multiplied by vertex `uv.y` in shader).
534    pub accent_mix: f32,
535    /// Optional per-instance albedo RGBA8 texture overriding [`RetainedMeshAsset::albedo_texture`].
536    pub albedo_texture: Option<std::sync::Arc<RetainedTileTexture>>,
537}
538
539impl Default for RetainedGeoInstance {
540    fn default() -> Self {
541        Self {
542            mesh_id: 0,
543            anchor_ecef: [0.0; 3],
544            model_cols: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
545            base_color: [1.0, 1.0, 1.0, 1.0],
546            emissive_rgb: [0.0, 0.0, 0.0],
547            roughness: 0.45,
548            metalness: 0.1,
549            unlit: false,
550            accent_mix: 0.0,
551            albedo_texture: None,
552        }
553    }
554}
555
556/// 2D sprite rendering mode for a GPU-instanced [`RetainedParticleLayer`].
557#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
558pub enum RetainedParticleSprite {
559    /// Sample a custom 2D RGBA8 texture identified by `texture_id` inside
560    /// [`RetainedTerrainFrame::particle_textures`].
561    Textured(u64),
562    /// Pure mathematical 2D motion-tapered raindrop streak (zero texture fetches).
563    #[default]
564    ProceduralStreak,
565    /// Pure mathematical simplistic 6-fold geometric snowflake crystal (zero texture fetches).
566    ProceduralSnowflake,
567    /// Pure mathematical soft translucent sleet/graupel ice pellet (zero texture fetches).
568    ProceduralPellet,
569    /// Pure mathematical wide-area falling rain/snow virga curtain sheet for far-field depth illusion.
570    ProceduralCurtain,
571}
572
573/// Billboard alignment strategy for a GPU-instanced [`RetainedParticleLayer`].
574#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
575pub enum RetainedParticleBillboard {
576    /// Aligns the 2D quad's vertical axis with the particle's 3D apparent velocity vector
577    /// and horizontal axis perpendicular to both velocity and camera view ray.
578    #[default]
579    VelocityAligned,
580    /// Camera-facing 2D sprite aligned with camera right/up vectors with per-particle 2D spin.
581    CameraFacing,
582}
583
584/// GPU-instanced camera-local toroidal 2D billboard particle volume.
585///
586/// All `particle_count` particles are procedurally distributed, toroidally wrapped in
587/// world-locked East-North-Up (ENU) space around the camera eye (optionally shifted forward
588/// along the camera view cone via `forward_bias_world`), depth-tested against terrain and
589/// 3D objects, and billboarded entirely on the GPU in one draw call.
590#[derive(Debug, Clone, PartialEq)]
591pub struct RetainedParticleLayer {
592    pub id: u64,
593    pub particle_count: u32,
594    pub sprite: RetainedParticleSprite,
595    pub billboard: RetainedParticleBillboard,
596    /// Local orthonormal unit East vector in world / ECEF coordinates at the camera eye.
597    pub basis_east: [f32; 3],
598    /// Local orthonormal unit North vector in world / ECEF coordinates at the camera eye.
599    pub basis_north: [f32; 3],
600    /// Local orthonormal unit Up vector in world / ECEF coordinates at the camera eye.
601    pub basis_up: [f32; 3],
602    /// Optional world-space offset shifting the toroidal wrap box forward into the camera view cone.
603    pub forward_bias_world: [f32; 3],
604    /// Pre-wrapped `f64 -> f32` fractional toroidal offsets in `[0.0, 1.0)` encoding
605    /// `(wind_enu * time_s - camera_world_phase_enu) / volume_extent_enu`.
606    pub wrapped_phase: [f32; 3],
607    /// `[eye_alt_msl_m, ground_alt_msl_m, ceiling_alt_msl_m, ceiling_fade_band_m]`.
608    pub altitude_bounds: [f32; 4],
609    /// `[extent_xy_m, extent_z_m, box_edge_fade_frac, near_lens_fade_m]`.
610    pub volume_params: [f32; 4],
611    /// `[fall_speed_mps, wind_east_mps, wind_north_mps, wrapped_time_s]`.
612    pub motion_params: [f32; 4],
613    /// `[width_m, height_m, velocity_stretch, spin_rad_s]`.
614    pub size_params: [f32; 4],
615    /// `[flutter_amp_m, flutter_freq_hz, min_px_size, max_px_size]`.
616    pub flutter_clamp: [f32; 4],
617    /// Multiplicative RGBA tint (alpha modulates global opacity & cloud envelope).
618    pub color: [f32; 4],
619    /// Deterministic per-layer hash seed offset.
620    pub seed: u32,
621}
622
623impl Default for RetainedParticleLayer {
624    fn default() -> Self {
625        Self {
626            id: 0,
627            particle_count: 0,
628            sprite: RetainedParticleSprite::ProceduralStreak,
629            billboard: RetainedParticleBillboard::VelocityAligned,
630            basis_east: [1.0, 0.0, 0.0],
631            basis_north: [0.0, 1.0, 0.0],
632            basis_up: [0.0, 0.0, 1.0],
633            forward_bias_world: [0.0, 0.0, 0.0],
634            wrapped_phase: [0.0, 0.0, 0.0],
635            altitude_bounds: [100.0, 0.0, 5_500.0, 900.0],
636            volume_params: [48.0, 36.0, 0.22, 1.4],
637            motion_params: [26.0, 3.0, 1.0, 0.0],
638            size_params: [0.045, 0.95, 0.032, 0.0],
639            flutter_clamp: [0.0, 0.0, 1.4, 52.0],
640            color: [0.80, 0.89, 1.0, 0.72],
641            seed: 1,
642        }
643    }
644}
645
646/// One directional wind-driven ocean wave train for smooth dual-state wind cross-fading.
647#[derive(Debug, Clone, Copy, PartialEq)]
648pub struct RetainedOceanWaveTrain {
649    /// Normalized `[east, north]` wave propagation direction.
650    pub dir_en: [f32; 2],
651    /// Wind speed in m/s governing wave height, wavelength dispersion, and whitecaps.
652    pub wind_speed_mps: f32,
653    /// Continuous wrapped phase clock in seconds for this wave train.
654    pub phase_time_s: f32,
655    /// Cross-fade blend weight in `[0.0..=1.0]`.
656    pub weight: f32,
657}
658
659impl Default for RetainedOceanWaveTrain {
660    fn default() -> Self {
661        Self {
662            dir_en: [0.866, 0.5],
663            wind_speed_mps: 8.0,
664            phase_time_s: 0.0,
665            weight: 1.0,
666        }
667    }
668}
669
670/// GPU-native per-pixel ocean wave spectrum & optional coastal shoreline shoaling descriptor.
671///
672/// Shaded directly in the terrain water pass with zero floating CPU polygons, Schlick Fresnel
673/// reflections of the physical 2.5D sky, GGX solar/lunar glitter, and optional coastal SDF surf.
674#[derive(Debug, Clone, PartialEq)]
675pub struct RetainedOceanSurface {
676    pub enabled: bool,
677    /// RTE anchor origin in ECEF / morphed world metres (quantized near camera focus).
678    pub origin_ecef: [f64; 3],
679    /// Local orthonormal unit East vector at `origin_ecef`.
680    pub basis_east: [f32; 3],
681    /// Local orthonormal unit North vector at `origin_ecef`.
682    pub basis_north: [f32; 3],
683    /// Local orthonormal unit Up vector at `origin_ecef`.
684    pub basis_up: [f32; 3],
685    /// Primary (outgoing or steady-state) directional wave train.
686    pub train_a: RetainedOceanWaveTrain,
687    /// Secondary (incoming during wind direction/speed transition) wave train.
688    pub train_b: RetainedOceanWaveTrain,
689    /// Overall wave slope / height strength multiplier (`1.0` default).
690    pub wave_strength: f32,
691    /// Spatial frequency multiplier (`1.0` default).
692    pub wave_scale: f32,
693    /// Solar/lunar specular glitter intensity multiplier (`1.0` default).
694    pub glint_intensity: f32,
695    /// Surface shading blend opacity over underlying water imagery (`0.82` default).
696    pub opacity: f32,
697    /// Altitude visibility fade in `[0.0..=1.0]`.
698    pub alt_fade: f32,
699    /// Enables optional coastal shoreline refraction, breaking surf lines, and periodic swash.
700    pub coastal_shoaling: bool,
701    /// Distance in metres from shoreline over which shoaling & periodic surf occur (`360.0` default).
702    pub shoaling_range_m: f32,
703    /// World half-span in metres covered by `coastal_sdf` around `sdf_center_en_m`.
704    pub sdf_half_span_m: f32,
705    /// Offset `[east_m, north_m]` of the coastal SDF texture center relative to `origin_ecef`.
706    pub sdf_center_en_m: [f32; 2],
707    /// Optional `256x256` RGBA8 shoreline SDF texture (`R=water_mask, G=shore_dist_norm, BA=shore_dir_en`).
708    pub coastal_sdf: Option<std::sync::Arc<RetainedTileTexture>>,
709}
710
711impl Default for RetainedOceanSurface {
712    fn default() -> Self {
713        Self {
714            enabled: false,
715            origin_ecef: [0.0; 3],
716            basis_east: [1.0, 0.0, 0.0],
717            basis_north: [0.0, 1.0, 0.0],
718            basis_up: [0.0, 0.0, 1.0],
719            train_a: RetainedOceanWaveTrain::default(),
720            train_b: RetainedOceanWaveTrain {
721                weight: 0.0,
722                ..RetainedOceanWaveTrain::default()
723            },
724            wave_strength: 1.0,
725            wave_scale: 1.0,
726            glint_intensity: 1.0,
727            opacity: 0.82,
728            alt_fade: 1.0,
729            coastal_shoaling: false,
730            shoaling_range_m: 360.0,
731            sdf_half_span_m: 1_500.0,
732            sdf_center_en_m: [0.0, 0.0],
733            coastal_sdf: None,
734        }
735    }
736}
737
738/// One real catalog star in J2000 ICRF celestial coordinates.
739#[derive(Debug, Clone, Copy, PartialEq)]
740pub struct RetainedStar {
741    /// Unit direction vector in J2000 ICRF equatorial coordinates.
742    pub icrf_dir: [f32; 3],
743    /// Apparent visual magnitude (Vmag; lower = brighter).
744    pub vmag: f32,
745    /// Linear sRGB Planck blackbody color `(r, g, b)` + `1.0` alpha.
746    pub color: [f32; 4],
747}
748
749/// 6-face RGBA8 cubemap texture uploadable to `wgpu` (`TextureViewDimension::Cube`).
750#[derive(Debug, Clone, PartialEq)]
751pub struct RetainedCubemapTexture {
752    pub id: u64,
753    pub revision: u64,
754    /// Width and height of each square cubemap face in texels.
755    pub face_size: u32,
756    /// 6 faces in WebGPU/Vulkan array-layer order: `[+X, -X, +Y, -Y, +Z, -Z]`.
757    pub faces_rgba8: [std::sync::Arc<Vec<u8>>; 6],
758}
759
760/// Persistent GPU-uploadable planetary & space environment assets (land mask, cloud map, Moon, star catalog, space skybox).
761#[derive(Debug, Clone, Default, PartialEq)]
762pub struct RetainedEnvironmentAssets {
763    pub revision: u64,
764    /// Equirectangular land mask (land=255, ocean=0 in red/alpha channels) for deterministic land-only city lights.
765    pub land_mask: Option<std::sync::Arc<RetainedTileTexture>>,
766    /// Global 3D equirectangular cloud map texture (alpha or luminance channel).
767    pub cloud_map: Option<std::sync::Arc<RetainedTileTexture>>,
768    /// Equirectangular Moon surface albedo texture (NASA LRO).
769    pub moon_texture: Option<std::sync::Arc<RetainedTileTexture>>,
770    /// Real bright star catalog (e.g. Yale BSC5 in J2000 ICRF).
771    pub stars: Option<std::sync::Arc<Vec<RetainedStar>>>,
772    /// J2000 ICRF telescope space skybox cubemap (`[+X, -X, +Y, -Y, +Z, -Z]`).
773    pub skybox_cubemap: Option<std::sync::Arc<RetainedCubemapTexture>>,
774}
775
776/// Camera and lighting uniforms needed for O(1) RTE GPU frame presentation without scene rebuilds.
777#[derive(Debug, Clone, Copy, PartialEq)]
778pub struct RetainedCameraUniforms {
779    /// Column-major projection matrix.
780    pub proj: [[f32; 4]; 4],
781    /// Column-major camera rotation matrix with camera positioned at world origin `[0, 0, 0]`.
782    pub view_rot: [[f32; 4]; 4],
783    /// Pre-multiplied column-major `proj * view_rot` matrix.
784    pub view_proj_rte: [[f32; 4]; 4],
785    /// High-precision eye position in world / ECEF coordinates.
786    pub eye_ecef: [f64; 3],
787    /// World-space directional sun direction (pointing from surface toward light).
788    pub sun_dir: [f32; 3],
789    pub sun_color: [f32; 3],
790    pub ambient_color: [f32; 3],
791    pub background: Background3D,
792    pub near: f32,
793    pub far: f32,
794    /// Column-major J2000 ICRF -> ECEF rotation matrix (GMST sidereal rotation).
795    pub ecef_from_icrf: [[f32; 4]; 4],
796    /// Normalized ECEF direction toward the Moon.
797    pub moon_dir: [f32; 3],
798    /// Physical day/night terminator strength (`0.0` = flat daylight, `1.0` = full terminator, fades to 0 in 2.5D).
799    pub day_night_strength: f32,
800    /// Deterministic land-masked night city-lights intensity (`0.0` = off, auto-fades out in 2.5D).
801    pub city_lights_intensity: f32,
802    /// Seamless 3D -> 2.5D ground morph factor (`0.0` = 3D space globe, `1.0` = 2.5D local ground).
803    pub local_25d_blend: f32,
804    /// Render physical limb-darkened Sun disc & corona (`true` by default).
805    pub sun_visible: bool,
806    /// Visual Sun angular radius in radians (default ~`0.018` rad).
807    pub sun_angular_radius_rad: f32,
808    /// Render NASA textured Moon with real orbital lunar phase (`true` by default).
809    pub moon_visible: bool,
810    /// Visual Moon angular radius in radians (default ~`0.022` rad).
811    pub moon_angular_radius_rad: f32,
812    /// Render scientific deep-space starfield skybox (`true` by default).
813    pub stars_visible: bool,
814    /// Brightness multiplier for starfield & Milky Way band.
815    pub stars_intensity: f32,
816    /// Brightness multiplier for real telescope skybox cubemap (`1.0` default).
817    pub skybox_intensity: f32,
818    /// Opacity of global 3D cloud-map shell (`0.0` = off; auto-fades out in 2.5D).
819    pub cloud_layer_opacity: f32,
820    /// Opacity of local cropped satellite overhead cloud canopy in low-altitude / 2.5D view.
821    pub local_cloud_opacity: f32,
822    /// Global cloud-map longitudinal scroll offset in radians.
823    pub cloud_lon_offset_rad: f32,
824    /// Simulation / animation time in seconds.
825    pub time_s: f32,
826    /// Opt-in physical Rayleigh/Mie 2.5D sky scattering weight (`0.0` = classic flat blue 2.5D sky, `1.0` = full physical sky).
827    pub realistic_25d_sky: f32,
828    /// Opt-in 2.5D night-sky star & Milky Way visibility sync (`0.0` = off, `1.0` = stars appear at night above horizon).
829    pub night_stars_25d: f32,
830    /// Opt-in physical 2.5D directional sun & DEM relief hillshading weight (`0.0` = flat 2.5D terrain, `1.0` = lit).
831    pub terrain_25d_lighting: f32,
832    /// Opt-in hardware directional shadow-map pass & 9-tap PCF mountain/object shadow strength (`0.0` = disabled).
833    pub terrain_25d_shadows: f32,
834    /// Directional shadow map resolution in pixels (`2048` default; lazily allocated only when shadows > 0).
835    pub shadow_map_size: u32,
836    /// Unified weather optical storm/overcast darkness (`0.0` = clear sky, `1.0` = brooding storm overcast).
837    pub weather_darkness: f32,
838    /// Unified weather cloud cover fraction (`0.0..=1.0`, attenuating sun glare & night stars).
839    pub weather_cloud_cover: f32,
840    /// Unified weather / precipitation atmospheric visibility haze (`0.0..=1.0`).
841    pub weather_haze: f32,
842    /// Weather-modulated cloud RGB tint multiplier (`[1.0, 1.0, 1.0]` neutral).
843    pub cloud_tint_rgb: [f32; 3],
844    /// Weather-driven overhead 2.5D cloud coverage boost (`0.0..=1.0`).
845    pub cloud_25d_cover_boost: f32,
846}
847
848impl Default for RetainedCameraUniforms {
849    fn default() -> Self {
850        let ident = [
851            [1.0, 0.0, 0.0, 0.0],
852            [0.0, 1.0, 0.0, 0.0],
853            [0.0, 0.0, 1.0, 0.0],
854            [0.0, 0.0, 0.0, 1.0],
855        ];
856        Self {
857            proj: ident,
858            view_rot: ident,
859            view_proj_rte: ident,
860            eye_ecef: [0.0, 0.0, 5.0],
861            sun_dir: [0.577_350_26, 0.577_350_26, 0.577_350_26],
862            sun_color: [1.0, 0.98, 0.95],
863            ambient_color: [0.22, 0.24, 0.28],
864            background: Background3D::Transparent,
865            near: 0.1,
866            far: 100_000_000.0,
867            ecef_from_icrf: ident,
868            moon_dir: [-0.577_350_26, 0.577_350_26, 0.577_350_26],
869            day_night_strength: 1.0,
870            city_lights_intensity: 0.0,
871            local_25d_blend: 0.0,
872            sun_visible: false,
873            sun_angular_radius_rad: 0.018,
874            moon_visible: false,
875            moon_angular_radius_rad: 0.022,
876            stars_visible: false,
877            stars_intensity: 1.0,
878            skybox_intensity: 1.0,
879            cloud_layer_opacity: 0.0,
880            local_cloud_opacity: 0.0,
881            cloud_lon_offset_rad: 0.0,
882            time_s: 0.0,
883            realistic_25d_sky: 0.0,
884            night_stars_25d: 0.0,
885            terrain_25d_lighting: 0.0,
886            terrain_25d_shadows: 0.0,
887            shadow_map_size: 2048,
888            weather_darkness: 0.0,
889            weather_cloud_cover: 0.0,
890            weather_haze: 0.0,
891            cloud_tint_rgb: [1.0, 1.0, 1.0],
892            cloud_25d_cover_boost: 0.0,
893        }
894    }
895}
896
897/// Snapshot of retained terrain tiles, textures, dynamic meshes, instanced geo objects,
898/// GPU-instanced 2D camera-local particle volumes, GPU ocean surface, and camera parameters.
899#[derive(Debug, Clone, Default, PartialEq)]
900pub struct RetainedTerrainFrame {
901    pub camera: RetainedCameraUniforms,
902    pub geometry_revision: u64,
903    /// Monotonic revision of `geo_mesh_assets` / `geo_instances`, used to prevent stale background
904    /// tile worker snapshots from overwriting newer main-thread `EarthWorld` updates.
905    pub geo_revision: u64,
906    pub meshes: Vec<std::sync::Arc<RetainedTileMesh>>,
907    pub instances: Vec<RetainedTileInstance>,
908    pub textures: Vec<std::sync::Arc<RetainedTileTexture>>,
909    pub dynamic_meshes: Vec<RetainedDynamicMesh>,
910    pub geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
911    pub geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
912    pub particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
913    pub particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
914    pub ocean: Option<std::sync::Arc<RetainedOceanSurface>>,
915    pub environment: Option<std::sync::Arc<RetainedEnvironmentAssets>>,
916}
917
918#[derive(Debug)]
919struct RetainedSceneState {
920    camera: RetainedCameraUniforms,
921    terrain: Option<std::sync::Arc<RetainedTerrainFrame>>,
922    fallback_scene: Option<std::sync::Arc<Scene3D>>,
923}
924
925#[derive(Debug)]
926struct RetainedScene3DInner {
927    camera_generation: std::sync::atomic::AtomicU64,
928    geometry_generation: std::sync::atomic::AtomicU64,
929    overlay_generation: std::sync::atomic::AtomicU64,
930    geo_revision: std::sync::atomic::AtomicU64,
931    state: std::sync::RwLock<RetainedSceneState>,
932}
933
934/// Thread-safe retained 3D scene handle shared between host state (camera/worker) and `Canvas3D`.
935///
936/// Calling [`RetainedScene3D::update_camera`] updates camera uniforms in place and bumps only
937/// `camera_generation`, allowing the GPU backend to re-render at uncapped framerates without
938/// rebuilding DOM nodes, layout, display lists, or tile meshes.
939#[derive(Clone)]
940pub struct RetainedScene3D {
941    inner: std::sync::Arc<RetainedScene3DInner>,
942}
943
944impl std::fmt::Debug for RetainedScene3D {
945    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
946        let (cam, geom, overlay) = self.generations();
947        f.debug_struct("RetainedScene3D")
948            .field("camera_generation", &cam)
949            .field("geometry_generation", &geom)
950            .field("overlay_generation", &overlay)
951            .finish()
952    }
953}
954
955impl PartialEq for RetainedScene3D {
956    fn eq(&self, other: &Self) -> bool {
957        if std::sync::Arc::ptr_eq(&self.inner, &other.inner) {
958            return true;
959        }
960        let Ok(a) = self.inner.state.read() else {
961            return false;
962        };
963        let Ok(b) = other.inner.state.read() else {
964            return false;
965        };
966        a.camera == b.camera && a.terrain == b.terrain && a.fallback_scene == b.fallback_scene
967    }
968}
969
970impl RetainedScene3D {
971    pub fn new(camera: RetainedCameraUniforms) -> Self {
972        Self {
973            inner: std::sync::Arc::new(RetainedScene3DInner {
974                camera_generation: std::sync::atomic::AtomicU64::new(1),
975                geometry_generation: std::sync::atomic::AtomicU64::new(0),
976                overlay_generation: std::sync::atomic::AtomicU64::new(0),
977                geo_revision: std::sync::atomic::AtomicU64::new(0),
978                state: std::sync::RwLock::new(RetainedSceneState {
979                    camera,
980                    terrain: None,
981                    fallback_scene: None,
982                }),
983            }),
984        }
985    }
986
987    /// Monotonic revision of the latest published `geo_mesh_assets` / `geo_instances`.
988    #[inline]
989    pub fn geo_revision(&self) -> u64 {
990        self.inner
991            .geo_revision
992            .load(std::sync::atomic::Ordering::Acquire)
993    }
994
995    pub fn update_camera(&self, camera: RetainedCameraUniforms) {
996        if let Ok(mut guard) = self.inner.state.write() {
997            guard.camera = camera;
998        }
999        self.inner
1000            .camera_generation
1001            .fetch_add(1, std::sync::atomic::Ordering::Release);
1002    }
1003
1004    pub fn update_terrain(&self, terrain: std::sync::Arc<RetainedTerrainFrame>) {
1005        if let Ok(mut guard) = self.inner.state.write() {
1006            guard.camera = terrain.camera;
1007            let rev = terrain.geo_revision;
1008            guard.terrain = Some(terrain);
1009            self.inner
1010                .geo_revision
1011                .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1012        }
1013        self.inner
1014            .geometry_generation
1015            .fetch_add(1, std::sync::atomic::Ordering::Release);
1016        self.inner
1017            .camera_generation
1018            .fetch_add(1, std::sync::atomic::Ordering::Release);
1019    }
1020
1021    /// Publishes a new terrain tile frame from a background LOD worker while preserving the live camera,
1022    /// any main-thread camera-locked particle layers or GPU ocean state when omitted, and any newer
1023    /// main-thread `geo_mesh_assets`/`geo_instances` (preventing 1-frame rubber-banding).
1024    pub fn update_terrain_preserving_camera(&self, terrain: std::sync::Arc<RetainedTerrainFrame>) {
1025        if let Ok(mut guard) = self.inner.state.write() {
1026            if let Some(ref existing) = guard.terrain {
1027                let keep_particles =
1028                    terrain.particle_layers.is_empty() && !existing.particle_layers.is_empty();
1029                let keep_ocean = terrain.ocean.is_none() && existing.ocean.is_some();
1030                let keep_geo =
1031                    existing.geo_revision > 0 && terrain.geo_revision < existing.geo_revision;
1032                if keep_particles || keep_ocean || keep_geo {
1033                    let mut merged = (*terrain).clone();
1034                    if keep_particles {
1035                        merged.particle_layers = existing.particle_layers.clone();
1036                        merged.particle_textures = existing.particle_textures.clone();
1037                    }
1038                    if keep_ocean {
1039                        merged.ocean = existing.ocean.clone();
1040                    }
1041                    if keep_geo {
1042                        merged.geo_revision = existing.geo_revision;
1043                        merged.geo_mesh_assets = existing.geo_mesh_assets.clone();
1044                        merged.geo_instances = existing.geo_instances.clone();
1045                    }
1046                    let rev = merged.geo_revision;
1047                    guard.terrain = Some(std::sync::Arc::new(merged));
1048                    self.inner
1049                        .geo_revision
1050                        .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1051                } else {
1052                    let rev = terrain.geo_revision;
1053                    guard.terrain = Some(terrain);
1054                    self.inner
1055                        .geo_revision
1056                        .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1057                }
1058            } else {
1059                let rev = terrain.geo_revision;
1060                guard.terrain = Some(terrain);
1061                self.inner
1062                    .geo_revision
1063                    .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1064            }
1065        }
1066        self.inner
1067            .geometry_generation
1068            .fetch_add(1, std::sync::atomic::Ordering::Release);
1069    }
1070
1071    /// Atomically publishes a new terrain tile frame together with its matching camera uniforms
1072    /// while preserving main-thread camera-locked particle layers, GPU ocean state, and newer
1073    /// main-thread `geo_mesh_assets`/`geo_instances` when omitted or stale.
1074    ///
1075    /// Used on the single boundary frame switching between spherical/tangent 3D and the canonical
1076    /// 2D flat-map plane so terrain geometry and camera never mismatch even transiently.
1077    pub fn update_terrain_with_camera_preserving_overlays(
1078        &self,
1079        terrain: std::sync::Arc<RetainedTerrainFrame>,
1080    ) {
1081        if let Ok(mut guard) = self.inner.state.write() {
1082            guard.camera = terrain.camera;
1083            if let Some(ref existing) = guard.terrain {
1084                let keep_particles =
1085                    terrain.particle_layers.is_empty() && !existing.particle_layers.is_empty();
1086                let keep_ocean = terrain.ocean.is_none() && existing.ocean.is_some();
1087                let keep_geo =
1088                    existing.geo_revision > 0 && terrain.geo_revision < existing.geo_revision;
1089                if keep_particles || keep_ocean || keep_geo {
1090                    let mut merged = (*terrain).clone();
1091                    if keep_particles {
1092                        merged.particle_layers = existing.particle_layers.clone();
1093                        merged.particle_textures = existing.particle_textures.clone();
1094                    }
1095                    if keep_ocean {
1096                        merged.ocean = existing.ocean.clone();
1097                    }
1098                    if keep_geo {
1099                        merged.geo_revision = existing.geo_revision;
1100                        merged.geo_mesh_assets = existing.geo_mesh_assets.clone();
1101                        merged.geo_instances = existing.geo_instances.clone();
1102                    }
1103                    let rev = merged.geo_revision;
1104                    guard.terrain = Some(std::sync::Arc::new(merged));
1105                    self.inner
1106                        .geo_revision
1107                        .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1108                } else {
1109                    let rev = terrain.geo_revision;
1110                    guard.terrain = Some(terrain);
1111                    self.inner
1112                        .geo_revision
1113                        .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1114                }
1115            } else {
1116                let rev = terrain.geo_revision;
1117                guard.terrain = Some(terrain);
1118                self.inner
1119                    .geo_revision
1120                    .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1121            }
1122        }
1123        self.inner
1124            .geometry_generation
1125            .fetch_add(1, std::sync::atomic::Ordering::Release);
1126        self.inner
1127            .camera_generation
1128            .fetch_add(1, std::sync::atomic::Ordering::Release);
1129    }
1130
1131    /// Marks the retained 3D scene dirty for one more frame when per-frame GPU texture/mesh upload budgets deferred remaining work.
1132    pub fn request_gpu_continuation(&self) {
1133        self.inner
1134            .camera_generation
1135            .fetch_add(1, std::sync::atomic::Ordering::Release);
1136    }
1137
1138    /// Updates camera uniforms and replaces only dynamic 3D overlays (e.g. orbital satellites)
1139    /// without rebuilding or re-allocating cached terrain tiles, textures, particle volumes, ocean, or environment assets.
1140    pub fn update_camera_and_dynamic_meshes(
1141        &self,
1142        camera: RetainedCameraUniforms,
1143        dynamic_meshes: Vec<RetainedDynamicMesh>,
1144    ) {
1145        if let Ok(mut guard) = self.inner.state.write() {
1146            guard.camera = camera;
1147            if let Some(ref existing) = guard.terrain {
1148                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1149                    camera,
1150                    geometry_revision: existing.geometry_revision,
1151                    geo_revision: existing.geo_revision,
1152                    meshes: existing.meshes.clone(),
1153                    instances: existing.instances.clone(),
1154                    textures: existing.textures.clone(),
1155                    dynamic_meshes,
1156                    geo_mesh_assets: existing.geo_mesh_assets.clone(),
1157                    geo_instances: existing.geo_instances.clone(),
1158                    particle_layers: existing.particle_layers.clone(),
1159                    particle_textures: existing.particle_textures.clone(),
1160                    ocean: existing.ocean.clone(),
1161                    environment: existing.environment.clone(),
1162                }));
1163            }
1164        }
1165        self.inner
1166            .camera_generation
1167            .fetch_add(1, std::sync::atomic::Ordering::Release);
1168    }
1169
1170    /// Updates hardware-instanced geodetic objects in O(1) TerrainFrame shallow-clone time without
1171    /// rebuilding terrain tiles, textures, particle volumes, ocean, or environment state.
1172    pub fn update_geo_objects(
1173        &self,
1174        geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1175        geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1176    ) {
1177        if let Ok(mut guard) = self.inner.state.write() {
1178            let camera = guard.camera;
1179            let next_geo_rev = self
1180                .inner
1181                .geo_revision
1182                .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1183                .wrapping_add(1)
1184                .max(1);
1185            if let Some(ref existing) = guard.terrain {
1186                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1187                    camera,
1188                    geometry_revision: existing.geometry_revision,
1189                    geo_revision: next_geo_rev,
1190                    meshes: existing.meshes.clone(),
1191                    instances: existing.instances.clone(),
1192                    textures: existing.textures.clone(),
1193                    dynamic_meshes: existing.dynamic_meshes.clone(),
1194                    geo_mesh_assets,
1195                    geo_instances,
1196                    particle_layers: existing.particle_layers.clone(),
1197                    particle_textures: existing.particle_textures.clone(),
1198                    ocean: existing.ocean.clone(),
1199                    environment: existing.environment.clone(),
1200                }));
1201            } else {
1202                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1203                    camera,
1204                    geometry_revision: 1,
1205                    geo_revision: next_geo_rev,
1206                    geo_mesh_assets,
1207                    geo_instances,
1208                    ..Default::default()
1209                }));
1210            }
1211        }
1212        self.inner
1213            .geometry_generation
1214            .fetch_add(1, std::sync::atomic::Ordering::Release);
1215        self.inner
1216            .camera_generation
1217            .fetch_add(1, std::sync::atomic::Ordering::Release);
1218    }
1219
1220    /// Updates camera uniforms, dynamic 3D overlays, and hardware-instanced geodetic objects atomically.
1221    pub fn update_camera_and_world_overlays(
1222        &self,
1223        camera: RetainedCameraUniforms,
1224        dynamic_meshes: Vec<RetainedDynamicMesh>,
1225        geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1226        geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1227    ) {
1228        if let Ok(mut guard) = self.inner.state.write() {
1229            guard.camera = camera;
1230            let next_geo_rev = self
1231                .inner
1232                .geo_revision
1233                .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1234                .wrapping_add(1)
1235                .max(1);
1236            if let Some(ref existing) = guard.terrain {
1237                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1238                    camera,
1239                    geometry_revision: existing.geometry_revision,
1240                    geo_revision: next_geo_rev,
1241                    meshes: existing.meshes.clone(),
1242                    instances: existing.instances.clone(),
1243                    textures: existing.textures.clone(),
1244                    dynamic_meshes,
1245                    geo_mesh_assets,
1246                    geo_instances,
1247                    particle_layers: existing.particle_layers.clone(),
1248                    particle_textures: existing.particle_textures.clone(),
1249                    ocean: existing.ocean.clone(),
1250                    environment: existing.environment.clone(),
1251                }));
1252            } else if !geo_instances.is_empty() || !dynamic_meshes.is_empty() {
1253                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1254                    camera,
1255                    geometry_revision: 1,
1256                    geo_revision: next_geo_rev,
1257                    dynamic_meshes,
1258                    geo_mesh_assets,
1259                    geo_instances,
1260                    ..Default::default()
1261                }));
1262            }
1263        }
1264        self.inner
1265            .camera_generation
1266            .fetch_add(1, std::sync::atomic::Ordering::Release);
1267    }
1268
1269    /// Updates camera uniforms and hardware-instanced geodetic objects atomically while preserving
1270    /// existing terrain meshes, textures, particle volumes, ocean, and dynamic 3D overlays.
1271    pub fn update_camera_and_geo_objects(
1272        &self,
1273        camera: RetainedCameraUniforms,
1274        geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1275        geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1276    ) {
1277        if let Ok(mut guard) = self.inner.state.write() {
1278            guard.camera = camera;
1279            let next_geo_rev = self
1280                .inner
1281                .geo_revision
1282                .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1283                .wrapping_add(1)
1284                .max(1);
1285            if let Some(ref existing) = guard.terrain {
1286                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1287                    camera,
1288                    geometry_revision: existing.geometry_revision,
1289                    geo_revision: next_geo_rev,
1290                    meshes: existing.meshes.clone(),
1291                    instances: existing.instances.clone(),
1292                    textures: existing.textures.clone(),
1293                    dynamic_meshes: existing.dynamic_meshes.clone(),
1294                    geo_mesh_assets,
1295                    geo_instances,
1296                    particle_layers: existing.particle_layers.clone(),
1297                    particle_textures: existing.particle_textures.clone(),
1298                    ocean: existing.ocean.clone(),
1299                    environment: existing.environment.clone(),
1300                }));
1301            } else if !geo_instances.is_empty() {
1302                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1303                    camera,
1304                    geometry_revision: 1,
1305                    geo_revision: next_geo_rev,
1306                    geo_mesh_assets,
1307                    geo_instances,
1308                    ..Default::default()
1309                }));
1310            }
1311        }
1312        self.inner
1313            .camera_generation
1314            .fetch_add(1, std::sync::atomic::Ordering::Release);
1315    }
1316
1317    /// Updates only GPU-instanced 2D camera-local particle volumes in O(1) without touching terrain,
1318    /// dynamic meshes, ocean, or geodetic objects.
1319    pub fn update_particles(
1320        &self,
1321        particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1322        particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1323    ) {
1324        if let Ok(mut guard) = self.inner.state.write() {
1325            let camera = guard.camera;
1326            if let Some(ref existing) = guard.terrain {
1327                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1328                    camera,
1329                    geometry_revision: existing.geometry_revision,
1330                    geo_revision: existing.geo_revision,
1331                    meshes: existing.meshes.clone(),
1332                    instances: existing.instances.clone(),
1333                    textures: existing.textures.clone(),
1334                    dynamic_meshes: existing.dynamic_meshes.clone(),
1335                    geo_mesh_assets: existing.geo_mesh_assets.clone(),
1336                    geo_instances: existing.geo_instances.clone(),
1337                    particle_layers,
1338                    particle_textures,
1339                    ocean: existing.ocean.clone(),
1340                    environment: existing.environment.clone(),
1341                }));
1342            } else if !particle_layers.is_empty() {
1343                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1344                    camera,
1345                    geometry_revision: 1,
1346                    particle_layers,
1347                    particle_textures,
1348                    ..Default::default()
1349                }));
1350            }
1351        }
1352        self.inner
1353            .camera_generation
1354            .fetch_add(1, std::sync::atomic::Ordering::Release);
1355    }
1356
1357    /// Updates camera uniforms and GPU-instanced 2D camera-local particle volumes atomically in O(1).
1358    pub fn update_camera_and_particles(
1359        &self,
1360        camera: RetainedCameraUniforms,
1361        particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1362        particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1363    ) {
1364        if let Ok(mut guard) = self.inner.state.write() {
1365            guard.camera = camera;
1366            if let Some(ref existing) = guard.terrain {
1367                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1368                    camera,
1369                    geometry_revision: existing.geometry_revision,
1370                    geo_revision: existing.geo_revision,
1371                    meshes: existing.meshes.clone(),
1372                    instances: existing.instances.clone(),
1373                    textures: existing.textures.clone(),
1374                    dynamic_meshes: existing.dynamic_meshes.clone(),
1375                    geo_mesh_assets: existing.geo_mesh_assets.clone(),
1376                    geo_instances: existing.geo_instances.clone(),
1377                    particle_layers,
1378                    particle_textures,
1379                    ocean: existing.ocean.clone(),
1380                    environment: existing.environment.clone(),
1381                }));
1382            } else if !particle_layers.is_empty() {
1383                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1384                    camera,
1385                    geometry_revision: 1,
1386                    particle_layers,
1387                    particle_textures,
1388                    ..Default::default()
1389                }));
1390            }
1391        }
1392        self.inner
1393            .camera_generation
1394            .fetch_add(1, std::sync::atomic::Ordering::Release);
1395    }
1396
1397    /// Updates camera uniforms and GPU ocean surface descriptor atomically in O(1).
1398    pub fn update_camera_and_ocean(
1399        &self,
1400        camera: RetainedCameraUniforms,
1401        ocean: Option<std::sync::Arc<RetainedOceanSurface>>,
1402    ) {
1403        if let Ok(mut guard) = self.inner.state.write() {
1404            guard.camera = camera;
1405            if let Some(ref existing) = guard.terrain {
1406                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1407                    camera,
1408                    geometry_revision: existing.geometry_revision,
1409                    geo_revision: existing.geo_revision,
1410                    meshes: existing.meshes.clone(),
1411                    instances: existing.instances.clone(),
1412                    textures: existing.textures.clone(),
1413                    dynamic_meshes: existing.dynamic_meshes.clone(),
1414                    geo_mesh_assets: existing.geo_mesh_assets.clone(),
1415                    geo_instances: existing.geo_instances.clone(),
1416                    particle_layers: existing.particle_layers.clone(),
1417                    particle_textures: existing.particle_textures.clone(),
1418                    ocean,
1419                    environment: existing.environment.clone(),
1420                }));
1421            } else if ocean.is_some() {
1422                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1423                    camera,
1424                    geometry_revision: 1,
1425                    ocean,
1426                    ..Default::default()
1427                }));
1428            }
1429        }
1430        self.inner
1431            .camera_generation
1432            .fetch_add(1, std::sync::atomic::Ordering::Release);
1433    }
1434
1435    /// Updates camera uniforms, particle volumes, and GPU ocean surface descriptor atomically in O(1).
1436    pub fn update_camera_and_particles_and_ocean(
1437        &self,
1438        camera: RetainedCameraUniforms,
1439        particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1440        particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1441        ocean: Option<std::sync::Arc<RetainedOceanSurface>>,
1442    ) {
1443        if let Ok(mut guard) = self.inner.state.write() {
1444            guard.camera = camera;
1445            if let Some(ref existing) = guard.terrain {
1446                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1447                    camera,
1448                    geometry_revision: existing.geometry_revision,
1449                    geo_revision: existing.geo_revision,
1450                    meshes: existing.meshes.clone(),
1451                    instances: existing.instances.clone(),
1452                    textures: existing.textures.clone(),
1453                    dynamic_meshes: existing.dynamic_meshes.clone(),
1454                    geo_mesh_assets: existing.geo_mesh_assets.clone(),
1455                    geo_instances: existing.geo_instances.clone(),
1456                    particle_layers,
1457                    particle_textures,
1458                    ocean,
1459                    environment: existing.environment.clone(),
1460                }));
1461            } else if !particle_layers.is_empty() || ocean.is_some() {
1462                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1463                    camera,
1464                    geometry_revision: 1,
1465                    particle_layers,
1466                    particle_textures,
1467                    ocean,
1468                    ..Default::default()
1469                }));
1470            }
1471        }
1472        self.inner
1473            .camera_generation
1474            .fetch_add(1, std::sync::atomic::Ordering::Release);
1475    }
1476
1477    /// Updates camera uniforms, hardware-instanced geodetic objects, and particle volumes atomically.
1478    pub fn update_camera_and_geo_and_particles(
1479        &self,
1480        camera: RetainedCameraUniforms,
1481        geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1482        geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1483        particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1484        particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1485    ) {
1486        if let Ok(mut guard) = self.inner.state.write() {
1487            guard.camera = camera;
1488            let next_geo_rev = self
1489                .inner
1490                .geo_revision
1491                .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1492                .wrapping_add(1)
1493                .max(1);
1494            if let Some(ref existing) = guard.terrain {
1495                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1496                    camera,
1497                    geometry_revision: existing.geometry_revision,
1498                    geo_revision: next_geo_rev,
1499                    meshes: existing.meshes.clone(),
1500                    instances: existing.instances.clone(),
1501                    textures: existing.textures.clone(),
1502                    dynamic_meshes: existing.dynamic_meshes.clone(),
1503                    geo_mesh_assets,
1504                    geo_instances,
1505                    particle_layers,
1506                    particle_textures,
1507                    ocean: existing.ocean.clone(),
1508                    environment: existing.environment.clone(),
1509                }));
1510            } else if !geo_instances.is_empty() || !particle_layers.is_empty() {
1511                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1512                    camera,
1513                    geometry_revision: 1,
1514                    geo_revision: next_geo_rev,
1515                    geo_mesh_assets,
1516                    geo_instances,
1517                    particle_layers,
1518                    particle_textures,
1519                    ..Default::default()
1520                }));
1521            }
1522        }
1523        self.inner
1524            .camera_generation
1525            .fetch_add(1, std::sync::atomic::Ordering::Release);
1526    }
1527
1528    /// Updates camera uniforms, dynamic overlays, geodetic objects, and particle volumes atomically.
1529    pub fn update_camera_and_world_and_particles(
1530        &self,
1531        camera: RetainedCameraUniforms,
1532        dynamic_meshes: Vec<RetainedDynamicMesh>,
1533        geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1534        geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1535        particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1536        particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1537    ) {
1538        if let Ok(mut guard) = self.inner.state.write() {
1539            guard.camera = camera;
1540            let next_geo_rev = self
1541                .inner
1542                .geo_revision
1543                .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1544                .wrapping_add(1)
1545                .max(1);
1546            if let Some(ref existing) = guard.terrain {
1547                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1548                    camera,
1549                    geometry_revision: existing.geometry_revision,
1550                    geo_revision: next_geo_rev,
1551                    meshes: existing.meshes.clone(),
1552                    instances: existing.instances.clone(),
1553                    textures: existing.textures.clone(),
1554                    dynamic_meshes,
1555                    geo_mesh_assets,
1556                    geo_instances,
1557                    particle_layers,
1558                    particle_textures,
1559                    ocean: existing.ocean.clone(),
1560                    environment: existing.environment.clone(),
1561                }));
1562            } else if !geo_instances.is_empty()
1563                || !dynamic_meshes.is_empty()
1564                || !particle_layers.is_empty()
1565            {
1566                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1567                    camera,
1568                    geometry_revision: 1,
1569                    geo_revision: next_geo_rev,
1570                    dynamic_meshes,
1571                    geo_mesh_assets,
1572                    geo_instances,
1573                    particle_layers,
1574                    particle_textures,
1575                    ..Default::default()
1576                }));
1577            }
1578        }
1579        self.inner
1580            .camera_generation
1581            .fetch_add(1, std::sync::atomic::Ordering::Release);
1582    }
1583
1584    /// Updates camera uniforms, dynamic overlays, geodetic objects, particle volumes, and GPU ocean atomically.
1585    pub fn update_camera_and_world_and_particles_and_ocean(
1586        &self,
1587        camera: RetainedCameraUniforms,
1588        dynamic_meshes: Vec<RetainedDynamicMesh>,
1589        geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1590        geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1591        particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1592        particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1593        ocean: Option<std::sync::Arc<RetainedOceanSurface>>,
1594    ) {
1595        if let Ok(mut guard) = self.inner.state.write() {
1596            guard.camera = camera;
1597            let next_geo_rev = self
1598                .inner
1599                .geo_revision
1600                .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1601                .wrapping_add(1)
1602                .max(1);
1603            if let Some(ref existing) = guard.terrain {
1604                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1605                    camera,
1606                    geometry_revision: existing.geometry_revision,
1607                    geo_revision: next_geo_rev,
1608                    meshes: existing.meshes.clone(),
1609                    instances: existing.instances.clone(),
1610                    textures: existing.textures.clone(),
1611                    dynamic_meshes,
1612                    geo_mesh_assets,
1613                    geo_instances,
1614                    particle_layers,
1615                    particle_textures,
1616                    ocean,
1617                    environment: existing.environment.clone(),
1618                }));
1619            } else if !geo_instances.is_empty()
1620                || !dynamic_meshes.is_empty()
1621                || !particle_layers.is_empty()
1622                || ocean.is_some()
1623            {
1624                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1625                    camera,
1626                    geometry_revision: 1,
1627                    geo_revision: next_geo_rev,
1628                    dynamic_meshes,
1629                    geo_mesh_assets,
1630                    geo_instances,
1631                    particle_layers,
1632                    particle_textures,
1633                    ocean,
1634                    ..Default::default()
1635                }));
1636            }
1637        }
1638        self.inner
1639            .camera_generation
1640            .fetch_add(1, std::sync::atomic::Ordering::Release);
1641    }
1642
1643    pub fn set_fallback_scene(&self, scene: std::sync::Arc<Scene3D>) {
1644        if let Ok(mut guard) = self.inner.state.write() {
1645            guard.fallback_scene = Some(scene);
1646        }
1647        self.inner
1648            .overlay_generation
1649            .fetch_add(1, std::sync::atomic::Ordering::Release);
1650    }
1651
1652    #[inline]
1653    pub fn camera_generation(&self) -> u64 {
1654        self.inner
1655            .camera_generation
1656            .load(std::sync::atomic::Ordering::Acquire)
1657    }
1658
1659    #[inline]
1660    pub fn geometry_generation(&self) -> u64 {
1661        self.inner
1662            .geometry_generation
1663            .load(std::sync::atomic::Ordering::Acquire)
1664    }
1665
1666    #[inline]
1667    pub fn overlay_generation(&self) -> u64 {
1668        self.inner
1669            .overlay_generation
1670            .load(std::sync::atomic::Ordering::Acquire)
1671    }
1672
1673    #[inline]
1674    pub fn generations(&self) -> (u64, u64, u64) {
1675        (
1676            self.camera_generation(),
1677            self.geometry_generation(),
1678            self.overlay_generation(),
1679        )
1680    }
1681
1682    pub fn camera(&self) -> RetainedCameraUniforms {
1683        self.inner
1684            .state
1685            .read()
1686            .map(|g| g.camera)
1687            .unwrap_or_default()
1688    }
1689
1690    pub fn snapshot_terrain(&self) -> Option<std::sync::Arc<RetainedTerrainFrame>> {
1691        self.inner.state.read().ok().and_then(|g| g.terrain.clone())
1692    }
1693
1694    pub fn fallback_scene(&self) -> Option<std::sync::Arc<Scene3D>> {
1695        self.inner
1696            .state
1697            .read()
1698            .ok()
1699            .and_then(|g| g.fallback_scene.clone())
1700    }
1701}
1702
1703/// Top-Level 3D Scene representation embedded in a Strata Viewport.
1704///
1705/// The background, celestial, cloud, overlay, and texture store state are private so adding
1706/// them does not break struct literals written by existing callers. Use the
1707/// `with_*` builders; the accessors below read them back.
1708#[derive(Debug, Default, Clone, PartialEq)]
1709pub struct Scene3D {
1710    pub camera: Camera3D,
1711    pub lights: Vec<Light3D>,
1712    pub meshes: Vec<Mesh3D>,
1713    background: Background3D,
1714    celestial: Vec<CelestialBody3D>,
1715    cloud_shells: Vec<CloudShell3D>,
1716    overlay: Option<Overlay3D>,
1717    /// Camera up hint in world space. `None` uses the renderer's fallback.
1718    camera_up: Option<[f64; 3]>,
1719    /// Optional shared texture registry resolved automatically by software, Cairo, and GPU viewport rasterizers.
1720    textures: Option<std::sync::Arc<crate::texture3d::TextureStore>>,
1721    /// Optional retained terrain snapshot attached for zero-rebuild GPU vertex pulling.
1722    retained_terrain: Option<std::sync::Arc<RetainedTerrainFrame>>,
1723    /// Optional retained scene handle allowing out-of-band O(1) camera/worker updates.
1724    retained_handle: Option<RetainedScene3D>,
1725}
1726
1727impl Scene3D {
1728    pub fn new() -> Self {
1729        Self::default()
1730    }
1731
1732    pub fn with_retained_terrain(mut self, terrain: std::sync::Arc<RetainedTerrainFrame>) -> Self {
1733        self.retained_terrain = Some(terrain);
1734        self
1735    }
1736
1737    pub fn set_retained_terrain(&mut self, terrain: Option<std::sync::Arc<RetainedTerrainFrame>>) {
1738        self.retained_terrain = terrain;
1739    }
1740
1741    pub fn retained_terrain(&self) -> Option<&std::sync::Arc<RetainedTerrainFrame>> {
1742        self.retained_terrain.as_ref()
1743    }
1744
1745    pub fn with_retained_handle(mut self, handle: RetainedScene3D) -> Self {
1746        self.retained_handle = Some(handle);
1747        self
1748    }
1749
1750    pub fn set_retained_handle(&mut self, handle: Option<RetainedScene3D>) {
1751        self.retained_handle = handle;
1752    }
1753
1754    pub fn retained_handle(&self) -> Option<&RetainedScene3D> {
1755        self.retained_handle.as_ref()
1756    }
1757
1758    pub fn add_mesh(&mut self, mesh: Mesh3D) {
1759        self.meshes.push(mesh);
1760    }
1761
1762    pub fn add_light(&mut self, light: Light3D) {
1763        self.lights.push(light);
1764    }
1765
1766    /// Replaces the background fill used before geometry is drawn.
1767    pub fn with_background(mut self, background: Background3D) -> Self {
1768        self.background = background;
1769        self
1770    }
1771
1772    /// Adds an emissive celestial body.
1773    pub fn with_celestial(mut self, body: CelestialBody3D) -> Self {
1774        self.celestial.push(body);
1775        self
1776    }
1777
1778    /// Adds a translucent cloud shell.
1779    pub fn with_cloud_shell(mut self, shell: CloudShell3D) -> Self {
1780        self.cloud_shells.push(shell);
1781        self
1782    }
1783
1784    /// Attaches the overlay pass drawn after geometry.
1785    pub fn with_overlay(mut self, overlay: Overlay3D) -> Self {
1786        self.overlay = Some(overlay);
1787        self
1788    }
1789
1790    pub fn overlay(&self) -> Option<&Overlay3D> {
1791        self.overlay.as_ref()
1792    }
1793
1794    /// Returns a mutable reference to the scene's 3D overlay pass, initializing an empty
1795    /// [`Overlay3D`] if none is attached yet.
1796    pub fn overlay_mut(&mut self) -> &mut Overlay3D {
1797        self.overlay.get_or_insert_with(Overlay3D::new)
1798    }
1799
1800    /// Attaches a shared [`crate::texture3d::TextureStore`] carried with the scene through
1801    /// `DrawCommand::DrawViewport3D` into live window and offscreen rasterizers.
1802    pub fn with_textures(
1803        mut self,
1804        textures: std::sync::Arc<crate::texture3d::TextureStore>,
1805    ) -> Self {
1806        self.textures = Some(textures);
1807        self
1808    }
1809
1810    /// Sets or clears the shared [`crate::texture3d::TextureStore`] attached to this scene.
1811    pub fn set_textures(
1812        &mut self,
1813        textures: Option<std::sync::Arc<crate::texture3d::TextureStore>>,
1814    ) {
1815        self.textures = textures;
1816    }
1817
1818    /// Borrows the shared [`crate::texture3d::TextureStore`] handle attached to this scene, if any.
1819    pub fn textures(&self) -> Option<&std::sync::Arc<crate::texture3d::TextureStore>> {
1820        self.textures.as_ref()
1821    }
1822
1823    /// Borrows the underlying [`crate::texture3d::TextureStore`] attached to this scene, if any.
1824    pub fn textures_deref(&self) -> Option<&crate::texture3d::TextureStore> {
1825        self.textures.as_deref()
1826    }
1827
1828    /// Sets the camera's up direction. A downward-looking camera has no unique
1829    /// screen up from the world Y axis, so scenes that care about roll should
1830    /// declare it, for example the local east-north-up frame at a ground focus.
1831    pub fn with_camera_up(mut self, up: [f64; 3]) -> Self {
1832        self.camera_up = Some(up);
1833        self
1834    }
1835
1836    pub fn camera_up(&self) -> Option<[f64; 3]> {
1837        self.camera_up
1838    }
1839
1840    pub fn background(&self) -> Background3D {
1841        self.background
1842    }
1843
1844    pub fn celestial(&self) -> &[CelestialBody3D] {
1845        &self.celestial
1846    }
1847
1848    pub fn cloud_shells(&self) -> &[CloudShell3D] {
1849        &self.cloud_shells
1850    }
1851}
1852
1853/// Callback that rasterizes a text run into the framebuffer.
1854///
1855/// The 3D overlay pass needs text, but `strata_render` must not depend on the
1856/// platform text backend. Consumers install a rasterizer, exactly like the
1857/// layout crate installs a text measurer.
1858pub type TextRasterizer = crate::overlay3d::TextRasterizer;
1859
1860thread_local! {
1861    static TEXT_RASTERIZER: std::cell::Cell<Option<TextRasterizer>> = const { std::cell::Cell::new(None) };
1862}
1863
1864/// Installs the overlay text rasterizer for this thread.
1865pub fn register_overlay_text_rasterizer(rasterizer: TextRasterizer) {
1866    TEXT_RASTERIZER.with(|slot| slot.set(Some(rasterizer)));
1867}
1868
1869/// Returns the installed overlay text rasterizer, if any.
1870pub fn overlay_text_rasterizer() -> Option<TextRasterizer> {
1871    TEXT_RASTERIZER.with(|slot| slot.get())
1872}
1873
1874// ---------------------------------------------------------------------------
1875// Declarative & Programmatic 3D RSX Viewport Components
1876// ---------------------------------------------------------------------------
1877
1878use strata_dom::{Attribute, NodeBlueprint, Tag, View};
1879use strata_macro::component;
1880
1881/// Conversion trait allowing RSX `<Canvas3D scene={...}>` and `<SceneViewport scene={...}>`
1882/// props to accept owned [`Scene3D`], `Option<Scene3D>`, or zero-copy `Arc<Scene3D>` handles.
1883pub trait IntoScene3DProp {
1884    fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>>;
1885}
1886
1887impl IntoScene3DProp for Scene3D {
1888    fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
1889        Some(std::sync::Arc::new(self))
1890    }
1891}
1892
1893impl IntoScene3DProp for Option<Scene3D> {
1894    fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
1895        self.map(std::sync::Arc::new)
1896    }
1897}
1898
1899impl IntoScene3DProp for std::sync::Arc<Scene3D> {
1900    fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
1901        Some(self)
1902    }
1903}
1904
1905impl IntoScene3DProp for &std::sync::Arc<Scene3D> {
1906    fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
1907        Some(std::sync::Arc::clone(self))
1908    }
1909}
1910
1911impl IntoScene3DProp for Option<std::sync::Arc<Scene3D>> {
1912    fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
1913        self
1914    }
1915}
1916
1917impl IntoScene3DProp for Option<&std::sync::Arc<Scene3D>> {
1918    fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
1919        self.map(std::sync::Arc::clone)
1920    }
1921}
1922
1923#[allow(non_snake_case)]
1924pub fn Canvas3D(class: Option<&'static str>, children: Option<Vec<NodeBlueprint>>) -> View {
1925    let mut builder = Canvas3D::builder();
1926    if let Some(c) = class {
1927        builder = builder.class(c);
1928    }
1929    if let Some(ch) = children {
1930        builder = builder.children(ch);
1931    }
1932    builder.build()
1933}
1934
1935#[allow(non_snake_case)]
1936pub struct Canvas3D {}
1937
1938impl Canvas3D {
1939    pub fn builder() -> Canvas3DBuilder {
1940        Canvas3DBuilder::default()
1941    }
1942}
1943
1944/// Conversion trait allowing `on_camera_change` on 3D viewports (`Canvas3D`, `SceneViewport`)
1945/// to accept closures, `Rc<dyn Fn(&OrbitControls)>`, or `Option<Rc<dyn Fn(&OrbitControls)>>`.
1946pub trait IntoCameraChangeProp {
1947    fn into_camera_change_prop(
1948        self,
1949    ) -> Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>>;
1950}
1951
1952impl IntoCameraChangeProp for Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>> {
1953    fn into_camera_change_prop(
1954        self,
1955    ) -> Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>> {
1956        self
1957    }
1958}
1959
1960impl IntoCameraChangeProp for std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)> {
1961    fn into_camera_change_prop(
1962        self,
1963    ) -> Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>> {
1964        Some(self)
1965    }
1966}
1967
1968impl<F: Fn(&crate::orbit_controls::OrbitControls) + 'static> IntoCameraChangeProp for F {
1969    fn into_camera_change_prop(
1970        self,
1971    ) -> Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>> {
1972        Some(std::rc::Rc::new(self))
1973    }
1974}
1975
1976/// Attaches built-in `OrbitControls` pointer drag (orbit/pan) and wheel (zoom) listeners
1977/// to a 3D canvas attribute list, invoking `cb` whenever the camera state changes.
1978pub fn attach_orbit_controls_listeners(
1979    attrs: &mut Vec<Attribute>,
1980    scene: Option<&Scene3D>,
1981    width: Option<f32>,
1982    height: Option<f32>,
1983    cb: std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>,
1984) {
1985    use std::cell::RefCell;
1986    use std::rc::Rc;
1987    use strata_dom::{Event, EventType};
1988
1989    let mut initial_controls = match scene {
1990        Some(s) => crate::orbit_controls::OrbitControls::from_camera(&s.camera),
1991        None => crate::orbit_controls::OrbitControls::default(),
1992    };
1993    initial_controls.enable_damping = false;
1994    let fov_deg = match scene.map(|s| &s.camera) {
1995        Some(Camera3D::Perspective {
1996            fov_horizontal_deg, ..
1997        }) => *fov_horizontal_deg,
1998        _ => 60.0,
1999    };
2000    let vw = width.unwrap_or(800.0).max(1.0);
2001    let vh = height.unwrap_or(600.0).max(1.0);
2002    let controls = Rc::new(RefCell::new(initial_controls));
2003
2004    let ctrl_down = Rc::clone(&controls);
2005    attrs.push(Attribute::event_listener(
2006        EventType::PointerDown,
2007        move |ev: Event| {
2008            let btn = ev.button.max(0) as u8;
2009            ctrl_down
2010                .borrow_mut()
2011                .on_pointer_down(ev.client_x as f32, ev.client_y as f32, btn);
2012        },
2013    ));
2014
2015    let ctrl_move = Rc::clone(&controls);
2016    let cb_move = Rc::clone(&cb);
2017    attrs.push(Attribute::event_listener(
2018        EventType::PointerMove,
2019        move |ev: Event| {
2020            let changed = {
2021                let mut c = ctrl_move.borrow_mut();
2022                let active = c.active_mode != crate::orbit_controls::OrbitInteractionMode::None;
2023                if active {
2024                    c.on_pointer_move(ev.client_x as f32, ev.client_y as f32, vw, vh, fov_deg);
2025                }
2026                active
2027            };
2028            if changed {
2029                let c = ctrl_move.borrow();
2030                cb_move(&c);
2031            }
2032        },
2033    ));
2034
2035    let ctrl_up = Rc::clone(&controls);
2036    attrs.push(Attribute::event_listener(
2037        EventType::PointerUp,
2038        move |_ev: Event| {
2039            ctrl_up.borrow_mut().on_pointer_up();
2040        },
2041    ));
2042
2043    let ctrl_wheel = Rc::clone(&controls);
2044    let cb_wheel = Rc::clone(&cb);
2045    attrs.push(Attribute::event_listener(
2046        EventType::Wheel,
2047        move |ev: Event| {
2048            ev.default_prevented.set(true);
2049            {
2050                let mut c = ctrl_wheel.borrow_mut();
2051                c.on_wheel(ev.delta_y as f32);
2052            }
2053            let c = ctrl_wheel.borrow();
2054            cb_wheel(&c);
2055        },
2056    ));
2057}
2058
2059#[derive(Default)]
2060pub struct Canvas3DBuilder {
2061    pub scene: Option<std::sync::Arc<Scene3D>>,
2062    pub retained: Option<RetainedScene3D>,
2063    pub uncapped: bool,
2064    pub class: Option<strata_dom::ClassList>,
2065    pub style: Option<String>,
2066    pub id: Option<String>,
2067    pub width: Option<f32>,
2068    pub height: Option<f32>,
2069    pub on_camera_change: Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>>,
2070    pub events: Vec<Attribute>,
2071    pub children: Option<Vec<NodeBlueprint>>,
2072}
2073
2074impl Canvas3DBuilder {
2075    pub fn scene(mut self, scene: impl IntoScene3DProp) -> Self {
2076        self.scene = scene.into_scene3d_prop();
2077        self
2078    }
2079
2080    pub fn class(mut self, class: impl Into<strata_dom::ClassList>) -> Self {
2081        self.class = Some(class.into());
2082        self
2083    }
2084
2085    pub fn style(mut self, style: impl Into<String>) -> Self {
2086        self.style = Some(style.into());
2087        self
2088    }
2089
2090    pub fn id(mut self, id: impl Into<String>) -> Self {
2091        self.id = Some(id.into());
2092        self
2093    }
2094
2095    pub fn width(mut self, width: impl Into<Option<f32>>) -> Self {
2096        self.width = width.into();
2097        self
2098    }
2099
2100    pub fn height(mut self, height: impl Into<Option<f32>>) -> Self {
2101        self.height = height.into();
2102        self
2103    }
2104
2105    pub fn on_camera_change(mut self, cb: impl IntoCameraChangeProp) -> Self {
2106        self.on_camera_change = cb.into_camera_change_prop();
2107        self
2108    }
2109
2110    pub fn on_camera_change_fn(
2111        mut self,
2112        cb: impl Fn(&crate::orbit_controls::OrbitControls) + 'static,
2113    ) -> Self {
2114        self.on_camera_change = Some(std::rc::Rc::new(cb));
2115        self
2116    }
2117
2118    fn push_event(
2119        mut self,
2120        ty: strata_dom::EventType,
2121        handler: impl Fn(strata_dom::Event) + 'static,
2122    ) -> Self {
2123        self.events.push(Attribute::event_listener(ty, handler));
2124        self
2125    }
2126
2127    pub fn onmousedown(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2128        self.push_event(strata_dom::EventType::MouseDown, handler)
2129    }
2130
2131    pub fn onmousedown_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2132        self.onmousedown(handler)
2133    }
2134
2135    pub fn onmousemove(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2136        self.push_event(strata_dom::EventType::MouseMove, handler)
2137    }
2138
2139    pub fn onmousemove_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2140        self.onmousemove(handler)
2141    }
2142
2143    pub fn onmouseup(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2144        self.push_event(strata_dom::EventType::MouseUp, handler)
2145    }
2146
2147    pub fn onmouseup_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2148        self.onmouseup(handler)
2149    }
2150
2151    pub fn onwheel(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2152        self.push_event(strata_dom::EventType::Wheel, handler)
2153    }
2154
2155    pub fn onwheel_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2156        self.onwheel(handler)
2157    }
2158
2159    pub fn onpointerdown(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2160        self.push_event(strata_dom::EventType::PointerDown, handler)
2161    }
2162
2163    pub fn onpointerdown_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2164        self.onpointerdown(handler)
2165    }
2166
2167    pub fn onpointermove(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2168        self.push_event(strata_dom::EventType::PointerMove, handler)
2169    }
2170
2171    pub fn onpointermove_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2172        self.onpointermove(handler)
2173    }
2174
2175    pub fn onpointerup(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2176        self.push_event(strata_dom::EventType::PointerUp, handler)
2177    }
2178
2179    pub fn onpointerup_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2180        self.onpointerup(handler)
2181    }
2182
2183    pub fn onclick(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2184        self.push_event(strata_dom::EventType::Click, handler)
2185    }
2186
2187    pub fn onclick_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2188        self.onclick(handler)
2189    }
2190
2191    pub fn onresize(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2192        self.push_event(strata_dom::EventType::Resize, handler)
2193    }
2194
2195    pub fn onresize_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2196        self.onresize(handler)
2197    }
2198
2199    /// Binds a persistent [`RetainedScene3D`] handle for out-of-band zero-rebuild GPU updates.
2200    pub fn retained(mut self, handle: impl Into<Option<RetainedScene3D>>) -> Self {
2201        self.retained = handle.into();
2202        self
2203    }
2204
2205    /// Opts this 3D canvas into uncapped vsync-off presentation when supported by the surface.
2206    pub fn uncapped(mut self, uncapped: bool) -> Self {
2207        self.uncapped = uncapped;
2208        self
2209    }
2210
2211    pub fn children(mut self, children: Vec<NodeBlueprint>) -> Self {
2212        self.children = Some(children);
2213        self
2214    }
2215
2216    pub fn build(self) -> View {
2217        let mut attrs = Vec::with_capacity(5 + self.events.len());
2218        attrs.push(Attribute::property("data-strata-canvas3d", "true"));
2219        if self.uncapped {
2220            attrs.push(Attribute::property("data-strata-uncapped", "true"));
2221        }
2222        if let Some(id) = self.id {
2223            attrs.push(Attribute::property("id", id));
2224        }
2225        if let Some(w) = self.width {
2226            attrs.push(Attribute::property("width", w.to_string()));
2227        }
2228        if let Some(h) = self.height {
2229            attrs.push(Attribute::property("height", h.to_string()));
2230        }
2231        if let Some(style) = self.style {
2232            attrs.push(Attribute::property("style", style));
2233        }
2234        attrs.extend(self.events);
2235        let effective_scene = match (self.scene, self.retained) {
2236            (Some(mut scene), Some(retained)) => {
2237                if scene.retained_handle().is_none() {
2238                    let s = std::sync::Arc::make_mut(&mut scene);
2239                    s.set_retained_handle(Some(retained));
2240                }
2241                Some(scene)
2242            }
2243            (Some(scene), None) => Some(scene),
2244            (None, Some(retained)) => {
2245                let mut scene = retained
2246                    .fallback_scene()
2247                    .map(|s| (*s).clone())
2248                    .unwrap_or_default();
2249                scene.set_retained_handle(Some(retained));
2250                Some(std::sync::Arc::new(scene))
2251            }
2252            (None, None) => None,
2253        };
2254        if let Some(cb) = self.on_camera_change {
2255            attach_orbit_controls_listeners(
2256                &mut attrs,
2257                effective_scene.as_deref(),
2258                self.width,
2259                self.height,
2260                cb,
2261            );
2262        }
2263        if let Some(scene) = effective_scene {
2264            let payload: std::sync::Arc<dyn std::any::Any + Send + Sync> = scene;
2265            attrs.push(Attribute::scene_payload_arc(payload));
2266        }
2267        View::new(NodeBlueprint::element(
2268            Tag::Canvas,
2269            self.class.unwrap_or_default(),
2270            attrs,
2271            self.children.unwrap_or_default(),
2272        ))
2273    }
2274}
2275
2276#[component]
2277pub fn PerspectiveCamera(
2278    fov: Option<f32>,
2279    aspect: Option<f32>,
2280    near: Option<f32>,
2281    far: Option<f32>,
2282    position: Option<[f32; 3]>,
2283    target: Option<[f32; 3]>,
2284) -> View {
2285    let mut attrs = Vec::new();
2286    if let Some(f) = fov {
2287        attrs.push(Attribute::property("data-fov", f.to_string()));
2288    }
2289    if let Some(a) = aspect {
2290        attrs.push(Attribute::property("data-aspect", a.to_string()));
2291    }
2292    if let Some(n) = near {
2293        attrs.push(Attribute::property("data-near", n.to_string()));
2294    }
2295    if let Some(fa) = far {
2296        attrs.push(Attribute::property("data-far", fa.to_string()));
2297    }
2298    if let Some(p) = position {
2299        attrs.push(Attribute::property(
2300            "data-position",
2301            format!("{},{},{}", p[0], p[1], p[2]),
2302        ));
2303    }
2304    if let Some(t) = target {
2305        attrs.push(Attribute::property(
2306            "data-target",
2307            format!("{},{},{}", t[0], t[1], t[2]),
2308        ));
2309    }
2310    View::new(NodeBlueprint::element(
2311        Tag::Custom("PerspectiveCamera"),
2312        strata_dom::ClassList::default(),
2313        attrs,
2314        Vec::new(),
2315    ))
2316}
2317
2318#[component]
2319pub fn OrthographicCamera(
2320    left: Option<f32>,
2321    right: Option<f32>,
2322    top: Option<f32>,
2323    bottom: Option<f32>,
2324    near: Option<f32>,
2325    far: Option<f32>,
2326    position: Option<[f32; 3]>,
2327    target: Option<[f32; 3]>,
2328) -> View {
2329    let mut attrs = Vec::new();
2330    if let Some(v) = left {
2331        attrs.push(Attribute::property("data-left", v.to_string()));
2332    }
2333    if let Some(v) = right {
2334        attrs.push(Attribute::property("data-right", v.to_string()));
2335    }
2336    if let Some(v) = top {
2337        attrs.push(Attribute::property("data-top", v.to_string()));
2338    }
2339    if let Some(v) = bottom {
2340        attrs.push(Attribute::property("data-bottom", v.to_string()));
2341    }
2342    if let Some(v) = near {
2343        attrs.push(Attribute::property("data-near", v.to_string()));
2344    }
2345    if let Some(v) = far {
2346        attrs.push(Attribute::property("data-far", v.to_string()));
2347    }
2348    if let Some(p) = position {
2349        attrs.push(Attribute::property(
2350            "data-position",
2351            format!("{},{},{}", p[0], p[1], p[2]),
2352        ));
2353    }
2354    if let Some(t) = target {
2355        attrs.push(Attribute::property(
2356            "data-target",
2357            format!("{},{},{}", t[0], t[1], t[2]),
2358        ));
2359    }
2360    View::new(NodeBlueprint::element(
2361        Tag::Custom("OrthographicCamera"),
2362        strata_dom::ClassList::default(),
2363        attrs,
2364        Vec::new(),
2365    ))
2366}
2367
2368#[component]
2369pub fn AmbientLight(color: Option<&'static str>, intensity: Option<f32>) -> View {
2370    let mut attrs = Vec::new();
2371    if let Some(c) = color {
2372        attrs.push(Attribute::property("data-color", c));
2373    }
2374    if let Some(i) = intensity {
2375        attrs.push(Attribute::property("data-intensity", i.to_string()));
2376    }
2377    View::new(NodeBlueprint::element(
2378        Tag::Custom("AmbientLight"),
2379        strata_dom::ClassList::default(),
2380        attrs,
2381        Vec::new(),
2382    ))
2383}
2384
2385#[component]
2386pub fn DirectionalLight(
2387    position: Option<[f32; 3]>,
2388    color: Option<&'static str>,
2389    intensity: Option<f32>,
2390    cast_shadow: Option<bool>,
2391) -> View {
2392    let mut attrs = Vec::new();
2393    if let Some(p) = position {
2394        attrs.push(Attribute::property(
2395            "data-position",
2396            format!("{},{},{}", p[0], p[1], p[2]),
2397        ));
2398    }
2399    if let Some(c) = color {
2400        attrs.push(Attribute::property("data-color", c));
2401    }
2402    if let Some(i) = intensity {
2403        attrs.push(Attribute::property("data-intensity", i.to_string()));
2404    }
2405    if let Some(s) = cast_shadow {
2406        attrs.push(Attribute::property("data-cast-shadow", s.to_string()));
2407    }
2408    View::new(NodeBlueprint::element(
2409        Tag::Custom("DirectionalLight"),
2410        strata_dom::ClassList::default(),
2411        attrs,
2412        Vec::new(),
2413    ))
2414}
2415
2416#[component]
2417pub fn PointLight(
2418    position: Option<[f32; 3]>,
2419    color: Option<&'static str>,
2420    intensity: Option<f32>,
2421    distance: Option<f32>,
2422) -> View {
2423    let mut attrs = Vec::new();
2424    if let Some(p) = position {
2425        attrs.push(Attribute::property(
2426            "data-position",
2427            format!("{},{},{}", p[0], p[1], p[2]),
2428        ));
2429    }
2430    if let Some(c) = color {
2431        attrs.push(Attribute::property("data-color", c));
2432    }
2433    if let Some(i) = intensity {
2434        attrs.push(Attribute::property("data-intensity", i.to_string()));
2435    }
2436    if let Some(d) = distance {
2437        attrs.push(Attribute::property("data-distance", d.to_string()));
2438    }
2439    View::new(NodeBlueprint::element(
2440        Tag::Custom("PointLight"),
2441        strata_dom::ClassList::default(),
2442        attrs,
2443        Vec::new(),
2444    ))
2445}
2446
2447#[component]
2448pub fn Mesh(
2449    position: Option<[f32; 3]>,
2450    rotation: Option<[f32; 3]>,
2451    scale: Option<[f32; 3]>,
2452    children: Option<Vec<NodeBlueprint>>,
2453) -> View {
2454    let mut attrs = Vec::new();
2455    if let Some(p) = position {
2456        attrs.push(Attribute::property(
2457            "data-position",
2458            format!("{},{},{}", p[0], p[1], p[2]),
2459        ));
2460    }
2461    if let Some(r) = rotation {
2462        attrs.push(Attribute::property(
2463            "data-rotation",
2464            format!("{},{},{}", r[0], r[1], r[2]),
2465        ));
2466    }
2467    if let Some(s) = scale {
2468        attrs.push(Attribute::property(
2469            "data-scale",
2470            format!("{},{},{}", s[0], s[1], s[2]),
2471        ));
2472    }
2473    View::new(NodeBlueprint::element(
2474        Tag::Custom("Mesh"),
2475        strata_dom::ClassList::default(),
2476        attrs,
2477        children.unwrap_or_default(),
2478    ))
2479}
2480
2481#[component]
2482pub fn BoxGeometry(width: Option<f32>, height: Option<f32>, depth: Option<f32>) -> View {
2483    let mut attrs = Vec::new();
2484    if let Some(w) = width {
2485        attrs.push(Attribute::property("data-width", w.to_string()));
2486    }
2487    if let Some(h) = height {
2488        attrs.push(Attribute::property("data-height", h.to_string()));
2489    }
2490    if let Some(d) = depth {
2491        attrs.push(Attribute::property("data-depth", d.to_string()));
2492    }
2493    View::new(NodeBlueprint::element(
2494        Tag::Custom("BoxGeometry"),
2495        strata_dom::ClassList::default(),
2496        attrs,
2497        Vec::new(),
2498    ))
2499}
2500
2501#[component]
2502pub fn SphereGeometry(
2503    radius: Option<f32>,
2504    width_segments: Option<u32>,
2505    height_segments: Option<u32>,
2506) -> View {
2507    let mut attrs = Vec::new();
2508    if let Some(r) = radius {
2509        attrs.push(Attribute::property("data-radius", r.to_string()));
2510    }
2511    if let Some(w) = width_segments {
2512        attrs.push(Attribute::property("data-width-segments", w.to_string()));
2513    }
2514    if let Some(h) = height_segments {
2515        attrs.push(Attribute::property("data-height-segments", h.to_string()));
2516    }
2517    View::new(NodeBlueprint::element(
2518        Tag::Custom("SphereGeometry"),
2519        strata_dom::ClassList::default(),
2520        attrs,
2521        Vec::new(),
2522    ))
2523}
2524
2525#[component]
2526pub fn PlaneGeometry(width: Option<f32>, height: Option<f32>) -> View {
2527    let mut attrs = Vec::new();
2528    if let Some(w) = width {
2529        attrs.push(Attribute::property("data-width", w.to_string()));
2530    }
2531    if let Some(h) = height {
2532        attrs.push(Attribute::property("data-height", h.to_string()));
2533    }
2534    View::new(NodeBlueprint::element(
2535        Tag::Custom("PlaneGeometry"),
2536        strata_dom::ClassList::default(),
2537        attrs,
2538        Vec::new(),
2539    ))
2540}
2541
2542#[component]
2543pub fn CylinderGeometry(
2544    radius_top: Option<f32>,
2545    radius_bottom: Option<f32>,
2546    height: Option<f32>,
2547    radial_segments: Option<u32>,
2548) -> View {
2549    let mut attrs = Vec::new();
2550    if let Some(rt) = radius_top {
2551        attrs.push(Attribute::property("data-radius-top", rt.to_string()));
2552    }
2553    if let Some(rb) = radius_bottom {
2554        attrs.push(Attribute::property("data-radius-bottom", rb.to_string()));
2555    }
2556    if let Some(h) = height {
2557        attrs.push(Attribute::property("data-height", h.to_string()));
2558    }
2559    if let Some(rs) = radial_segments {
2560        attrs.push(Attribute::property("data-radial-segments", rs.to_string()));
2561    }
2562    View::new(NodeBlueprint::element(
2563        Tag::Custom("CylinderGeometry"),
2564        strata_dom::ClassList::default(),
2565        attrs,
2566        Vec::new(),
2567    ))
2568}
2569
2570#[component]
2571pub fn StandardMaterial(
2572    color: Option<&'static str>,
2573    roughness: Option<f32>,
2574    metalness: Option<f32>,
2575) -> View {
2576    let mut attrs = Vec::new();
2577    if let Some(c) = color {
2578        attrs.push(Attribute::property("data-color", c));
2579    }
2580    if let Some(r) = roughness {
2581        attrs.push(Attribute::property("data-roughness", r.to_string()));
2582    }
2583    if let Some(m) = metalness {
2584        attrs.push(Attribute::property("data-metalness", m.to_string()));
2585    }
2586    View::new(NodeBlueprint::element(
2587        Tag::Custom("StandardMaterial"),
2588        strata_dom::ClassList::default(),
2589        attrs,
2590        Vec::new(),
2591    ))
2592}
2593
2594#[component]
2595pub fn ShaderMaterial(
2596    glsl_fragment: Option<&'static str>,
2597    uniform_time: Option<f32>,
2598    uniforms: Option<strata_js::JsValue>,
2599) -> View {
2600    let mut attrs = Vec::new();
2601    if let Some(g) = glsl_fragment {
2602        attrs.push(Attribute::property("data-glsl", g));
2603    }
2604    if let Some(t) = uniform_time {
2605        attrs.push(Attribute::property("data-time", t.to_string()));
2606    }
2607    View::new(NodeBlueprint::element(
2608        Tag::Custom("ShaderMaterial"),
2609        strata_dom::ClassList::default(),
2610        attrs,
2611        Vec::new(),
2612    ))
2613}
2614
2615fn get_3d_attr<'a>(attrs: &'a [strata_dom::Attribute], key: &str) -> Option<&'a str> {
2616    attrs.iter().find_map(|attr| {
2617        if let strata_dom::Attribute::Property { key: k, value: v } = attr {
2618            if k == key {
2619                return Some(v.as_str());
2620            }
2621        }
2622        None
2623    })
2624}
2625
2626fn parse_3d_vec3(s: &str) -> Option<[f32; 3]> {
2627    let mut parts = s.split(',');
2628    let x = parts.next()?.trim().parse::<f32>().ok()?;
2629    let y = parts.next()?.trim().parse::<f32>().ok()?;
2630    let z = parts.next()?.trim().parse::<f32>().ok()?;
2631    Some([x, y, z])
2632}
2633
2634/// Extracts an `Arc<Scene3D>` from a `<Canvas3D>` or viewport [`NodeBlueprint`]:
2635/// returns a zero-copy `Arc::clone` when an explicit `Attribute::ScenePayload` is attached
2636/// with no declarative child overrides, or compiles declarative children when present.
2637pub fn extract_scene3d_arc_from_blueprint(
2638    canvas_node: &NodeBlueprint,
2639) -> Option<std::sync::Arc<Scene3D>> {
2640    let NodeBlueprint::Element {
2641        attributes,
2642        children,
2643        ..
2644    } = canvas_node
2645    else {
2646        return None;
2647    };
2648
2649    let mut payload_scene: Option<std::sync::Arc<Scene3D>> = None;
2650    for attr in attributes {
2651        if let strata_dom::Attribute::ScenePayload(any) = attr {
2652            if let Ok(arc_scene) = any.clone().downcast::<Scene3D>() {
2653                payload_scene = Some(arc_scene);
2654                break;
2655            }
2656            if let Some(nested_arc) = any.downcast_ref::<std::sync::Arc<Scene3D>>() {
2657                payload_scene = Some(std::sync::Arc::clone(nested_arc));
2658                break;
2659            }
2660        }
2661    }
2662
2663    if let Some(arc_scene) = payload_scene {
2664        if children.is_empty() {
2665            return Some(arc_scene);
2666        }
2667        return Some(std::sync::Arc::new(compile_scene3d_from_blueprint(
2668            canvas_node,
2669        )));
2670    }
2671
2672    Some(std::sync::Arc::new(compile_scene3d_from_blueprint(
2673        canvas_node,
2674    )))
2675}
2676
2677/// Compiles a `<Canvas3D>` blueprint subtree (including any attached programmatic `ScenePayload`)
2678/// into a populated [`Scene3D`] instance.
2679pub fn compile_scene3d_from_blueprint(canvas_node: &NodeBlueprint) -> Scene3D {
2680    let (attributes, children) = match canvas_node {
2681        NodeBlueprint::Element {
2682            attributes,
2683            children,
2684            ..
2685        } => (attributes, children),
2686        _ => return Scene3D::new(),
2687    };
2688
2689    let mut scene = attributes
2690        .iter()
2691        .find_map(|attr| match attr {
2692            strata_dom::Attribute::ScenePayload(any) => {
2693                any.downcast_ref::<Scene3D>().cloned().or_else(|| {
2694                    any.downcast_ref::<std::sync::Arc<Scene3D>>()
2695                        .map(|a| (**a).clone())
2696                })
2697            }
2698            _ => None,
2699        })
2700        .unwrap_or_default();
2701
2702    for child in children {
2703        if let NodeBlueprint::Element {
2704            tag,
2705            attributes,
2706            children: mesh_children,
2707            ..
2708        } = child
2709        {
2710            match tag {
2711                Tag::Custom("PerspectiveCamera") => {
2712                    let fov = get_3d_attr(attributes, "data-fov")
2713                        .and_then(|v| v.parse().ok())
2714                        .unwrap_or(60.0);
2715                    let near = get_3d_attr(attributes, "data-near")
2716                        .and_then(|v| v.parse().ok())
2717                        .unwrap_or(0.1);
2718                    let far = get_3d_attr(attributes, "data-far")
2719                        .and_then(|v| v.parse().ok())
2720                        .unwrap_or(1000.0);
2721                    let position = get_3d_attr(attributes, "data-position")
2722                        .and_then(parse_3d_vec3)
2723                        .unwrap_or([0.0, 2.0, 5.0]);
2724                    let target = get_3d_attr(attributes, "data-target")
2725                        .and_then(parse_3d_vec3)
2726                        .unwrap_or([0.0, 0.0, 0.0]);
2727                    scene.camera = Camera3D::Perspective {
2728                        fov_horizontal_deg: fov,
2729                        near,
2730                        far,
2731                        position,
2732                        target,
2733                    };
2734                }
2735                Tag::Custom("OrthographicCamera") => {
2736                    let left = get_3d_attr(attributes, "data-left")
2737                        .and_then(|v| v.parse().ok())
2738                        .unwrap_or(-5.0);
2739                    let right = get_3d_attr(attributes, "data-right")
2740                        .and_then(|v| v.parse().ok())
2741                        .unwrap_or(5.0);
2742                    let top = get_3d_attr(attributes, "data-top")
2743                        .and_then(|v| v.parse().ok())
2744                        .unwrap_or(5.0);
2745                    let bottom = get_3d_attr(attributes, "data-bottom")
2746                        .and_then(|v| v.parse().ok())
2747                        .unwrap_or(-5.0);
2748                    let near = get_3d_attr(attributes, "data-near")
2749                        .and_then(|v| v.parse().ok())
2750                        .unwrap_or(0.1);
2751                    let far = get_3d_attr(attributes, "data-far")
2752                        .and_then(|v| v.parse().ok())
2753                        .unwrap_or(1000.0);
2754                    let position = get_3d_attr(attributes, "data-position")
2755                        .and_then(parse_3d_vec3)
2756                        .unwrap_or([0.0, 2.0, 5.0]);
2757                    let target = get_3d_attr(attributes, "data-target")
2758                        .and_then(parse_3d_vec3)
2759                        .unwrap_or([0.0, 0.0, 0.0]);
2760                    scene.camera = Camera3D::Orthographic {
2761                        left,
2762                        right,
2763                        top,
2764                        bottom,
2765                        near,
2766                        far,
2767                        position,
2768                        target,
2769                    };
2770                }
2771                Tag::Custom("AmbientLight") => {
2772                    let color_str = get_3d_attr(attributes, "data-color").unwrap_or("#ffffff");
2773                    let color = strata_style::parse_color(color_str).unwrap_or(Color::WHITE);
2774                    let intensity = get_3d_attr(attributes, "data-intensity")
2775                        .and_then(|v| v.parse().ok())
2776                        .unwrap_or(1.0);
2777                    scene.add_light(Light3D::Ambient { color, intensity });
2778                }
2779                Tag::Custom("DirectionalLight") => {
2780                    let pos = get_3d_attr(attributes, "data-position")
2781                        .and_then(parse_3d_vec3)
2782                        .unwrap_or([5.0, 10.0, 7.0]);
2783                    let color_str = get_3d_attr(attributes, "data-color").unwrap_or("#ffffff");
2784                    let color = strata_style::parse_color(color_str).unwrap_or(Color::WHITE);
2785                    let intensity = get_3d_attr(attributes, "data-intensity")
2786                        .and_then(|v| v.parse().ok())
2787                        .unwrap_or(1.0);
2788                    let cast_shadow = get_3d_attr(attributes, "data-cast-shadow")
2789                        .and_then(|v| v.parse().ok())
2790                        .unwrap_or(false);
2791                    scene.add_light(Light3D::Directional {
2792                        position: pos,
2793                        color,
2794                        intensity,
2795                        cast_shadow,
2796                    });
2797                }
2798                Tag::Custom("PointLight") => {
2799                    let pos = get_3d_attr(attributes, "data-position")
2800                        .and_then(parse_3d_vec3)
2801                        .unwrap_or([0.0, 2.0, 0.0]);
2802                    let color_str = get_3d_attr(attributes, "data-color").unwrap_or("#ffffff");
2803                    let color = strata_style::parse_color(color_str).unwrap_or(Color::WHITE);
2804                    let intensity = get_3d_attr(attributes, "data-intensity")
2805                        .and_then(|v| v.parse().ok())
2806                        .unwrap_or(1.0);
2807                    let distance = get_3d_attr(attributes, "data-distance")
2808                        .and_then(|v| v.parse().ok())
2809                        .unwrap_or(10.0);
2810                    scene.add_light(Light3D::Point {
2811                        position: pos,
2812                        color,
2813                        intensity,
2814                        distance,
2815                    });
2816                }
2817                Tag::Custom("Mesh") => {
2818                    let position = get_3d_attr(attributes, "data-position")
2819                        .and_then(parse_3d_vec3)
2820                        .unwrap_or([0.0, 0.0, 0.0]);
2821                    let rotation = get_3d_attr(attributes, "data-rotation")
2822                        .and_then(parse_3d_vec3)
2823                        .unwrap_or([0.0, 0.0, 0.0]);
2824                    let scale = get_3d_attr(attributes, "data-scale")
2825                        .and_then(parse_3d_vec3)
2826                        .unwrap_or([1.0, 1.0, 1.0]);
2827                    let transform = Transform3D {
2828                        position,
2829                        rotation,
2830                        scale,
2831                    };
2832
2833                    let mut geometry = Geometry3D::Box {
2834                        width: 1.0,
2835                        height: 1.0,
2836                        depth: 1.0,
2837                    };
2838                    let mut material = Material3D::default();
2839
2840                    for sub in mesh_children {
2841                        if let NodeBlueprint::Element {
2842                            tag: sub_tag,
2843                            attributes: sub_attrs,
2844                            ..
2845                        } = sub
2846                        {
2847                            match sub_tag {
2848                                Tag::Custom("BoxGeometry") => {
2849                                    let width = get_3d_attr(sub_attrs, "data-width")
2850                                        .and_then(|v| v.parse().ok())
2851                                        .unwrap_or(1.0);
2852                                    let height = get_3d_attr(sub_attrs, "data-height")
2853                                        .and_then(|v| v.parse().ok())
2854                                        .unwrap_or(1.0);
2855                                    let depth = get_3d_attr(sub_attrs, "data-depth")
2856                                        .and_then(|v| v.parse().ok())
2857                                        .unwrap_or(1.0);
2858                                    geometry = Geometry3D::Box {
2859                                        width,
2860                                        height,
2861                                        depth,
2862                                    };
2863                                }
2864                                Tag::Custom("SphereGeometry") => {
2865                                    let radius = get_3d_attr(sub_attrs, "data-radius")
2866                                        .and_then(|v| v.parse().ok())
2867                                        .unwrap_or(1.0);
2868                                    let width_segments =
2869                                        get_3d_attr(sub_attrs, "data-width-segments")
2870                                            .and_then(|v| v.parse().ok())
2871                                            .unwrap_or(16);
2872                                    let height_segments =
2873                                        get_3d_attr(sub_attrs, "data-height-segments")
2874                                            .and_then(|v| v.parse().ok())
2875                                            .unwrap_or(16);
2876                                    geometry = Geometry3D::Sphere {
2877                                        radius,
2878                                        width_segments,
2879                                        height_segments,
2880                                    };
2881                                }
2882                                Tag::Custom("PlaneGeometry") => {
2883                                    let width = get_3d_attr(sub_attrs, "data-width")
2884                                        .and_then(|v| v.parse().ok())
2885                                        .unwrap_or(1.0);
2886                                    let height = get_3d_attr(sub_attrs, "data-height")
2887                                        .and_then(|v| v.parse().ok())
2888                                        .unwrap_or(1.0);
2889                                    geometry = Geometry3D::Plane { width, height };
2890                                }
2891                                Tag::Custom("CylinderGeometry") => {
2892                                    let radius_top = get_3d_attr(sub_attrs, "data-radius-top")
2893                                        .and_then(|v| v.parse().ok())
2894                                        .unwrap_or(1.0);
2895                                    let radius_bottom =
2896                                        get_3d_attr(sub_attrs, "data-radius-bottom")
2897                                            .and_then(|v| v.parse().ok())
2898                                            .unwrap_or(1.0);
2899                                    let height = get_3d_attr(sub_attrs, "data-height")
2900                                        .and_then(|v| v.parse().ok())
2901                                        .unwrap_or(1.0);
2902                                    let radial_segments =
2903                                        get_3d_attr(sub_attrs, "data-radial-segments")
2904                                            .and_then(|v| v.parse().ok())
2905                                            .unwrap_or(16);
2906                                    geometry = Geometry3D::Cylinder {
2907                                        radius_top,
2908                                        radius_bottom,
2909                                        height,
2910                                        radial_segments,
2911                                    };
2912                                }
2913                                Tag::Custom("StandardMaterial") => {
2914                                    let color_str =
2915                                        get_3d_attr(sub_attrs, "data-color").unwrap_or("#ffffff");
2916                                    let color = strata_style::parse_color(color_str)
2917                                        .unwrap_or(Color::WHITE);
2918                                    let roughness = get_3d_attr(sub_attrs, "data-roughness")
2919                                        .and_then(|v| v.parse().ok())
2920                                        .unwrap_or(0.5);
2921                                    let metalness = get_3d_attr(sub_attrs, "data-metalness")
2922                                        .and_then(|v| v.parse().ok())
2923                                        .unwrap_or(0.0);
2924                                    material = Material3D::Standard {
2925                                        color,
2926                                        roughness,
2927                                        metalness,
2928                                        emissive: None,
2929                                    };
2930                                }
2931                                Tag::Custom("ShaderMaterial") => {
2932                                    let glsl =
2933                                        get_3d_attr(sub_attrs, "data-glsl").map(|s| s.to_string());
2934                                    let time = get_3d_attr(sub_attrs, "data-time")
2935                                        .and_then(|v| v.parse().ok())
2936                                        .unwrap_or(0.0);
2937                                    let mut uniforms = BTreeMap::new();
2938                                    uniforms.insert("u_time".to_string(), time);
2939                                    material = Material3D::Shader {
2940                                        vertex_shader: None,
2941                                        fragment_shader: None,
2942                                        glsl_fragment: glsl,
2943                                        uniforms,
2944                                    };
2945                                }
2946                                _ => {}
2947                            }
2948                        }
2949                    }
2950
2951                    scene.add_mesh(Mesh3D {
2952                        geometry,
2953                        material,
2954                        transform,
2955                    });
2956                }
2957                _ => {}
2958            }
2959        }
2960    }
2961
2962    scene
2963}