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    /// World-fixed conformal Mercator metres `[wx_m, wy_m]` at `origin_ecef` so wave phases &
710    /// procedural noise stay 100% deterministic across camera pan, zoom, and origin snapping.
711    pub world_origin_merc_m: [f64; 2],
712    /// Origin latitude in radians (`0.0` when unset / flat local test plane).
713    pub origin_lat_rad: f32,
714    /// East metric cosine scale in 2.5D tangent mode (`1.0` when unset / equatorial).
715    pub east_scale: f32,
716}
717
718impl Default for RetainedOceanSurface {
719    fn default() -> Self {
720        Self {
721            enabled: false,
722            origin_ecef: [0.0; 3],
723            basis_east: [1.0, 0.0, 0.0],
724            basis_north: [0.0, 1.0, 0.0],
725            basis_up: [0.0, 0.0, 1.0],
726            train_a: RetainedOceanWaveTrain::default(),
727            train_b: RetainedOceanWaveTrain {
728                weight: 0.0,
729                ..RetainedOceanWaveTrain::default()
730            },
731            wave_strength: 1.0,
732            wave_scale: 1.0,
733            glint_intensity: 1.0,
734            opacity: 0.82,
735            alt_fade: 1.0,
736            coastal_shoaling: false,
737            shoaling_range_m: 360.0,
738            sdf_half_span_m: 1_500.0,
739            sdf_center_en_m: [0.0, 0.0],
740            coastal_sdf: None,
741            world_origin_merc_m: [0.0, 0.0],
742            origin_lat_rad: 0.0,
743            east_scale: 1.0,
744        }
745    }
746}
747
748/// One real catalog star in J2000 ICRF celestial coordinates.
749#[derive(Debug, Clone, Copy, PartialEq)]
750pub struct RetainedStar {
751    /// Unit direction vector in J2000 ICRF equatorial coordinates.
752    pub icrf_dir: [f32; 3],
753    /// Apparent visual magnitude (Vmag; lower = brighter).
754    pub vmag: f32,
755    /// Linear sRGB Planck blackbody color `(r, g, b)` + `1.0` alpha.
756    pub color: [f32; 4],
757}
758
759/// 6-face RGBA8 cubemap texture uploadable to `wgpu` (`TextureViewDimension::Cube`).
760#[derive(Debug, Clone, PartialEq)]
761pub struct RetainedCubemapTexture {
762    pub id: u64,
763    pub revision: u64,
764    /// Width and height of each square cubemap face in texels.
765    pub face_size: u32,
766    /// 6 faces in WebGPU/Vulkan array-layer order: `[+X, -X, +Y, -Y, +Z, -Z]`.
767    pub faces_rgba8: [std::sync::Arc<Vec<u8>>; 6],
768}
769
770/// Persistent GPU-uploadable planetary & space environment assets (land mask, cloud map, Moon, star catalog, space skybox).
771#[derive(Debug, Clone, Default, PartialEq)]
772pub struct RetainedEnvironmentAssets {
773    pub revision: u64,
774    /// Equirectangular land mask (land=255, ocean=0 in red/alpha channels) for deterministic land-only city lights.
775    pub land_mask: Option<std::sync::Arc<RetainedTileTexture>>,
776    /// Global 3D equirectangular cloud map texture (alpha or luminance channel).
777    pub cloud_map: Option<std::sync::Arc<RetainedTileTexture>>,
778    /// Equirectangular Moon surface albedo texture (NASA LRO).
779    pub moon_texture: Option<std::sync::Arc<RetainedTileTexture>>,
780    /// Real bright star catalog (e.g. Yale BSC5 in J2000 ICRF).
781    pub stars: Option<std::sync::Arc<Vec<RetainedStar>>>,
782    /// J2000 ICRF telescope space skybox cubemap (`[+X, -X, +Y, -Y, +Z, -Z]`).
783    pub skybox_cubemap: Option<std::sync::Arc<RetainedCubemapTexture>>,
784}
785
786/// Camera and lighting uniforms needed for O(1) RTE GPU frame presentation without scene rebuilds.
787#[derive(Debug, Clone, Copy, PartialEq)]
788pub struct RetainedCameraUniforms {
789    /// Column-major projection matrix.
790    pub proj: [[f32; 4]; 4],
791    /// Column-major camera rotation matrix with camera positioned at world origin `[0, 0, 0]`.
792    pub view_rot: [[f32; 4]; 4],
793    /// Pre-multiplied column-major `proj * view_rot` matrix.
794    pub view_proj_rte: [[f32; 4]; 4],
795    /// High-precision eye position in world / ECEF coordinates.
796    pub eye_ecef: [f64; 3],
797    /// World-space directional sun direction (pointing from surface toward light).
798    pub sun_dir: [f32; 3],
799    pub sun_color: [f32; 3],
800    pub ambient_color: [f32; 3],
801    pub background: Background3D,
802    pub near: f32,
803    pub far: f32,
804    /// Column-major J2000 ICRF -> ECEF rotation matrix (GMST sidereal rotation).
805    pub ecef_from_icrf: [[f32; 4]; 4],
806    /// Normalized ECEF direction toward the Moon.
807    pub moon_dir: [f32; 3],
808    /// Physical day/night terminator strength (`0.0` = flat daylight, `1.0` = full terminator, fades to 0 in 2.5D).
809    pub day_night_strength: f32,
810    /// Deterministic land-masked night city-lights intensity (`0.0` = off, auto-fades out in 2.5D).
811    pub city_lights_intensity: f32,
812    /// Seamless 3D -> 2.5D ground morph factor (`0.0` = 3D space globe, `1.0` = 2.5D local ground).
813    pub local_25d_blend: f32,
814    /// Render physical limb-darkened Sun disc & corona (`true` by default).
815    pub sun_visible: bool,
816    /// Visual Sun angular radius in radians (default ~`0.018` rad).
817    pub sun_angular_radius_rad: f32,
818    /// Render NASA textured Moon with real orbital lunar phase (`true` by default).
819    pub moon_visible: bool,
820    /// Visual Moon angular radius in radians (default ~`0.022` rad).
821    pub moon_angular_radius_rad: f32,
822    /// Render scientific deep-space starfield skybox (`true` by default).
823    pub stars_visible: bool,
824    /// Brightness multiplier for starfield & Milky Way band.
825    pub stars_intensity: f32,
826    /// Brightness multiplier for real telescope skybox cubemap (`1.0` default).
827    pub skybox_intensity: f32,
828    /// Opacity of global 3D cloud-map shell (`0.0` = off; auto-fades out in 2.5D).
829    pub cloud_layer_opacity: f32,
830    /// Opacity of local cropped satellite overhead cloud canopy in low-altitude / 2.5D view.
831    pub local_cloud_opacity: f32,
832    /// Global cloud-map longitudinal scroll offset in radians.
833    pub cloud_lon_offset_rad: f32,
834    /// Simulation / animation time in seconds.
835    pub time_s: f32,
836    /// Opt-in physical Rayleigh/Mie 2.5D sky scattering weight (`0.0` = classic flat blue 2.5D sky, `1.0` = full physical sky).
837    pub realistic_25d_sky: f32,
838    /// Opt-in 2.5D night-sky star & Milky Way visibility sync (`0.0` = off, `1.0` = stars appear at night above horizon).
839    pub night_stars_25d: f32,
840    /// Opt-in physical 2.5D directional sun & DEM relief hillshading weight (`0.0` = flat 2.5D terrain, `1.0` = lit).
841    pub terrain_25d_lighting: f32,
842    /// Opt-in hardware directional shadow-map pass & 9-tap PCF mountain/object shadow strength (`0.0` = disabled).
843    pub terrain_25d_shadows: f32,
844    /// Directional shadow map resolution in pixels (`2048` default; lazily allocated only when shadows > 0).
845    pub shadow_map_size: u32,
846    /// Unified weather optical storm/overcast darkness (`0.0` = clear sky, `1.0` = brooding storm overcast).
847    pub weather_darkness: f32,
848    /// Unified weather cloud cover fraction (`0.0..=1.0`, attenuating sun glare & night stars).
849    pub weather_cloud_cover: f32,
850    /// Unified weather / precipitation atmospheric visibility haze (`0.0..=1.0`).
851    pub weather_haze: f32,
852    /// Weather-modulated cloud RGB tint multiplier (`[1.0, 1.0, 1.0]` neutral).
853    pub cloud_tint_rgb: [f32; 3],
854    /// Weather-driven overhead 2.5D cloud coverage boost (`0.0..=1.0`).
855    pub cloud_25d_cover_boost: f32,
856    /// Flat 2D map morph factor (`0.0` = 3D/2.5D perspective scene, `1.0` = flat 2D map imagery).
857    pub map_2d_morph: f32,
858}
859
860impl Default for RetainedCameraUniforms {
861    fn default() -> Self {
862        let ident = [
863            [1.0, 0.0, 0.0, 0.0],
864            [0.0, 1.0, 0.0, 0.0],
865            [0.0, 0.0, 1.0, 0.0],
866            [0.0, 0.0, 0.0, 1.0],
867        ];
868        Self {
869            proj: ident,
870            view_rot: ident,
871            view_proj_rte: ident,
872            eye_ecef: [0.0, 0.0, 5.0],
873            sun_dir: [0.577_350_26, 0.577_350_26, 0.577_350_26],
874            sun_color: [1.0, 0.98, 0.95],
875            ambient_color: [0.22, 0.24, 0.28],
876            background: Background3D::Transparent,
877            near: 0.1,
878            far: 100_000_000.0,
879            ecef_from_icrf: ident,
880            moon_dir: [-0.577_350_26, 0.577_350_26, 0.577_350_26],
881            day_night_strength: 1.0,
882            city_lights_intensity: 0.0,
883            local_25d_blend: 0.0,
884            sun_visible: false,
885            sun_angular_radius_rad: 0.018,
886            moon_visible: false,
887            moon_angular_radius_rad: 0.022,
888            stars_visible: false,
889            stars_intensity: 1.0,
890            skybox_intensity: 1.0,
891            cloud_layer_opacity: 0.0,
892            local_cloud_opacity: 0.0,
893            cloud_lon_offset_rad: 0.0,
894            time_s: 0.0,
895            realistic_25d_sky: 0.0,
896            night_stars_25d: 0.0,
897            terrain_25d_lighting: 0.0,
898            terrain_25d_shadows: 0.0,
899            shadow_map_size: 2048,
900            weather_darkness: 0.0,
901            weather_cloud_cover: 0.0,
902            weather_haze: 0.0,
903            cloud_tint_rgb: [1.0, 1.0, 1.0],
904            cloud_25d_cover_boost: 0.0,
905            map_2d_morph: 0.0,
906        }
907    }
908}
909
910/// Snapshot of retained terrain tiles, textures, dynamic meshes, instanced geo objects,
911/// GPU-instanced 2D camera-local particle volumes, GPU ocean surface, and camera parameters.
912#[derive(Debug, Clone, Default, PartialEq)]
913pub struct RetainedTerrainFrame {
914    pub camera: RetainedCameraUniforms,
915    pub geometry_revision: u64,
916    /// Monotonic revision of `geo_mesh_assets` / `geo_instances`, used to prevent stale background
917    /// tile worker snapshots from overwriting newer main-thread `EarthWorld` updates.
918    pub geo_revision: u64,
919    pub meshes: Vec<std::sync::Arc<RetainedTileMesh>>,
920    pub instances: Vec<RetainedTileInstance>,
921    pub textures: Vec<std::sync::Arc<RetainedTileTexture>>,
922    pub dynamic_meshes: Vec<RetainedDynamicMesh>,
923    pub geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
924    pub geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
925    pub particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
926    pub particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
927    pub ocean: Option<std::sync::Arc<RetainedOceanSurface>>,
928    pub environment: Option<std::sync::Arc<RetainedEnvironmentAssets>>,
929}
930
931#[derive(Debug)]
932struct RetainedSceneState {
933    camera: RetainedCameraUniforms,
934    terrain: Option<std::sync::Arc<RetainedTerrainFrame>>,
935    fallback_scene: Option<std::sync::Arc<Scene3D>>,
936}
937
938#[derive(Debug)]
939struct RetainedScene3DInner {
940    camera_generation: std::sync::atomic::AtomicU64,
941    geometry_generation: std::sync::atomic::AtomicU64,
942    overlay_generation: std::sync::atomic::AtomicU64,
943    geo_revision: std::sync::atomic::AtomicU64,
944    state: std::sync::RwLock<RetainedSceneState>,
945}
946
947/// Thread-safe retained 3D scene handle shared between host state (camera/worker) and `Canvas3D`.
948///
949/// Calling [`RetainedScene3D::update_camera`] updates camera uniforms in place and bumps only
950/// `camera_generation`, allowing the GPU backend to re-render at uncapped framerates without
951/// rebuilding DOM nodes, layout, display lists, or tile meshes.
952#[derive(Clone)]
953pub struct RetainedScene3D {
954    inner: std::sync::Arc<RetainedScene3DInner>,
955}
956
957impl std::fmt::Debug for RetainedScene3D {
958    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
959        let (cam, geom, overlay) = self.generations();
960        f.debug_struct("RetainedScene3D")
961            .field("camera_generation", &cam)
962            .field("geometry_generation", &geom)
963            .field("overlay_generation", &overlay)
964            .finish()
965    }
966}
967
968impl PartialEq for RetainedScene3D {
969    fn eq(&self, other: &Self) -> bool {
970        if std::sync::Arc::ptr_eq(&self.inner, &other.inner) {
971            return true;
972        }
973        let Ok(a) = self.inner.state.read() else {
974            return false;
975        };
976        let Ok(b) = other.inner.state.read() else {
977            return false;
978        };
979        a.camera == b.camera && a.terrain == b.terrain && a.fallback_scene == b.fallback_scene
980    }
981}
982
983impl RetainedScene3D {
984    pub fn new(camera: RetainedCameraUniforms) -> Self {
985        Self {
986            inner: std::sync::Arc::new(RetainedScene3DInner {
987                camera_generation: std::sync::atomic::AtomicU64::new(1),
988                geometry_generation: std::sync::atomic::AtomicU64::new(0),
989                overlay_generation: std::sync::atomic::AtomicU64::new(0),
990                geo_revision: std::sync::atomic::AtomicU64::new(0),
991                state: std::sync::RwLock::new(RetainedSceneState {
992                    camera,
993                    terrain: None,
994                    fallback_scene: None,
995                }),
996            }),
997        }
998    }
999
1000    /// Monotonic revision of the latest published `geo_mesh_assets` / `geo_instances`.
1001    #[inline]
1002    pub fn geo_revision(&self) -> u64 {
1003        self.inner
1004            .geo_revision
1005            .load(std::sync::atomic::Ordering::Acquire)
1006    }
1007
1008    pub fn update_camera(&self, camera: RetainedCameraUniforms) {
1009        if let Ok(mut guard) = self.inner.state.write() {
1010            guard.camera = camera;
1011        }
1012        self.inner
1013            .camera_generation
1014            .fetch_add(1, std::sync::atomic::Ordering::Release);
1015    }
1016
1017    pub fn update_terrain(&self, terrain: std::sync::Arc<RetainedTerrainFrame>) {
1018        if let Ok(mut guard) = self.inner.state.write() {
1019            guard.camera = terrain.camera;
1020            let rev = terrain.geo_revision;
1021            guard.terrain = Some(terrain);
1022            self.inner
1023                .geo_revision
1024                .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1025        }
1026        self.inner
1027            .geometry_generation
1028            .fetch_add(1, std::sync::atomic::Ordering::Release);
1029        self.inner
1030            .camera_generation
1031            .fetch_add(1, std::sync::atomic::Ordering::Release);
1032    }
1033
1034    /// Publishes a new terrain tile frame from a background LOD worker while preserving the live camera,
1035    /// any main-thread camera-locked particle layers or GPU ocean state when omitted, and any newer
1036    /// main-thread `geo_mesh_assets`/`geo_instances` (preventing 1-frame rubber-banding).
1037    pub fn update_terrain_preserving_camera(&self, terrain: std::sync::Arc<RetainedTerrainFrame>) {
1038        if let Ok(mut guard) = self.inner.state.write() {
1039            if let Some(ref existing) = guard.terrain {
1040                let keep_particles =
1041                    terrain.particle_layers.is_empty() && !existing.particle_layers.is_empty();
1042                let keep_ocean = terrain.ocean.is_none() && existing.ocean.is_some();
1043                let keep_geo =
1044                    existing.geo_revision > 0 && terrain.geo_revision < existing.geo_revision;
1045                if keep_particles || keep_ocean || keep_geo {
1046                    let mut merged = (*terrain).clone();
1047                    if keep_particles {
1048                        merged.particle_layers = existing.particle_layers.clone();
1049                        merged.particle_textures = existing.particle_textures.clone();
1050                    }
1051                    if keep_ocean {
1052                        merged.ocean = existing.ocean.clone();
1053                    }
1054                    if keep_geo {
1055                        merged.geo_revision = existing.geo_revision;
1056                        merged.geo_mesh_assets = existing.geo_mesh_assets.clone();
1057                        merged.geo_instances = existing.geo_instances.clone();
1058                    }
1059                    let rev = merged.geo_revision;
1060                    guard.terrain = Some(std::sync::Arc::new(merged));
1061                    self.inner
1062                        .geo_revision
1063                        .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1064                } else {
1065                    let rev = terrain.geo_revision;
1066                    guard.terrain = Some(terrain);
1067                    self.inner
1068                        .geo_revision
1069                        .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1070                }
1071            } else {
1072                let rev = terrain.geo_revision;
1073                guard.terrain = Some(terrain);
1074                self.inner
1075                    .geo_revision
1076                    .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1077            }
1078        }
1079        self.inner
1080            .geometry_generation
1081            .fetch_add(1, std::sync::atomic::Ordering::Release);
1082    }
1083
1084    /// Atomically publishes a new terrain tile frame together with its matching camera uniforms
1085    /// while preserving main-thread camera-locked particle layers, GPU ocean state, and newer
1086    /// main-thread `geo_mesh_assets`/`geo_instances` when omitted or stale.
1087    ///
1088    /// Used on the single boundary frame switching between spherical/tangent 3D and the canonical
1089    /// 2D flat-map plane so terrain geometry and camera never mismatch even transiently.
1090    pub fn update_terrain_with_camera_preserving_overlays(
1091        &self,
1092        terrain: std::sync::Arc<RetainedTerrainFrame>,
1093    ) {
1094        if let Ok(mut guard) = self.inner.state.write() {
1095            guard.camera = terrain.camera;
1096            if let Some(ref existing) = guard.terrain {
1097                let keep_particles =
1098                    terrain.particle_layers.is_empty() && !existing.particle_layers.is_empty();
1099                let keep_ocean = terrain.ocean.is_none() && existing.ocean.is_some();
1100                let keep_geo =
1101                    existing.geo_revision > 0 && terrain.geo_revision < existing.geo_revision;
1102                if keep_particles || keep_ocean || keep_geo {
1103                    let mut merged = (*terrain).clone();
1104                    if keep_particles {
1105                        merged.particle_layers = existing.particle_layers.clone();
1106                        merged.particle_textures = existing.particle_textures.clone();
1107                    }
1108                    if keep_ocean {
1109                        merged.ocean = existing.ocean.clone();
1110                    }
1111                    if keep_geo {
1112                        merged.geo_revision = existing.geo_revision;
1113                        merged.geo_mesh_assets = existing.geo_mesh_assets.clone();
1114                        merged.geo_instances = existing.geo_instances.clone();
1115                    }
1116                    let rev = merged.geo_revision;
1117                    guard.terrain = Some(std::sync::Arc::new(merged));
1118                    self.inner
1119                        .geo_revision
1120                        .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1121                } else {
1122                    let rev = terrain.geo_revision;
1123                    guard.terrain = Some(terrain);
1124                    self.inner
1125                        .geo_revision
1126                        .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1127                }
1128            } else {
1129                let rev = terrain.geo_revision;
1130                guard.terrain = Some(terrain);
1131                self.inner
1132                    .geo_revision
1133                    .fetch_max(rev, std::sync::atomic::Ordering::AcqRel);
1134            }
1135        }
1136        self.inner
1137            .geometry_generation
1138            .fetch_add(1, std::sync::atomic::Ordering::Release);
1139        self.inner
1140            .camera_generation
1141            .fetch_add(1, std::sync::atomic::Ordering::Release);
1142    }
1143
1144    /// Marks the retained 3D scene dirty for one more frame when per-frame GPU texture/mesh upload budgets deferred remaining work.
1145    pub fn request_gpu_continuation(&self) {
1146        self.inner
1147            .camera_generation
1148            .fetch_add(1, std::sync::atomic::Ordering::Release);
1149    }
1150
1151    /// Updates camera uniforms and replaces only dynamic 3D overlays (e.g. orbital satellites)
1152    /// without rebuilding or re-allocating cached terrain tiles, textures, particle volumes, ocean, or environment assets.
1153    pub fn update_camera_and_dynamic_meshes(
1154        &self,
1155        camera: RetainedCameraUniforms,
1156        dynamic_meshes: Vec<RetainedDynamicMesh>,
1157    ) {
1158        if let Ok(mut guard) = self.inner.state.write() {
1159            guard.camera = camera;
1160            if let Some(ref existing) = guard.terrain {
1161                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1162                    camera,
1163                    geometry_revision: existing.geometry_revision,
1164                    geo_revision: existing.geo_revision,
1165                    meshes: existing.meshes.clone(),
1166                    instances: existing.instances.clone(),
1167                    textures: existing.textures.clone(),
1168                    dynamic_meshes,
1169                    geo_mesh_assets: existing.geo_mesh_assets.clone(),
1170                    geo_instances: existing.geo_instances.clone(),
1171                    particle_layers: existing.particle_layers.clone(),
1172                    particle_textures: existing.particle_textures.clone(),
1173                    ocean: existing.ocean.clone(),
1174                    environment: existing.environment.clone(),
1175                }));
1176            }
1177        }
1178        self.inner
1179            .camera_generation
1180            .fetch_add(1, std::sync::atomic::Ordering::Release);
1181    }
1182
1183    /// Updates hardware-instanced geodetic objects in O(1) TerrainFrame shallow-clone time without
1184    /// rebuilding terrain tiles, textures, particle volumes, ocean, or environment state.
1185    pub fn update_geo_objects(
1186        &self,
1187        geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1188        geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1189    ) {
1190        if let Ok(mut guard) = self.inner.state.write() {
1191            let camera = guard.camera;
1192            let next_geo_rev = self
1193                .inner
1194                .geo_revision
1195                .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1196                .wrapping_add(1)
1197                .max(1);
1198            if let Some(ref existing) = guard.terrain {
1199                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1200                    camera,
1201                    geometry_revision: existing.geometry_revision,
1202                    geo_revision: next_geo_rev,
1203                    meshes: existing.meshes.clone(),
1204                    instances: existing.instances.clone(),
1205                    textures: existing.textures.clone(),
1206                    dynamic_meshes: existing.dynamic_meshes.clone(),
1207                    geo_mesh_assets,
1208                    geo_instances,
1209                    particle_layers: existing.particle_layers.clone(),
1210                    particle_textures: existing.particle_textures.clone(),
1211                    ocean: existing.ocean.clone(),
1212                    environment: existing.environment.clone(),
1213                }));
1214            } else {
1215                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1216                    camera,
1217                    geometry_revision: 1,
1218                    geo_revision: next_geo_rev,
1219                    geo_mesh_assets,
1220                    geo_instances,
1221                    ..Default::default()
1222                }));
1223            }
1224        }
1225        self.inner
1226            .geometry_generation
1227            .fetch_add(1, std::sync::atomic::Ordering::Release);
1228        self.inner
1229            .camera_generation
1230            .fetch_add(1, std::sync::atomic::Ordering::Release);
1231    }
1232
1233    /// Updates camera uniforms, dynamic 3D overlays, and hardware-instanced geodetic objects atomically.
1234    pub fn update_camera_and_world_overlays(
1235        &self,
1236        camera: RetainedCameraUniforms,
1237        dynamic_meshes: Vec<RetainedDynamicMesh>,
1238        geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1239        geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1240    ) {
1241        if let Ok(mut guard) = self.inner.state.write() {
1242            guard.camera = camera;
1243            let next_geo_rev = self
1244                .inner
1245                .geo_revision
1246                .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1247                .wrapping_add(1)
1248                .max(1);
1249            if let Some(ref existing) = guard.terrain {
1250                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1251                    camera,
1252                    geometry_revision: existing.geometry_revision,
1253                    geo_revision: next_geo_rev,
1254                    meshes: existing.meshes.clone(),
1255                    instances: existing.instances.clone(),
1256                    textures: existing.textures.clone(),
1257                    dynamic_meshes,
1258                    geo_mesh_assets,
1259                    geo_instances,
1260                    particle_layers: existing.particle_layers.clone(),
1261                    particle_textures: existing.particle_textures.clone(),
1262                    ocean: existing.ocean.clone(),
1263                    environment: existing.environment.clone(),
1264                }));
1265            } else if !geo_instances.is_empty() || !dynamic_meshes.is_empty() {
1266                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1267                    camera,
1268                    geometry_revision: 1,
1269                    geo_revision: next_geo_rev,
1270                    dynamic_meshes,
1271                    geo_mesh_assets,
1272                    geo_instances,
1273                    ..Default::default()
1274                }));
1275            }
1276        }
1277        self.inner
1278            .camera_generation
1279            .fetch_add(1, std::sync::atomic::Ordering::Release);
1280    }
1281
1282    /// Updates camera uniforms and hardware-instanced geodetic objects atomically while preserving
1283    /// existing terrain meshes, textures, particle volumes, ocean, and dynamic 3D overlays.
1284    pub fn update_camera_and_geo_objects(
1285        &self,
1286        camera: RetainedCameraUniforms,
1287        geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1288        geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1289    ) {
1290        if let Ok(mut guard) = self.inner.state.write() {
1291            guard.camera = camera;
1292            let next_geo_rev = self
1293                .inner
1294                .geo_revision
1295                .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1296                .wrapping_add(1)
1297                .max(1);
1298            if let Some(ref existing) = guard.terrain {
1299                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1300                    camera,
1301                    geometry_revision: existing.geometry_revision,
1302                    geo_revision: next_geo_rev,
1303                    meshes: existing.meshes.clone(),
1304                    instances: existing.instances.clone(),
1305                    textures: existing.textures.clone(),
1306                    dynamic_meshes: existing.dynamic_meshes.clone(),
1307                    geo_mesh_assets,
1308                    geo_instances,
1309                    particle_layers: existing.particle_layers.clone(),
1310                    particle_textures: existing.particle_textures.clone(),
1311                    ocean: existing.ocean.clone(),
1312                    environment: existing.environment.clone(),
1313                }));
1314            } else if !geo_instances.is_empty() {
1315                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1316                    camera,
1317                    geometry_revision: 1,
1318                    geo_revision: next_geo_rev,
1319                    geo_mesh_assets,
1320                    geo_instances,
1321                    ..Default::default()
1322                }));
1323            }
1324        }
1325        self.inner
1326            .camera_generation
1327            .fetch_add(1, std::sync::atomic::Ordering::Release);
1328    }
1329
1330    /// Updates only GPU-instanced 2D camera-local particle volumes in O(1) without touching terrain,
1331    /// dynamic meshes, ocean, or geodetic objects.
1332    pub fn update_particles(
1333        &self,
1334        particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1335        particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1336    ) {
1337        if let Ok(mut guard) = self.inner.state.write() {
1338            let camera = guard.camera;
1339            if let Some(ref existing) = guard.terrain {
1340                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1341                    camera,
1342                    geometry_revision: existing.geometry_revision,
1343                    geo_revision: existing.geo_revision,
1344                    meshes: existing.meshes.clone(),
1345                    instances: existing.instances.clone(),
1346                    textures: existing.textures.clone(),
1347                    dynamic_meshes: existing.dynamic_meshes.clone(),
1348                    geo_mesh_assets: existing.geo_mesh_assets.clone(),
1349                    geo_instances: existing.geo_instances.clone(),
1350                    particle_layers,
1351                    particle_textures,
1352                    ocean: existing.ocean.clone(),
1353                    environment: existing.environment.clone(),
1354                }));
1355            } else if !particle_layers.is_empty() {
1356                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1357                    camera,
1358                    geometry_revision: 1,
1359                    particle_layers,
1360                    particle_textures,
1361                    ..Default::default()
1362                }));
1363            }
1364        }
1365        self.inner
1366            .camera_generation
1367            .fetch_add(1, std::sync::atomic::Ordering::Release);
1368    }
1369
1370    /// Updates camera uniforms and GPU-instanced 2D camera-local particle volumes atomically in O(1).
1371    pub fn update_camera_and_particles(
1372        &self,
1373        camera: RetainedCameraUniforms,
1374        particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1375        particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1376    ) {
1377        if let Ok(mut guard) = self.inner.state.write() {
1378            guard.camera = camera;
1379            if let Some(ref existing) = guard.terrain {
1380                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1381                    camera,
1382                    geometry_revision: existing.geometry_revision,
1383                    geo_revision: existing.geo_revision,
1384                    meshes: existing.meshes.clone(),
1385                    instances: existing.instances.clone(),
1386                    textures: existing.textures.clone(),
1387                    dynamic_meshes: existing.dynamic_meshes.clone(),
1388                    geo_mesh_assets: existing.geo_mesh_assets.clone(),
1389                    geo_instances: existing.geo_instances.clone(),
1390                    particle_layers,
1391                    particle_textures,
1392                    ocean: existing.ocean.clone(),
1393                    environment: existing.environment.clone(),
1394                }));
1395            } else if !particle_layers.is_empty() {
1396                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1397                    camera,
1398                    geometry_revision: 1,
1399                    particle_layers,
1400                    particle_textures,
1401                    ..Default::default()
1402                }));
1403            }
1404        }
1405        self.inner
1406            .camera_generation
1407            .fetch_add(1, std::sync::atomic::Ordering::Release);
1408    }
1409
1410    /// Updates camera uniforms and GPU ocean surface descriptor atomically in O(1).
1411    pub fn update_camera_and_ocean(
1412        &self,
1413        camera: RetainedCameraUniforms,
1414        ocean: Option<std::sync::Arc<RetainedOceanSurface>>,
1415    ) {
1416        if let Ok(mut guard) = self.inner.state.write() {
1417            guard.camera = camera;
1418            if let Some(ref existing) = guard.terrain {
1419                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1420                    camera,
1421                    geometry_revision: existing.geometry_revision,
1422                    geo_revision: existing.geo_revision,
1423                    meshes: existing.meshes.clone(),
1424                    instances: existing.instances.clone(),
1425                    textures: existing.textures.clone(),
1426                    dynamic_meshes: existing.dynamic_meshes.clone(),
1427                    geo_mesh_assets: existing.geo_mesh_assets.clone(),
1428                    geo_instances: existing.geo_instances.clone(),
1429                    particle_layers: existing.particle_layers.clone(),
1430                    particle_textures: existing.particle_textures.clone(),
1431                    ocean,
1432                    environment: existing.environment.clone(),
1433                }));
1434            } else if ocean.is_some() {
1435                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1436                    camera,
1437                    geometry_revision: 1,
1438                    ocean,
1439                    ..Default::default()
1440                }));
1441            }
1442        }
1443        self.inner
1444            .camera_generation
1445            .fetch_add(1, std::sync::atomic::Ordering::Release);
1446    }
1447
1448    /// Updates camera uniforms, particle volumes, and GPU ocean surface descriptor atomically in O(1).
1449    pub fn update_camera_and_particles_and_ocean(
1450        &self,
1451        camera: RetainedCameraUniforms,
1452        particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1453        particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1454        ocean: Option<std::sync::Arc<RetainedOceanSurface>>,
1455    ) {
1456        if let Ok(mut guard) = self.inner.state.write() {
1457            guard.camera = camera;
1458            if let Some(ref existing) = guard.terrain {
1459                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1460                    camera,
1461                    geometry_revision: existing.geometry_revision,
1462                    geo_revision: existing.geo_revision,
1463                    meshes: existing.meshes.clone(),
1464                    instances: existing.instances.clone(),
1465                    textures: existing.textures.clone(),
1466                    dynamic_meshes: existing.dynamic_meshes.clone(),
1467                    geo_mesh_assets: existing.geo_mesh_assets.clone(),
1468                    geo_instances: existing.geo_instances.clone(),
1469                    particle_layers,
1470                    particle_textures,
1471                    ocean,
1472                    environment: existing.environment.clone(),
1473                }));
1474            } else if !particle_layers.is_empty() || ocean.is_some() {
1475                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1476                    camera,
1477                    geometry_revision: 1,
1478                    particle_layers,
1479                    particle_textures,
1480                    ocean,
1481                    ..Default::default()
1482                }));
1483            }
1484        }
1485        self.inner
1486            .camera_generation
1487            .fetch_add(1, std::sync::atomic::Ordering::Release);
1488    }
1489
1490    /// Updates camera uniforms, hardware-instanced geodetic objects, and particle volumes atomically.
1491    pub fn update_camera_and_geo_and_particles(
1492        &self,
1493        camera: RetainedCameraUniforms,
1494        geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1495        geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1496        particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1497        particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1498    ) {
1499        if let Ok(mut guard) = self.inner.state.write() {
1500            guard.camera = camera;
1501            let next_geo_rev = self
1502                .inner
1503                .geo_revision
1504                .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1505                .wrapping_add(1)
1506                .max(1);
1507            if let Some(ref existing) = guard.terrain {
1508                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1509                    camera,
1510                    geometry_revision: existing.geometry_revision,
1511                    geo_revision: next_geo_rev,
1512                    meshes: existing.meshes.clone(),
1513                    instances: existing.instances.clone(),
1514                    textures: existing.textures.clone(),
1515                    dynamic_meshes: existing.dynamic_meshes.clone(),
1516                    geo_mesh_assets,
1517                    geo_instances,
1518                    particle_layers,
1519                    particle_textures,
1520                    ocean: existing.ocean.clone(),
1521                    environment: existing.environment.clone(),
1522                }));
1523            } else if !geo_instances.is_empty() || !particle_layers.is_empty() {
1524                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1525                    camera,
1526                    geometry_revision: 1,
1527                    geo_revision: next_geo_rev,
1528                    geo_mesh_assets,
1529                    geo_instances,
1530                    particle_layers,
1531                    particle_textures,
1532                    ..Default::default()
1533                }));
1534            }
1535        }
1536        self.inner
1537            .camera_generation
1538            .fetch_add(1, std::sync::atomic::Ordering::Release);
1539    }
1540
1541    /// Updates camera uniforms, dynamic overlays, geodetic objects, and particle volumes atomically.
1542    pub fn update_camera_and_world_and_particles(
1543        &self,
1544        camera: RetainedCameraUniforms,
1545        dynamic_meshes: Vec<RetainedDynamicMesh>,
1546        geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1547        geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1548        particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1549        particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1550    ) {
1551        if let Ok(mut guard) = self.inner.state.write() {
1552            guard.camera = camera;
1553            let next_geo_rev = self
1554                .inner
1555                .geo_revision
1556                .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1557                .wrapping_add(1)
1558                .max(1);
1559            if let Some(ref existing) = guard.terrain {
1560                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1561                    camera,
1562                    geometry_revision: existing.geometry_revision,
1563                    geo_revision: next_geo_rev,
1564                    meshes: existing.meshes.clone(),
1565                    instances: existing.instances.clone(),
1566                    textures: existing.textures.clone(),
1567                    dynamic_meshes,
1568                    geo_mesh_assets,
1569                    geo_instances,
1570                    particle_layers,
1571                    particle_textures,
1572                    ocean: existing.ocean.clone(),
1573                    environment: existing.environment.clone(),
1574                }));
1575            } else if !geo_instances.is_empty()
1576                || !dynamic_meshes.is_empty()
1577                || !particle_layers.is_empty()
1578            {
1579                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1580                    camera,
1581                    geometry_revision: 1,
1582                    geo_revision: next_geo_rev,
1583                    dynamic_meshes,
1584                    geo_mesh_assets,
1585                    geo_instances,
1586                    particle_layers,
1587                    particle_textures,
1588                    ..Default::default()
1589                }));
1590            }
1591        }
1592        self.inner
1593            .camera_generation
1594            .fetch_add(1, std::sync::atomic::Ordering::Release);
1595    }
1596
1597    /// Updates camera uniforms, dynamic overlays, geodetic objects, particle volumes, and GPU ocean atomically.
1598    pub fn update_camera_and_world_and_particles_and_ocean(
1599        &self,
1600        camera: RetainedCameraUniforms,
1601        dynamic_meshes: Vec<RetainedDynamicMesh>,
1602        geo_mesh_assets: std::sync::Arc<Vec<std::sync::Arc<RetainedMeshAsset>>>,
1603        geo_instances: std::sync::Arc<Vec<RetainedGeoInstance>>,
1604        particle_layers: std::sync::Arc<Vec<RetainedParticleLayer>>,
1605        particle_textures: std::sync::Arc<Vec<std::sync::Arc<RetainedTileTexture>>>,
1606        ocean: Option<std::sync::Arc<RetainedOceanSurface>>,
1607    ) {
1608        if let Ok(mut guard) = self.inner.state.write() {
1609            guard.camera = camera;
1610            let next_geo_rev = self
1611                .inner
1612                .geo_revision
1613                .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
1614                .wrapping_add(1)
1615                .max(1);
1616            if let Some(ref existing) = guard.terrain {
1617                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1618                    camera,
1619                    geometry_revision: existing.geometry_revision,
1620                    geo_revision: next_geo_rev,
1621                    meshes: existing.meshes.clone(),
1622                    instances: existing.instances.clone(),
1623                    textures: existing.textures.clone(),
1624                    dynamic_meshes,
1625                    geo_mesh_assets,
1626                    geo_instances,
1627                    particle_layers,
1628                    particle_textures,
1629                    ocean,
1630                    environment: existing.environment.clone(),
1631                }));
1632            } else if !geo_instances.is_empty()
1633                || !dynamic_meshes.is_empty()
1634                || !particle_layers.is_empty()
1635                || ocean.is_some()
1636            {
1637                guard.terrain = Some(std::sync::Arc::new(RetainedTerrainFrame {
1638                    camera,
1639                    geometry_revision: 1,
1640                    geo_revision: next_geo_rev,
1641                    dynamic_meshes,
1642                    geo_mesh_assets,
1643                    geo_instances,
1644                    particle_layers,
1645                    particle_textures,
1646                    ocean,
1647                    ..Default::default()
1648                }));
1649            }
1650        }
1651        self.inner
1652            .camera_generation
1653            .fetch_add(1, std::sync::atomic::Ordering::Release);
1654    }
1655
1656    pub fn set_fallback_scene(&self, scene: std::sync::Arc<Scene3D>) {
1657        if let Ok(mut guard) = self.inner.state.write() {
1658            guard.fallback_scene = Some(scene);
1659        }
1660        self.inner
1661            .overlay_generation
1662            .fetch_add(1, std::sync::atomic::Ordering::Release);
1663    }
1664
1665    #[inline]
1666    pub fn camera_generation(&self) -> u64 {
1667        self.inner
1668            .camera_generation
1669            .load(std::sync::atomic::Ordering::Acquire)
1670    }
1671
1672    #[inline]
1673    pub fn geometry_generation(&self) -> u64 {
1674        self.inner
1675            .geometry_generation
1676            .load(std::sync::atomic::Ordering::Acquire)
1677    }
1678
1679    #[inline]
1680    pub fn overlay_generation(&self) -> u64 {
1681        self.inner
1682            .overlay_generation
1683            .load(std::sync::atomic::Ordering::Acquire)
1684    }
1685
1686    #[inline]
1687    pub fn generations(&self) -> (u64, u64, u64) {
1688        (
1689            self.camera_generation(),
1690            self.geometry_generation(),
1691            self.overlay_generation(),
1692        )
1693    }
1694
1695    pub fn camera(&self) -> RetainedCameraUniforms {
1696        self.inner
1697            .state
1698            .read()
1699            .map(|g| g.camera)
1700            .unwrap_or_default()
1701    }
1702
1703    pub fn snapshot_terrain(&self) -> Option<std::sync::Arc<RetainedTerrainFrame>> {
1704        self.inner.state.read().ok().and_then(|g| g.terrain.clone())
1705    }
1706
1707    pub fn fallback_scene(&self) -> Option<std::sync::Arc<Scene3D>> {
1708        self.inner
1709            .state
1710            .read()
1711            .ok()
1712            .and_then(|g| g.fallback_scene.clone())
1713    }
1714
1715    /// Stable process-unique pointer identity of this retained scene handle.
1716    #[inline]
1717    pub fn identity_id(&self) -> usize {
1718        std::sync::Arc::as_ptr(&self.inner) as usize
1719    }
1720}
1721
1722/// Top-Level 3D Scene representation embedded in a Strata Viewport.
1723///
1724/// The background, celestial, cloud, overlay, and texture store state are private so adding
1725/// them does not break struct literals written by existing callers. Use the
1726/// `with_*` builders; the accessors below read them back.
1727#[derive(Debug, Default, Clone, PartialEq)]
1728pub struct Scene3D {
1729    pub camera: Camera3D,
1730    pub lights: Vec<Light3D>,
1731    pub meshes: Vec<Mesh3D>,
1732    background: Background3D,
1733    celestial: Vec<CelestialBody3D>,
1734    cloud_shells: Vec<CloudShell3D>,
1735    overlay: Option<Overlay3D>,
1736    /// Camera up hint in world space. `None` uses the renderer's fallback.
1737    camera_up: Option<[f64; 3]>,
1738    /// Optional shared texture registry resolved automatically by software, Cairo, and GPU viewport rasterizers.
1739    textures: Option<std::sync::Arc<crate::texture3d::TextureStore>>,
1740    /// Optional retained terrain snapshot attached for zero-rebuild GPU vertex pulling.
1741    retained_terrain: Option<std::sync::Arc<RetainedTerrainFrame>>,
1742    /// Optional retained scene handle allowing out-of-band O(1) camera/worker updates.
1743    retained_handle: Option<RetainedScene3D>,
1744}
1745
1746impl Scene3D {
1747    pub fn new() -> Self {
1748        Self::default()
1749    }
1750
1751    pub fn with_retained_terrain(mut self, terrain: std::sync::Arc<RetainedTerrainFrame>) -> Self {
1752        self.retained_terrain = Some(terrain);
1753        self
1754    }
1755
1756    pub fn set_retained_terrain(&mut self, terrain: Option<std::sync::Arc<RetainedTerrainFrame>>) {
1757        self.retained_terrain = terrain;
1758    }
1759
1760    pub fn retained_terrain(&self) -> Option<&std::sync::Arc<RetainedTerrainFrame>> {
1761        self.retained_terrain.as_ref()
1762    }
1763
1764    pub fn with_retained_handle(mut self, handle: RetainedScene3D) -> Self {
1765        self.retained_handle = Some(handle);
1766        self
1767    }
1768
1769    pub fn set_retained_handle(&mut self, handle: Option<RetainedScene3D>) {
1770        self.retained_handle = handle;
1771    }
1772
1773    pub fn retained_handle(&self) -> Option<&RetainedScene3D> {
1774        self.retained_handle.as_ref()
1775    }
1776
1777    /// Computes a deterministic 64-bit fingerprint capturing scene generation, camera state,
1778    /// terrain/mesh geometry revisions, background, lighting, and atmosphere settings so GPU
1779    /// presenters can reuse a cached offscreen 3D color attachment whenever only the 2D UI changes.
1780    pub fn cache_fingerprint(&self) -> u64 {
1781        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
1782        let mix_u64 = |acc: &mut u64, v: u64| {
1783            *acc ^= v;
1784            *acc = acc.wrapping_mul(0x100_0000_01b3);
1785        };
1786        let mix_f32 = |acc: &mut u64, v: f32| mix_u64(acc, v.to_bits() as u64);
1787        let mix_f64 = |acc: &mut u64, v: f64| mix_u64(acc, v.to_bits());
1788        let mix_color = |acc: &mut u64, c: Color| {
1789            mix_u64(acc, u32::from_le_bytes([c.r, c.g, c.b, c.a]) as u64);
1790        };
1791
1792        if let Some(ref handle) = self.retained_handle {
1793            mix_u64(&mut h, 0x5245_5441_494e_4544);
1794            mix_u64(&mut h, handle.identity_id() as u64);
1795            let (cam_gen, geom_gen, ov_gen) = handle.generations();
1796            mix_u64(&mut h, cam_gen);
1797            mix_u64(&mut h, geom_gen);
1798            mix_u64(&mut h, ov_gen);
1799            let cam = handle.camera();
1800            for row in cam.view_proj_rte {
1801                for v in row {
1802                    mix_f32(&mut h, v);
1803                }
1804            }
1805            for v in cam.eye_ecef {
1806                mix_f64(&mut h, v);
1807            }
1808            for v in cam.sun_dir {
1809                mix_f32(&mut h, v);
1810            }
1811            mix_f32(&mut h, cam.near);
1812            mix_f32(&mut h, cam.far);
1813            mix_f32(&mut h, cam.day_night_strength);
1814            mix_f32(&mut h, cam.city_lights_intensity);
1815            mix_f32(&mut h, cam.local_25d_blend);
1816            mix_f32(&mut h, cam.cloud_layer_opacity);
1817            mix_f32(&mut h, cam.local_cloud_opacity);
1818            mix_f32(&mut h, cam.time_s);
1819            mix_f32(&mut h, cam.realistic_25d_sky);
1820            mix_u64(&mut h, cam.stars_visible as u64);
1821            mix_u64(&mut h, cam.sun_visible as u64);
1822            mix_u64(&mut h, cam.moon_visible as u64);
1823            return h;
1824        }
1825
1826        mix_u64(&mut h, 0x4445_434c_4152_4154);
1827        match self.camera {
1828            Camera3D::Perspective {
1829                fov_horizontal_deg,
1830                near,
1831                far,
1832                position,
1833                target,
1834            } => {
1835                mix_u64(&mut h, 1);
1836                mix_f32(&mut h, fov_horizontal_deg);
1837                mix_f32(&mut h, near);
1838                mix_f32(&mut h, far);
1839                for v in position {
1840                    mix_f32(&mut h, v);
1841                }
1842                for v in target {
1843                    mix_f32(&mut h, v);
1844                }
1845            }
1846            Camera3D::Orthographic {
1847                left,
1848                right,
1849                top,
1850                bottom,
1851                near,
1852                far,
1853                position,
1854                target,
1855            } => {
1856                mix_u64(&mut h, 2);
1857                for v in [left, right, top, bottom, near, far] {
1858                    mix_f32(&mut h, v);
1859                }
1860                for v in position {
1861                    mix_f32(&mut h, v);
1862                }
1863                for v in target {
1864                    mix_f32(&mut h, v);
1865                }
1866            }
1867        }
1868        if let Some(up) = self.camera_up {
1869            for v in up {
1870                mix_f64(&mut h, v);
1871            }
1872        }
1873        match self.background {
1874            Background3D::Transparent => mix_u64(&mut h, 1),
1875            Background3D::Solid(c) => {
1876                mix_u64(&mut h, 2);
1877                mix_color(&mut h, c);
1878            }
1879            Background3D::VerticalGradient { top, bottom } => {
1880                mix_u64(&mut h, 3);
1881                mix_color(&mut h, top);
1882                mix_color(&mut h, bottom);
1883            }
1884        }
1885        if let Some(ref terrain) = self.retained_terrain {
1886            mix_u64(&mut h, std::sync::Arc::as_ptr(terrain) as usize as u64);
1887            mix_u64(&mut h, terrain.geometry_revision);
1888            mix_u64(&mut h, terrain.geo_revision);
1889            mix_u64(&mut h, terrain.instances.len() as u64);
1890            mix_f32(&mut h, terrain.camera.time_s);
1891        }
1892        if let Some(ref tex) = self.textures {
1893            mix_u64(&mut h, std::sync::Arc::as_ptr(tex) as usize as u64);
1894        }
1895        mix_u64(&mut h, self.lights.len() as u64);
1896        for l in &self.lights {
1897            match *l {
1898                Light3D::Ambient { color, intensity } => {
1899                    mix_u64(&mut h, 1);
1900                    mix_color(&mut h, color);
1901                    mix_f32(&mut h, intensity);
1902                }
1903                Light3D::Directional {
1904                    position,
1905                    color,
1906                    intensity,
1907                    cast_shadow,
1908                } => {
1909                    mix_u64(&mut h, 2);
1910                    for v in position {
1911                        mix_f32(&mut h, v);
1912                    }
1913                    mix_color(&mut h, color);
1914                    mix_f32(&mut h, intensity);
1915                    mix_u64(&mut h, cast_shadow as u64);
1916                }
1917                Light3D::Point {
1918                    position,
1919                    color,
1920                    intensity,
1921                    distance,
1922                } => {
1923                    mix_u64(&mut h, 3);
1924                    for v in position {
1925                        mix_f32(&mut h, v);
1926                    }
1927                    mix_color(&mut h, color);
1928                    mix_f32(&mut h, intensity);
1929                    mix_f32(&mut h, distance);
1930                }
1931            }
1932        }
1933        mix_u64(&mut h, self.meshes.len() as u64);
1934        for m in &self.meshes {
1935            for v in m.transform.position {
1936                mix_f32(&mut h, v);
1937            }
1938            for v in m.transform.rotation {
1939                mix_f32(&mut h, v);
1940            }
1941            for v in m.transform.scale {
1942                mix_f32(&mut h, v);
1943            }
1944            match &m.geometry {
1945                Geometry3D::Box {
1946                    width,
1947                    height,
1948                    depth,
1949                } => {
1950                    mix_u64(&mut h, 1);
1951                    mix_f32(&mut h, *width);
1952                    mix_f32(&mut h, *height);
1953                    mix_f32(&mut h, *depth);
1954                }
1955                Geometry3D::Sphere {
1956                    radius,
1957                    width_segments,
1958                    height_segments,
1959                } => {
1960                    mix_u64(&mut h, 2);
1961                    mix_f32(&mut h, *radius);
1962                    mix_u64(&mut h, *width_segments as u64);
1963                    mix_u64(&mut h, *height_segments as u64);
1964                }
1965                Geometry3D::Plane { width, height } => {
1966                    mix_u64(&mut h, 3);
1967                    mix_f32(&mut h, *width);
1968                    mix_f32(&mut h, *height);
1969                }
1970                Geometry3D::Cylinder {
1971                    radius_top,
1972                    radius_bottom,
1973                    height,
1974                    radial_segments,
1975                } => {
1976                    mix_u64(&mut h, 4);
1977                    mix_f32(&mut h, *radius_top);
1978                    mix_f32(&mut h, *radius_bottom);
1979                    mix_f32(&mut h, *height);
1980                    mix_u64(&mut h, *radial_segments as u64);
1981                }
1982                Geometry3D::Custom { vertices, indices }
1983                | Geometry3D::CustomTextured { vertices, indices } => {
1984                    mix_u64(&mut h, 5);
1985                    mix_u64(&mut h, vertices.len() as u64);
1986                    mix_u64(&mut h, indices.len() as u64);
1987                    for &v in vertices.iter().take(6) {
1988                        mix_f32(&mut h, v);
1989                    }
1990                    if let Some(&v) = vertices.last() {
1991                        mix_f32(&mut h, v);
1992                    }
1993                }
1994            }
1995        }
1996        mix_u64(&mut h, self.celestial.len() as u64);
1997        mix_u64(&mut h, self.cloud_shells.len() as u64);
1998        mix_u64(&mut h, self.overlay.is_some() as u64);
1999        h
2000    }
2001
2002    pub fn add_mesh(&mut self, mesh: Mesh3D) {
2003        self.meshes.push(mesh);
2004    }
2005
2006    pub fn add_light(&mut self, light: Light3D) {
2007        self.lights.push(light);
2008    }
2009
2010    /// Replaces the background fill used before geometry is drawn.
2011    pub fn with_background(mut self, background: Background3D) -> Self {
2012        self.background = background;
2013        self
2014    }
2015
2016    /// Adds an emissive celestial body.
2017    pub fn with_celestial(mut self, body: CelestialBody3D) -> Self {
2018        self.celestial.push(body);
2019        self
2020    }
2021
2022    /// Adds a translucent cloud shell.
2023    pub fn with_cloud_shell(mut self, shell: CloudShell3D) -> Self {
2024        self.cloud_shells.push(shell);
2025        self
2026    }
2027
2028    /// Attaches the overlay pass drawn after geometry.
2029    pub fn with_overlay(mut self, overlay: Overlay3D) -> Self {
2030        self.overlay = Some(overlay);
2031        self
2032    }
2033
2034    pub fn overlay(&self) -> Option<&Overlay3D> {
2035        self.overlay.as_ref()
2036    }
2037
2038    /// Returns a mutable reference to the scene's 3D overlay pass, initializing an empty
2039    /// [`Overlay3D`] if none is attached yet.
2040    pub fn overlay_mut(&mut self) -> &mut Overlay3D {
2041        self.overlay.get_or_insert_with(Overlay3D::new)
2042    }
2043
2044    /// Attaches a shared [`crate::texture3d::TextureStore`] carried with the scene through
2045    /// `DrawCommand::DrawViewport3D` into live window and offscreen rasterizers.
2046    pub fn with_textures(
2047        mut self,
2048        textures: std::sync::Arc<crate::texture3d::TextureStore>,
2049    ) -> Self {
2050        self.textures = Some(textures);
2051        self
2052    }
2053
2054    /// Sets or clears the shared [`crate::texture3d::TextureStore`] attached to this scene.
2055    pub fn set_textures(
2056        &mut self,
2057        textures: Option<std::sync::Arc<crate::texture3d::TextureStore>>,
2058    ) {
2059        self.textures = textures;
2060    }
2061
2062    /// Borrows the shared [`crate::texture3d::TextureStore`] handle attached to this scene, if any.
2063    pub fn textures(&self) -> Option<&std::sync::Arc<crate::texture3d::TextureStore>> {
2064        self.textures.as_ref()
2065    }
2066
2067    /// Borrows the underlying [`crate::texture3d::TextureStore`] attached to this scene, if any.
2068    pub fn textures_deref(&self) -> Option<&crate::texture3d::TextureStore> {
2069        self.textures.as_deref()
2070    }
2071
2072    /// Sets the camera's up direction. A downward-looking camera has no unique
2073    /// screen up from the world Y axis, so scenes that care about roll should
2074    /// declare it, for example the local east-north-up frame at a ground focus.
2075    pub fn with_camera_up(mut self, up: [f64; 3]) -> Self {
2076        self.camera_up = Some(up);
2077        self
2078    }
2079
2080    pub fn camera_up(&self) -> Option<[f64; 3]> {
2081        self.camera_up
2082    }
2083
2084    pub fn background(&self) -> Background3D {
2085        self.background
2086    }
2087
2088    pub fn celestial(&self) -> &[CelestialBody3D] {
2089        &self.celestial
2090    }
2091
2092    pub fn cloud_shells(&self) -> &[CloudShell3D] {
2093        &self.cloud_shells
2094    }
2095}
2096
2097/// Callback that rasterizes a text run into the framebuffer.
2098///
2099/// The 3D overlay pass needs text, but `strata_render` must not depend on the
2100/// platform text backend. Consumers install a rasterizer, exactly like the
2101/// layout crate installs a text measurer.
2102pub type TextRasterizer = crate::overlay3d::TextRasterizer;
2103
2104thread_local! {
2105    static TEXT_RASTERIZER: std::cell::Cell<Option<TextRasterizer>> = const { std::cell::Cell::new(None) };
2106}
2107
2108/// Installs the overlay text rasterizer for this thread.
2109pub fn register_overlay_text_rasterizer(rasterizer: TextRasterizer) {
2110    TEXT_RASTERIZER.with(|slot| slot.set(Some(rasterizer)));
2111}
2112
2113/// Returns the installed overlay text rasterizer, if any.
2114pub fn overlay_text_rasterizer() -> Option<TextRasterizer> {
2115    TEXT_RASTERIZER.with(|slot| slot.get())
2116}
2117
2118// ---------------------------------------------------------------------------
2119// Declarative & Programmatic 3D RSX Viewport Components
2120// ---------------------------------------------------------------------------
2121
2122use strata_dom::{Attribute, NodeBlueprint, Tag, View};
2123use strata_macro::component;
2124
2125/// Conversion trait allowing RSX `<Canvas3D scene={...}>` and `<SceneViewport scene={...}>`
2126/// props to accept owned [`Scene3D`], `Option<Scene3D>`, or zero-copy `Arc<Scene3D>` handles.
2127pub trait IntoScene3DProp {
2128    fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>>;
2129}
2130
2131impl IntoScene3DProp for Scene3D {
2132    fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
2133        Some(std::sync::Arc::new(self))
2134    }
2135}
2136
2137impl IntoScene3DProp for Option<Scene3D> {
2138    fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
2139        self.map(std::sync::Arc::new)
2140    }
2141}
2142
2143impl IntoScene3DProp for std::sync::Arc<Scene3D> {
2144    fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
2145        Some(self)
2146    }
2147}
2148
2149impl IntoScene3DProp for &std::sync::Arc<Scene3D> {
2150    fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
2151        Some(std::sync::Arc::clone(self))
2152    }
2153}
2154
2155impl IntoScene3DProp for Option<std::sync::Arc<Scene3D>> {
2156    fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
2157        self
2158    }
2159}
2160
2161impl IntoScene3DProp for Option<&std::sync::Arc<Scene3D>> {
2162    fn into_scene3d_prop(self) -> Option<std::sync::Arc<Scene3D>> {
2163        self.map(std::sync::Arc::clone)
2164    }
2165}
2166
2167#[allow(non_snake_case)]
2168pub fn Canvas3D(class: Option<&'static str>, children: Option<Vec<NodeBlueprint>>) -> View {
2169    let mut builder = Canvas3D::builder();
2170    if let Some(c) = class {
2171        builder = builder.class(c);
2172    }
2173    if let Some(ch) = children {
2174        builder = builder.children(ch);
2175    }
2176    builder.build()
2177}
2178
2179#[allow(non_snake_case)]
2180pub struct Canvas3D {}
2181
2182impl Canvas3D {
2183    pub fn builder() -> Canvas3DBuilder {
2184        Canvas3DBuilder::default()
2185    }
2186}
2187
2188/// Conversion trait allowing `on_camera_change` on 3D viewports (`Canvas3D`, `SceneViewport`)
2189/// to accept closures, `Rc<dyn Fn(&OrbitControls)>`, or `Option<Rc<dyn Fn(&OrbitControls)>>`.
2190pub trait IntoCameraChangeProp {
2191    fn into_camera_change_prop(
2192        self,
2193    ) -> Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>>;
2194}
2195
2196impl IntoCameraChangeProp for Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>> {
2197    fn into_camera_change_prop(
2198        self,
2199    ) -> Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>> {
2200        self
2201    }
2202}
2203
2204impl IntoCameraChangeProp for std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)> {
2205    fn into_camera_change_prop(
2206        self,
2207    ) -> Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>> {
2208        Some(self)
2209    }
2210}
2211
2212impl<F: Fn(&crate::orbit_controls::OrbitControls) + 'static> IntoCameraChangeProp for F {
2213    fn into_camera_change_prop(
2214        self,
2215    ) -> Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>> {
2216        Some(std::rc::Rc::new(self))
2217    }
2218}
2219
2220/// Attaches built-in `OrbitControls` pointer drag (orbit/pan) and wheel (zoom) listeners
2221/// to a 3D canvas attribute list, invoking `cb` whenever the camera state changes.
2222pub fn attach_orbit_controls_listeners(
2223    attrs: &mut Vec<Attribute>,
2224    scene: Option<&Scene3D>,
2225    width: Option<f32>,
2226    height: Option<f32>,
2227    cb: std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>,
2228) {
2229    use std::cell::RefCell;
2230    use std::rc::Rc;
2231    use strata_dom::{Event, EventType};
2232
2233    let mut initial_controls = match scene {
2234        Some(s) => crate::orbit_controls::OrbitControls::from_camera(&s.camera),
2235        None => crate::orbit_controls::OrbitControls::default(),
2236    };
2237    initial_controls.enable_damping = false;
2238    let fov_deg = match scene.map(|s| &s.camera) {
2239        Some(Camera3D::Perspective {
2240            fov_horizontal_deg, ..
2241        }) => *fov_horizontal_deg,
2242        _ => 60.0,
2243    };
2244    let fallback_vw = width.unwrap_or(800.0).max(1.0);
2245    let fallback_vh = height.unwrap_or(600.0).max(1.0);
2246    let controls = Rc::new(RefCell::new(initial_controls));
2247
2248    let ctrl_down = Rc::clone(&controls);
2249    attrs.push(Attribute::event_listener(
2250        EventType::PointerDown,
2251        move |ev: Event| {
2252            let btn = ev.button.max(0) as u8;
2253            ctrl_down
2254                .borrow_mut()
2255                .on_pointer_down(ev.client_x as f32, ev.client_y as f32, btn);
2256        },
2257    ));
2258
2259    let ctrl_move = Rc::clone(&controls);
2260    let cb_move = Rc::clone(&cb);
2261    attrs.push(Attribute::event_listener(
2262        EventType::PointerMove,
2263        move |ev: Event| {
2264            let changed = {
2265                let mut c = ctrl_move.borrow_mut();
2266                let active = c.active_mode != crate::orbit_controls::OrbitInteractionMode::None;
2267                if active {
2268                    let vw = if ev.width > 0.0 {
2269                        (ev.width as f32).max(1.0)
2270                    } else {
2271                        fallback_vw
2272                    };
2273                    let vh = if ev.height > 0.0 {
2274                        (ev.height as f32).max(1.0)
2275                    } else {
2276                        fallback_vh
2277                    };
2278                    c.on_pointer_move(ev.client_x as f32, ev.client_y as f32, vw, vh, fov_deg);
2279                }
2280                active
2281            };
2282            if changed {
2283                let c = ctrl_move.borrow();
2284                cb_move(&c);
2285            }
2286        },
2287    ));
2288
2289    let ctrl_up = Rc::clone(&controls);
2290    attrs.push(Attribute::event_listener(
2291        EventType::PointerUp,
2292        move |_ev: Event| {
2293            ctrl_up.borrow_mut().on_pointer_up();
2294        },
2295    ));
2296
2297    let ctrl_wheel = Rc::clone(&controls);
2298    let cb_wheel = Rc::clone(&cb);
2299    attrs.push(Attribute::event_listener(
2300        EventType::Wheel,
2301        move |ev: Event| {
2302            ev.default_prevented.set(true);
2303            {
2304                let mut c = ctrl_wheel.borrow_mut();
2305                c.on_wheel(ev.delta_y as f32);
2306            }
2307            let c = ctrl_wheel.borrow();
2308            cb_wheel(&c);
2309        },
2310    ));
2311}
2312
2313#[derive(Default)]
2314pub struct Canvas3DBuilder {
2315    pub scene: Option<std::sync::Arc<Scene3D>>,
2316    pub retained: Option<RetainedScene3D>,
2317    pub uncapped: bool,
2318    pub responsive: bool,
2319    pub class: Option<strata_dom::ClassList>,
2320    pub style: Option<String>,
2321    pub id: Option<String>,
2322    pub title: Option<String>,
2323    pub __strata_key: Option<String>,
2324    pub width: Option<f32>,
2325    pub height: Option<f32>,
2326    pub on_camera_change: Option<std::rc::Rc<dyn Fn(&crate::orbit_controls::OrbitControls)>>,
2327    pub events: Vec<Attribute>,
2328    pub children: Option<Vec<NodeBlueprint>>,
2329}
2330
2331impl Canvas3DBuilder {
2332    pub fn scene(mut self, scene: impl IntoScene3DProp) -> Self {
2333        self.scene = scene.into_scene3d_prop();
2334        self
2335    }
2336
2337    pub fn class(mut self, class: impl strata_dom::IntoClassList) -> Self {
2338        self.class = Some(class.into_class_list());
2339        self
2340    }
2341
2342    pub fn style(mut self, style: impl Into<String>) -> Self {
2343        self.style = Some(style.into());
2344        self
2345    }
2346
2347    pub fn id(mut self, id: impl Into<String>) -> Self {
2348        self.id = Some(id.into());
2349        self
2350    }
2351
2352    pub fn title(mut self, title: impl strata_dom::IntoOptionalString) -> Self {
2353        self.title = title.into_optional_string();
2354        self
2355    }
2356
2357    pub fn key(mut self, key: impl std::fmt::Display) -> Self {
2358        self.__strata_key = Some(key.to_string());
2359        self
2360    }
2361
2362    pub fn width(mut self, width: impl Into<Option<f32>>) -> Self {
2363        self.width = width.into();
2364        self
2365    }
2366
2367    pub fn height(mut self, height: impl Into<Option<f32>>) -> Self {
2368        self.height = height.into();
2369        self
2370    }
2371
2372    /// When `true`, omits inline `width`/`height` attributes so CSS/flex classes
2373    /// (`w-full h-full`, `flex-1`, split panes) control the resolved viewport size.
2374    pub fn responsive(mut self, responsive: bool) -> Self {
2375        self.responsive = responsive;
2376        self
2377    }
2378
2379    pub fn on_camera_change(mut self, cb: impl IntoCameraChangeProp) -> Self {
2380        self.on_camera_change = cb.into_camera_change_prop();
2381        self
2382    }
2383
2384    pub fn on_camera_change_fn(
2385        mut self,
2386        cb: impl Fn(&crate::orbit_controls::OrbitControls) + 'static,
2387    ) -> Self {
2388        self.on_camera_change = Some(std::rc::Rc::new(cb));
2389        self
2390    }
2391
2392    fn push_event<Args>(
2393        mut self,
2394        ty: strata_dom::EventType,
2395        handler: impl strata_dom::EventHandlerMarker<Args> + 'static,
2396    ) -> Self {
2397        self.events.push(Attribute::event_listener(ty, handler));
2398        self
2399    }
2400
2401    pub fn onmousedown<Args>(
2402        self,
2403        handler: impl strata_dom::EventHandlerMarker<Args> + 'static,
2404    ) -> Self {
2405        self.push_event(strata_dom::EventType::MouseDown, handler)
2406    }
2407
2408    pub fn onmousedown_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2409        self.push_event(strata_dom::EventType::MouseDown, handler)
2410    }
2411
2412    pub fn onmousemove<Args>(
2413        self,
2414        handler: impl strata_dom::EventHandlerMarker<Args> + 'static,
2415    ) -> Self {
2416        self.push_event(strata_dom::EventType::MouseMove, handler)
2417    }
2418
2419    pub fn onmousemove_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2420        self.push_event(strata_dom::EventType::MouseMove, handler)
2421    }
2422
2423    pub fn onmouseup<Args>(
2424        self,
2425        handler: impl strata_dom::EventHandlerMarker<Args> + 'static,
2426    ) -> Self {
2427        self.push_event(strata_dom::EventType::MouseUp, handler)
2428    }
2429
2430    pub fn onmouseup_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2431        self.push_event(strata_dom::EventType::MouseUp, handler)
2432    }
2433
2434    pub fn onmouseenter<Args>(
2435        self,
2436        handler: impl strata_dom::EventHandlerMarker<Args> + 'static,
2437    ) -> Self {
2438        self.push_event(strata_dom::EventType::MouseEnter, handler)
2439    }
2440
2441    pub fn onmouseenter_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2442        self.push_event(strata_dom::EventType::MouseEnter, handler)
2443    }
2444
2445    pub fn onmouseleave<Args>(
2446        self,
2447        handler: impl strata_dom::EventHandlerMarker<Args> + 'static,
2448    ) -> Self {
2449        self.push_event(strata_dom::EventType::MouseLeave, handler)
2450    }
2451
2452    pub fn onmouseleave_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2453        self.push_event(strata_dom::EventType::MouseLeave, handler)
2454    }
2455
2456    pub fn onwheel<Args>(
2457        self,
2458        handler: impl strata_dom::EventHandlerMarker<Args> + 'static,
2459    ) -> Self {
2460        self.push_event(strata_dom::EventType::Wheel, handler)
2461    }
2462
2463    pub fn onwheel_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2464        self.push_event(strata_dom::EventType::Wheel, handler)
2465    }
2466
2467    pub fn onpointerdown<Args>(
2468        self,
2469        handler: impl strata_dom::EventHandlerMarker<Args> + 'static,
2470    ) -> Self {
2471        self.push_event(strata_dom::EventType::PointerDown, handler)
2472    }
2473
2474    pub fn onpointerdown_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2475        self.push_event(strata_dom::EventType::PointerDown, handler)
2476    }
2477
2478    pub fn onpointermove<Args>(
2479        self,
2480        handler: impl strata_dom::EventHandlerMarker<Args> + 'static,
2481    ) -> Self {
2482        self.push_event(strata_dom::EventType::PointerMove, handler)
2483    }
2484
2485    pub fn onpointermove_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2486        self.push_event(strata_dom::EventType::PointerMove, handler)
2487    }
2488
2489    pub fn onpointerup<Args>(
2490        self,
2491        handler: impl strata_dom::EventHandlerMarker<Args> + 'static,
2492    ) -> Self {
2493        self.push_event(strata_dom::EventType::PointerUp, handler)
2494    }
2495
2496    pub fn onpointerup_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2497        self.push_event(strata_dom::EventType::PointerUp, handler)
2498    }
2499
2500    pub fn onclick<Args>(self, handler: impl strata_dom::EventHandlerMarker<Args> + 'static) -> Self {
2501        self.push_event(strata_dom::EventType::Click, handler)
2502    }
2503
2504    pub fn onclick_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2505        self.push_event(strata_dom::EventType::Click, handler)
2506    }
2507
2508    pub fn ondblclick<Args>(
2509        self,
2510        handler: impl strata_dom::EventHandlerMarker<Args> + 'static,
2511    ) -> Self {
2512        self.push_event(strata_dom::EventType::DblClick, handler)
2513    }
2514
2515    pub fn ondblclick_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2516        self.push_event(strata_dom::EventType::DblClick, handler)
2517    }
2518
2519    pub fn oncontextmenu<Args>(
2520        self,
2521        handler: impl strata_dom::EventHandlerMarker<Args> + 'static,
2522    ) -> Self {
2523        self.push_event(strata_dom::EventType::ContextMenu, handler)
2524    }
2525
2526    pub fn oncontextmenu_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2527        self.push_event(strata_dom::EventType::ContextMenu, handler)
2528    }
2529
2530    pub fn onresize<Args>(
2531        self,
2532        handler: impl strata_dom::EventHandlerMarker<Args> + 'static,
2533    ) -> Self {
2534        self.push_event(strata_dom::EventType::Resize, handler)
2535    }
2536
2537    pub fn onresize_fn(self, handler: impl Fn(strata_dom::Event) + 'static) -> Self {
2538        self.push_event(strata_dom::EventType::Resize, handler)
2539    }
2540
2541    /// Binds a persistent [`RetainedScene3D`] handle for out-of-band zero-rebuild GPU updates.
2542    pub fn retained(mut self, handle: impl Into<Option<RetainedScene3D>>) -> Self {
2543        self.retained = handle.into();
2544        self
2545    }
2546
2547    /// Opts this 3D canvas into uncapped vsync-off presentation when supported by the surface.
2548    pub fn uncapped(mut self, uncapped: bool) -> Self {
2549        self.uncapped = uncapped;
2550        self
2551    }
2552
2553    pub fn children(mut self, children: impl strata_dom::IntoChildren<Vec<NodeBlueprint>>) -> Self {
2554        self.children = Some(children.into_children());
2555        self
2556    }
2557
2558    pub fn build(self) -> View {
2559        let render = move || {
2560            let _scope = strata_dom::ComponentScopeGuard::enter(concat!(
2561                module_path!(),
2562                "::Canvas3D"
2563            ));
2564            let is_responsive =
2565                self.responsive || (self.width.is_none() && self.height.is_none());
2566
2567            let mut attrs = Vec::with_capacity(6 + self.events.len());
2568            attrs.push(Attribute::property("data-strata-canvas3d", "true"));
2569            if self.uncapped {
2570                attrs.push(Attribute::property("data-strata-uncapped", "true"));
2571            }
2572            if let Some(id) = self.id {
2573                attrs.push(Attribute::property("id", id));
2574            }
2575            if let Some(title) = self.title {
2576                attrs.push(Attribute::property("title", title));
2577            }
2578            if !is_responsive {
2579                if let Some(w) = self.width {
2580                    attrs.push(Attribute::property("width", w.to_string()));
2581                }
2582                if let Some(h) = self.height {
2583                    attrs.push(Attribute::property("height", h.to_string()));
2584                }
2585            }
2586            if let Some(style) = self.style {
2587                attrs.push(Attribute::property("style", style));
2588            }
2589            attrs.extend(self.events);
2590            let effective_scene = match (self.scene, self.retained) {
2591                (Some(mut scene), Some(retained)) => {
2592                    if scene.retained_handle().is_none() {
2593                        let s = std::sync::Arc::make_mut(&mut scene);
2594                        s.set_retained_handle(Some(retained));
2595                    }
2596                    Some(scene)
2597                }
2598                (Some(scene), None) => Some(scene),
2599                (None, Some(retained)) => {
2600                    let mut scene = retained
2601                        .fallback_scene()
2602                        .map(|s| (*s).clone())
2603                        .unwrap_or_default();
2604                    scene.set_retained_handle(Some(retained));
2605                    Some(std::sync::Arc::new(scene))
2606                }
2607                (None, None) => None,
2608            };
2609            if let Some(cb) = self.on_camera_change {
2610                attach_orbit_controls_listeners(
2611                    &mut attrs,
2612                    effective_scene.as_deref(),
2613                    if is_responsive { None } else { self.width },
2614                    if is_responsive { None } else { self.height },
2615                    cb,
2616                );
2617            }
2618            if let Some(scene) = effective_scene {
2619                let payload: std::sync::Arc<dyn std::any::Any + Send + Sync> = scene;
2620                attrs.push(Attribute::scene_payload_arc(payload));
2621            }
2622            View::new(NodeBlueprint::element(
2623                Tag::Canvas,
2624                self.class.unwrap_or_default(),
2625                attrs,
2626                self.children.unwrap_or_default(),
2627            ))
2628        };
2629
2630        if let Some(k) = self.__strata_key {
2631            strata_dom::with_component_key(k, render)
2632        } else {
2633            render()
2634        }
2635    }
2636}
2637
2638#[component]
2639pub fn PerspectiveCamera(
2640    fov: Option<f32>,
2641    aspect: Option<f32>,
2642    near: Option<f32>,
2643    far: Option<f32>,
2644    position: Option<[f32; 3]>,
2645    target: Option<[f32; 3]>,
2646) -> View {
2647    let mut attrs = Vec::new();
2648    if let Some(f) = fov {
2649        attrs.push(Attribute::property("data-fov", f.to_string()));
2650    }
2651    if let Some(a) = aspect {
2652        attrs.push(Attribute::property("data-aspect", a.to_string()));
2653    }
2654    if let Some(n) = near {
2655        attrs.push(Attribute::property("data-near", n.to_string()));
2656    }
2657    if let Some(fa) = far {
2658        attrs.push(Attribute::property("data-far", fa.to_string()));
2659    }
2660    if let Some(p) = position {
2661        attrs.push(Attribute::property(
2662            "data-position",
2663            format!("{},{},{}", p[0], p[1], p[2]),
2664        ));
2665    }
2666    if let Some(t) = target {
2667        attrs.push(Attribute::property(
2668            "data-target",
2669            format!("{},{},{}", t[0], t[1], t[2]),
2670        ));
2671    }
2672    View::new(NodeBlueprint::element(
2673        Tag::Custom("PerspectiveCamera"),
2674        strata_dom::ClassList::default(),
2675        attrs,
2676        Vec::new(),
2677    ))
2678}
2679
2680#[component]
2681pub fn OrthographicCamera(
2682    left: Option<f32>,
2683    right: Option<f32>,
2684    top: Option<f32>,
2685    bottom: Option<f32>,
2686    near: Option<f32>,
2687    far: Option<f32>,
2688    position: Option<[f32; 3]>,
2689    target: Option<[f32; 3]>,
2690) -> View {
2691    let mut attrs = Vec::new();
2692    if let Some(v) = left {
2693        attrs.push(Attribute::property("data-left", v.to_string()));
2694    }
2695    if let Some(v) = right {
2696        attrs.push(Attribute::property("data-right", v.to_string()));
2697    }
2698    if let Some(v) = top {
2699        attrs.push(Attribute::property("data-top", v.to_string()));
2700    }
2701    if let Some(v) = bottom {
2702        attrs.push(Attribute::property("data-bottom", v.to_string()));
2703    }
2704    if let Some(v) = near {
2705        attrs.push(Attribute::property("data-near", v.to_string()));
2706    }
2707    if let Some(v) = far {
2708        attrs.push(Attribute::property("data-far", v.to_string()));
2709    }
2710    if let Some(p) = position {
2711        attrs.push(Attribute::property(
2712            "data-position",
2713            format!("{},{},{}", p[0], p[1], p[2]),
2714        ));
2715    }
2716    if let Some(t) = target {
2717        attrs.push(Attribute::property(
2718            "data-target",
2719            format!("{},{},{}", t[0], t[1], t[2]),
2720        ));
2721    }
2722    View::new(NodeBlueprint::element(
2723        Tag::Custom("OrthographicCamera"),
2724        strata_dom::ClassList::default(),
2725        attrs,
2726        Vec::new(),
2727    ))
2728}
2729
2730#[component]
2731pub fn AmbientLight(color: Option<&'static str>, intensity: Option<f32>) -> View {
2732    let mut attrs = Vec::new();
2733    if let Some(c) = color {
2734        attrs.push(Attribute::property("data-color", c));
2735    }
2736    if let Some(i) = intensity {
2737        attrs.push(Attribute::property("data-intensity", i.to_string()));
2738    }
2739    View::new(NodeBlueprint::element(
2740        Tag::Custom("AmbientLight"),
2741        strata_dom::ClassList::default(),
2742        attrs,
2743        Vec::new(),
2744    ))
2745}
2746
2747#[component]
2748pub fn DirectionalLight(
2749    position: Option<[f32; 3]>,
2750    color: Option<&'static str>,
2751    intensity: Option<f32>,
2752    cast_shadow: Option<bool>,
2753) -> View {
2754    let mut attrs = Vec::new();
2755    if let Some(p) = position {
2756        attrs.push(Attribute::property(
2757            "data-position",
2758            format!("{},{},{}", p[0], p[1], p[2]),
2759        ));
2760    }
2761    if let Some(c) = color {
2762        attrs.push(Attribute::property("data-color", c));
2763    }
2764    if let Some(i) = intensity {
2765        attrs.push(Attribute::property("data-intensity", i.to_string()));
2766    }
2767    if let Some(s) = cast_shadow {
2768        attrs.push(Attribute::property("data-cast-shadow", s.to_string()));
2769    }
2770    View::new(NodeBlueprint::element(
2771        Tag::Custom("DirectionalLight"),
2772        strata_dom::ClassList::default(),
2773        attrs,
2774        Vec::new(),
2775    ))
2776}
2777
2778#[component]
2779pub fn PointLight(
2780    position: Option<[f32; 3]>,
2781    color: Option<&'static str>,
2782    intensity: Option<f32>,
2783    distance: Option<f32>,
2784) -> View {
2785    let mut attrs = Vec::new();
2786    if let Some(p) = position {
2787        attrs.push(Attribute::property(
2788            "data-position",
2789            format!("{},{},{}", p[0], p[1], p[2]),
2790        ));
2791    }
2792    if let Some(c) = color {
2793        attrs.push(Attribute::property("data-color", c));
2794    }
2795    if let Some(i) = intensity {
2796        attrs.push(Attribute::property("data-intensity", i.to_string()));
2797    }
2798    if let Some(d) = distance {
2799        attrs.push(Attribute::property("data-distance", d.to_string()));
2800    }
2801    View::new(NodeBlueprint::element(
2802        Tag::Custom("PointLight"),
2803        strata_dom::ClassList::default(),
2804        attrs,
2805        Vec::new(),
2806    ))
2807}
2808
2809#[component]
2810pub fn Mesh(
2811    position: Option<[f32; 3]>,
2812    rotation: Option<[f32; 3]>,
2813    scale: Option<[f32; 3]>,
2814    children: Option<Vec<NodeBlueprint>>,
2815) -> View {
2816    let mut attrs = Vec::new();
2817    if let Some(p) = position {
2818        attrs.push(Attribute::property(
2819            "data-position",
2820            format!("{},{},{}", p[0], p[1], p[2]),
2821        ));
2822    }
2823    if let Some(r) = rotation {
2824        attrs.push(Attribute::property(
2825            "data-rotation",
2826            format!("{},{},{}", r[0], r[1], r[2]),
2827        ));
2828    }
2829    if let Some(s) = scale {
2830        attrs.push(Attribute::property(
2831            "data-scale",
2832            format!("{},{},{}", s[0], s[1], s[2]),
2833        ));
2834    }
2835    View::new(NodeBlueprint::element(
2836        Tag::Custom("Mesh"),
2837        strata_dom::ClassList::default(),
2838        attrs,
2839        children.unwrap_or_default(),
2840    ))
2841}
2842
2843#[component]
2844pub fn BoxGeometry(width: Option<f32>, height: Option<f32>, depth: Option<f32>) -> View {
2845    let mut attrs = Vec::new();
2846    if let Some(w) = width {
2847        attrs.push(Attribute::property("data-width", w.to_string()));
2848    }
2849    if let Some(h) = height {
2850        attrs.push(Attribute::property("data-height", h.to_string()));
2851    }
2852    if let Some(d) = depth {
2853        attrs.push(Attribute::property("data-depth", d.to_string()));
2854    }
2855    View::new(NodeBlueprint::element(
2856        Tag::Custom("BoxGeometry"),
2857        strata_dom::ClassList::default(),
2858        attrs,
2859        Vec::new(),
2860    ))
2861}
2862
2863#[component]
2864pub fn SphereGeometry(
2865    radius: Option<f32>,
2866    width_segments: Option<u32>,
2867    height_segments: Option<u32>,
2868) -> View {
2869    let mut attrs = Vec::new();
2870    if let Some(r) = radius {
2871        attrs.push(Attribute::property("data-radius", r.to_string()));
2872    }
2873    if let Some(w) = width_segments {
2874        attrs.push(Attribute::property("data-width-segments", w.to_string()));
2875    }
2876    if let Some(h) = height_segments {
2877        attrs.push(Attribute::property("data-height-segments", h.to_string()));
2878    }
2879    View::new(NodeBlueprint::element(
2880        Tag::Custom("SphereGeometry"),
2881        strata_dom::ClassList::default(),
2882        attrs,
2883        Vec::new(),
2884    ))
2885}
2886
2887#[component]
2888pub fn PlaneGeometry(width: Option<f32>, height: Option<f32>) -> View {
2889    let mut attrs = Vec::new();
2890    if let Some(w) = width {
2891        attrs.push(Attribute::property("data-width", w.to_string()));
2892    }
2893    if let Some(h) = height {
2894        attrs.push(Attribute::property("data-height", h.to_string()));
2895    }
2896    View::new(NodeBlueprint::element(
2897        Tag::Custom("PlaneGeometry"),
2898        strata_dom::ClassList::default(),
2899        attrs,
2900        Vec::new(),
2901    ))
2902}
2903
2904#[component]
2905pub fn CylinderGeometry(
2906    radius_top: Option<f32>,
2907    radius_bottom: Option<f32>,
2908    height: Option<f32>,
2909    radial_segments: Option<u32>,
2910) -> View {
2911    let mut attrs = Vec::new();
2912    if let Some(rt) = radius_top {
2913        attrs.push(Attribute::property("data-radius-top", rt.to_string()));
2914    }
2915    if let Some(rb) = radius_bottom {
2916        attrs.push(Attribute::property("data-radius-bottom", rb.to_string()));
2917    }
2918    if let Some(h) = height {
2919        attrs.push(Attribute::property("data-height", h.to_string()));
2920    }
2921    if let Some(rs) = radial_segments {
2922        attrs.push(Attribute::property("data-radial-segments", rs.to_string()));
2923    }
2924    View::new(NodeBlueprint::element(
2925        Tag::Custom("CylinderGeometry"),
2926        strata_dom::ClassList::default(),
2927        attrs,
2928        Vec::new(),
2929    ))
2930}
2931
2932#[component]
2933pub fn StandardMaterial(
2934    color: Option<&'static str>,
2935    roughness: Option<f32>,
2936    metalness: Option<f32>,
2937) -> View {
2938    let mut attrs = Vec::new();
2939    if let Some(c) = color {
2940        attrs.push(Attribute::property("data-color", c));
2941    }
2942    if let Some(r) = roughness {
2943        attrs.push(Attribute::property("data-roughness", r.to_string()));
2944    }
2945    if let Some(m) = metalness {
2946        attrs.push(Attribute::property("data-metalness", m.to_string()));
2947    }
2948    View::new(NodeBlueprint::element(
2949        Tag::Custom("StandardMaterial"),
2950        strata_dom::ClassList::default(),
2951        attrs,
2952        Vec::new(),
2953    ))
2954}
2955
2956#[component]
2957pub fn ShaderMaterial(
2958    glsl_fragment: Option<&'static str>,
2959    uniform_time: Option<f32>,
2960    uniforms: Option<Vec<(String, f32)>>,
2961) -> View {
2962    let mut attrs = Vec::new();
2963    if let Some(g) = glsl_fragment {
2964        attrs.push(Attribute::property("data-glsl", g));
2965    }
2966    if let Some(t) = uniform_time {
2967        attrs.push(Attribute::property("data-time", t.to_string()));
2968    }
2969    if let Some(u) = uniforms {
2970        let encoded = u
2971            .into_iter()
2972            .map(|(k, v)| format!("{k}={v}"))
2973            .collect::<Vec<_>>()
2974            .join(";");
2975        attrs.push(Attribute::property("data-uniforms", encoded));
2976    }
2977    View::new(NodeBlueprint::element(
2978        Tag::Custom("ShaderMaterial"),
2979        strata_dom::ClassList::default(),
2980        attrs,
2981        Vec::new(),
2982    ))
2983}
2984
2985fn get_3d_attr<'a>(attrs: &'a [strata_dom::Attribute], key: &str) -> Option<&'a str> {
2986    attrs.iter().find_map(|attr| {
2987        if let strata_dom::Attribute::Property { key: k, value: v } = attr {
2988            if k == key {
2989                return Some(v.as_str());
2990            }
2991        }
2992        None
2993    })
2994}
2995
2996fn parse_3d_vec3(s: &str) -> Option<[f32; 3]> {
2997    let mut parts = s.split(',');
2998    let x = parts.next()?.trim().parse::<f32>().ok()?;
2999    let y = parts.next()?.trim().parse::<f32>().ok()?;
3000    let z = parts.next()?.trim().parse::<f32>().ok()?;
3001    Some([x, y, z])
3002}
3003
3004/// Extracts an `Arc<Scene3D>` from a `<Canvas3D>` or viewport [`NodeBlueprint`]:
3005/// returns a zero-copy `Arc::clone` when an explicit `Attribute::ScenePayload` is attached
3006/// with no declarative child overrides, or compiles declarative children when present.
3007pub fn extract_scene3d_arc_from_blueprint(
3008    canvas_node: &NodeBlueprint,
3009) -> Option<std::sync::Arc<Scene3D>> {
3010    let NodeBlueprint::Element {
3011        attributes,
3012        children,
3013        ..
3014    } = canvas_node
3015    else {
3016        return None;
3017    };
3018
3019    let mut payload_scene: Option<std::sync::Arc<Scene3D>> = None;
3020    for attr in attributes {
3021        if let strata_dom::Attribute::ScenePayload(any) = attr {
3022            if let Ok(arc_scene) = any.clone().downcast::<Scene3D>() {
3023                payload_scene = Some(arc_scene);
3024                break;
3025            }
3026            if let Some(nested_arc) = any.downcast_ref::<std::sync::Arc<Scene3D>>() {
3027                payload_scene = Some(std::sync::Arc::clone(nested_arc));
3028                break;
3029            }
3030        }
3031    }
3032
3033    if let Some(arc_scene) = payload_scene {
3034        if children.is_empty() {
3035            return Some(arc_scene);
3036        }
3037        return Some(std::sync::Arc::new(compile_scene3d_from_blueprint(
3038            canvas_node,
3039        )));
3040    }
3041
3042    Some(std::sync::Arc::new(compile_scene3d_from_blueprint(
3043        canvas_node,
3044    )))
3045}
3046
3047/// Compiles a `<Canvas3D>` blueprint subtree (including any attached programmatic `ScenePayload`)
3048/// into a populated [`Scene3D`] instance.
3049pub fn compile_scene3d_from_blueprint(canvas_node: &NodeBlueprint) -> Scene3D {
3050    let (attributes, children) = match canvas_node {
3051        NodeBlueprint::Element {
3052            attributes,
3053            children,
3054            ..
3055        } => (attributes, children),
3056        _ => return Scene3D::new(),
3057    };
3058
3059    let mut scene = attributes
3060        .iter()
3061        .find_map(|attr| match attr {
3062            strata_dom::Attribute::ScenePayload(any) => {
3063                any.downcast_ref::<Scene3D>().cloned().or_else(|| {
3064                    any.downcast_ref::<std::sync::Arc<Scene3D>>()
3065                        .map(|a| (**a).clone())
3066                })
3067            }
3068            _ => None,
3069        })
3070        .unwrap_or_default();
3071
3072    for child in children {
3073        if let NodeBlueprint::Element {
3074            tag,
3075            attributes,
3076            children: mesh_children,
3077            ..
3078        } = child
3079        {
3080            match tag {
3081                Tag::Custom("PerspectiveCamera") => {
3082                    let fov = get_3d_attr(attributes, "data-fov")
3083                        .and_then(|v| v.parse().ok())
3084                        .unwrap_or(60.0);
3085                    let near = get_3d_attr(attributes, "data-near")
3086                        .and_then(|v| v.parse().ok())
3087                        .unwrap_or(0.1);
3088                    let far = get_3d_attr(attributes, "data-far")
3089                        .and_then(|v| v.parse().ok())
3090                        .unwrap_or(1000.0);
3091                    let position = get_3d_attr(attributes, "data-position")
3092                        .and_then(parse_3d_vec3)
3093                        .unwrap_or([0.0, 2.0, 5.0]);
3094                    let target = get_3d_attr(attributes, "data-target")
3095                        .and_then(parse_3d_vec3)
3096                        .unwrap_or([0.0, 0.0, 0.0]);
3097                    scene.camera = Camera3D::Perspective {
3098                        fov_horizontal_deg: fov,
3099                        near,
3100                        far,
3101                        position,
3102                        target,
3103                    };
3104                }
3105                Tag::Custom("OrthographicCamera") => {
3106                    let left = get_3d_attr(attributes, "data-left")
3107                        .and_then(|v| v.parse().ok())
3108                        .unwrap_or(-5.0);
3109                    let right = get_3d_attr(attributes, "data-right")
3110                        .and_then(|v| v.parse().ok())
3111                        .unwrap_or(5.0);
3112                    let top = get_3d_attr(attributes, "data-top")
3113                        .and_then(|v| v.parse().ok())
3114                        .unwrap_or(5.0);
3115                    let bottom = get_3d_attr(attributes, "data-bottom")
3116                        .and_then(|v| v.parse().ok())
3117                        .unwrap_or(-5.0);
3118                    let near = get_3d_attr(attributes, "data-near")
3119                        .and_then(|v| v.parse().ok())
3120                        .unwrap_or(0.1);
3121                    let far = get_3d_attr(attributes, "data-far")
3122                        .and_then(|v| v.parse().ok())
3123                        .unwrap_or(1000.0);
3124                    let position = get_3d_attr(attributes, "data-position")
3125                        .and_then(parse_3d_vec3)
3126                        .unwrap_or([0.0, 2.0, 5.0]);
3127                    let target = get_3d_attr(attributes, "data-target")
3128                        .and_then(parse_3d_vec3)
3129                        .unwrap_or([0.0, 0.0, 0.0]);
3130                    scene.camera = Camera3D::Orthographic {
3131                        left,
3132                        right,
3133                        top,
3134                        bottom,
3135                        near,
3136                        far,
3137                        position,
3138                        target,
3139                    };
3140                }
3141                Tag::Custom("AmbientLight") => {
3142                    let color_str = get_3d_attr(attributes, "data-color").unwrap_or("#ffffff");
3143                    let color = strata_style::parse_color(color_str).unwrap_or(Color::WHITE);
3144                    let intensity = get_3d_attr(attributes, "data-intensity")
3145                        .and_then(|v| v.parse().ok())
3146                        .unwrap_or(1.0);
3147                    scene.add_light(Light3D::Ambient { color, intensity });
3148                }
3149                Tag::Custom("DirectionalLight") => {
3150                    let pos = get_3d_attr(attributes, "data-position")
3151                        .and_then(parse_3d_vec3)
3152                        .unwrap_or([5.0, 10.0, 7.0]);
3153                    let color_str = get_3d_attr(attributes, "data-color").unwrap_or("#ffffff");
3154                    let color = strata_style::parse_color(color_str).unwrap_or(Color::WHITE);
3155                    let intensity = get_3d_attr(attributes, "data-intensity")
3156                        .and_then(|v| v.parse().ok())
3157                        .unwrap_or(1.0);
3158                    let cast_shadow = get_3d_attr(attributes, "data-cast-shadow")
3159                        .and_then(|v| v.parse().ok())
3160                        .unwrap_or(false);
3161                    scene.add_light(Light3D::Directional {
3162                        position: pos,
3163                        color,
3164                        intensity,
3165                        cast_shadow,
3166                    });
3167                }
3168                Tag::Custom("PointLight") => {
3169                    let pos = get_3d_attr(attributes, "data-position")
3170                        .and_then(parse_3d_vec3)
3171                        .unwrap_or([0.0, 2.0, 0.0]);
3172                    let color_str = get_3d_attr(attributes, "data-color").unwrap_or("#ffffff");
3173                    let color = strata_style::parse_color(color_str).unwrap_or(Color::WHITE);
3174                    let intensity = get_3d_attr(attributes, "data-intensity")
3175                        .and_then(|v| v.parse().ok())
3176                        .unwrap_or(1.0);
3177                    let distance = get_3d_attr(attributes, "data-distance")
3178                        .and_then(|v| v.parse().ok())
3179                        .unwrap_or(10.0);
3180                    scene.add_light(Light3D::Point {
3181                        position: pos,
3182                        color,
3183                        intensity,
3184                        distance,
3185                    });
3186                }
3187                Tag::Custom("Mesh") => {
3188                    let position = get_3d_attr(attributes, "data-position")
3189                        .and_then(parse_3d_vec3)
3190                        .unwrap_or([0.0, 0.0, 0.0]);
3191                    let rotation = get_3d_attr(attributes, "data-rotation")
3192                        .and_then(parse_3d_vec3)
3193                        .unwrap_or([0.0, 0.0, 0.0]);
3194                    let scale = get_3d_attr(attributes, "data-scale")
3195                        .and_then(parse_3d_vec3)
3196                        .unwrap_or([1.0, 1.0, 1.0]);
3197                    let transform = Transform3D {
3198                        position,
3199                        rotation,
3200                        scale,
3201                    };
3202
3203                    let mut geometry = Geometry3D::Box {
3204                        width: 1.0,
3205                        height: 1.0,
3206                        depth: 1.0,
3207                    };
3208                    let mut material = Material3D::default();
3209
3210                    for sub in mesh_children {
3211                        if let NodeBlueprint::Element {
3212                            tag: sub_tag,
3213                            attributes: sub_attrs,
3214                            ..
3215                        } = sub
3216                        {
3217                            match sub_tag {
3218                                Tag::Custom("BoxGeometry") => {
3219                                    let width = get_3d_attr(sub_attrs, "data-width")
3220                                        .and_then(|v| v.parse().ok())
3221                                        .unwrap_or(1.0);
3222                                    let height = get_3d_attr(sub_attrs, "data-height")
3223                                        .and_then(|v| v.parse().ok())
3224                                        .unwrap_or(1.0);
3225                                    let depth = get_3d_attr(sub_attrs, "data-depth")
3226                                        .and_then(|v| v.parse().ok())
3227                                        .unwrap_or(1.0);
3228                                    geometry = Geometry3D::Box {
3229                                        width,
3230                                        height,
3231                                        depth,
3232                                    };
3233                                }
3234                                Tag::Custom("SphereGeometry") => {
3235                                    let radius = get_3d_attr(sub_attrs, "data-radius")
3236                                        .and_then(|v| v.parse().ok())
3237                                        .unwrap_or(1.0);
3238                                    let width_segments =
3239                                        get_3d_attr(sub_attrs, "data-width-segments")
3240                                            .and_then(|v| v.parse().ok())
3241                                            .unwrap_or(16);
3242                                    let height_segments =
3243                                        get_3d_attr(sub_attrs, "data-height-segments")
3244                                            .and_then(|v| v.parse().ok())
3245                                            .unwrap_or(16);
3246                                    geometry = Geometry3D::Sphere {
3247                                        radius,
3248                                        width_segments,
3249                                        height_segments,
3250                                    };
3251                                }
3252                                Tag::Custom("PlaneGeometry") => {
3253                                    let width = get_3d_attr(sub_attrs, "data-width")
3254                                        .and_then(|v| v.parse().ok())
3255                                        .unwrap_or(1.0);
3256                                    let height = get_3d_attr(sub_attrs, "data-height")
3257                                        .and_then(|v| v.parse().ok())
3258                                        .unwrap_or(1.0);
3259                                    geometry = Geometry3D::Plane { width, height };
3260                                }
3261                                Tag::Custom("CylinderGeometry") => {
3262                                    let radius_top = get_3d_attr(sub_attrs, "data-radius-top")
3263                                        .and_then(|v| v.parse().ok())
3264                                        .unwrap_or(1.0);
3265                                    let radius_bottom =
3266                                        get_3d_attr(sub_attrs, "data-radius-bottom")
3267                                            .and_then(|v| v.parse().ok())
3268                                            .unwrap_or(1.0);
3269                                    let height = get_3d_attr(sub_attrs, "data-height")
3270                                        .and_then(|v| v.parse().ok())
3271                                        .unwrap_or(1.0);
3272                                    let radial_segments =
3273                                        get_3d_attr(sub_attrs, "data-radial-segments")
3274                                            .and_then(|v| v.parse().ok())
3275                                            .unwrap_or(16);
3276                                    geometry = Geometry3D::Cylinder {
3277                                        radius_top,
3278                                        radius_bottom,
3279                                        height,
3280                                        radial_segments,
3281                                    };
3282                                }
3283                                Tag::Custom("StandardMaterial") => {
3284                                    let color_str =
3285                                        get_3d_attr(sub_attrs, "data-color").unwrap_or("#ffffff");
3286                                    let color = strata_style::parse_color(color_str)
3287                                        .unwrap_or(Color::WHITE);
3288                                    let roughness = get_3d_attr(sub_attrs, "data-roughness")
3289                                        .and_then(|v| v.parse().ok())
3290                                        .unwrap_or(0.5);
3291                                    let metalness = get_3d_attr(sub_attrs, "data-metalness")
3292                                        .and_then(|v| v.parse().ok())
3293                                        .unwrap_or(0.0);
3294                                    material = Material3D::Standard {
3295                                        color,
3296                                        roughness,
3297                                        metalness,
3298                                        emissive: None,
3299                                    };
3300                                }
3301                                Tag::Custom("ShaderMaterial") => {
3302                                    let glsl =
3303                                        get_3d_attr(sub_attrs, "data-glsl").map(|s| s.to_string());
3304                                    let time = get_3d_attr(sub_attrs, "data-time")
3305                                        .and_then(|v| v.parse().ok())
3306                                        .unwrap_or(0.0);
3307                                    let mut uniforms = BTreeMap::new();
3308                                    uniforms.insert("u_time".to_string(), time);
3309                                    material = Material3D::Shader {
3310                                        vertex_shader: None,
3311                                        fragment_shader: None,
3312                                        glsl_fragment: glsl,
3313                                        uniforms,
3314                                    };
3315                                }
3316                                _ => {}
3317                            }
3318                        }
3319                    }
3320
3321                    scene.add_mesh(Mesh3D {
3322                        geometry,
3323                        material,
3324                        transform,
3325                    });
3326                }
3327                _ => {}
3328            }
3329        }
3330    }
3331
3332    scene
3333}