euv-core 0.52.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Gimbal-lock-free 3D world-space transform backed by a unit Hamilton quaternion (`position`, `rotation`, `scale`).
#[derive(Clone, Copy, Data, Debug, PartialEq)]
pub struct Transform3D {
    /// World-space translation `(x, y, z)`.
    #[get(type(copy))]
    pub(crate) position: Vec3,
    /// Unit Hamilton quaternion orientation `(x, y, z, w)`.
    #[get(type(copy))]
    pub(crate) rotation: Quat,
    /// Scale multiplier along `(x, y, z)`.
    #[get(type(copy))]
    pub(crate) scale: Vec3,
}

/// Multi-camera scene registry entry supporting both Perspective and Orthographic Blender/glTF cameras.
#[derive(Clone, Data, Debug, PartialEq)]
pub struct SceneCamera3D {
    /// Human-readable camera label.
    pub(crate) name: String,
    /// Optional owning node index inside `World3D::scene_graph`.
    #[get(type(copy))]
    pub(crate) node_id: Option<u32>,
    /// World-space camera eye position.
    #[get(type(copy))]
    pub(crate) position: Vec3,
    /// World-space camera orientation quaternion (glTF camera looks along local `-Z`, up `+Y`).
    #[get(type(copy))]
    pub(crate) rotation: Quat,
    /// Perspective or orthographic projection parameters.
    #[get(type(copy))]
    pub(crate) projection: GltfCameraProjection,
}

/// Fluent descriptor for spawning a `SceneObject3D` into `World3D`.
#[derive(Clone, Data, Debug, PartialEq)]
pub struct SpawnObjectDesc {
    /// Human-readable object label.
    pub(crate) name: String,
    /// Registered mesh identifier from `World3D::register_mesh`.
    #[get(type(copy))]
    pub(crate) mesh_id: usize,
    /// World-space TRS transform.
    #[get(type(copy))]
    pub(crate) transform: Transform3D,
    /// Surface PBR material.
    #[get(type(copy))]
    pub(crate) material: PbrMaterial,
    /// Whether this object casts ray-traced shadows and appears in BVH reflections.
    #[get(type(copy))]
    pub(crate) ray_trace_caster: bool,
    /// Whether this object participates in solid vehicle and camera collision detection.
    #[get(type(copy))]
    pub(crate) solid_collider: bool,
    /// Continuous spin speed in radians/sec.
    #[get(type(copy))]
    pub(crate) spin_speed: f32,
    /// Whether this object moves dynamically and belongs in the incrementally refitted dynamic BVH.
    #[get(type(copy))]
    pub(crate) is_dynamic: bool,
}

/// Fluent descriptor for importing a 3D `.obj` or `.gltf` model into `World3D`.
#[derive(Clone, Data, Debug, PartialEq)]
pub struct ImportModelDesc {
    /// Source model interchange format.
    #[get(type(copy))]
    pub(crate) format: ModelFormat,
    /// Raw `.obj` or `.gltf` text content.
    pub(crate) source: String,
    /// World-space placement transform.
    #[get(type(copy))]
    pub(crate) transform: Transform3D,
    /// Fallback PBR material when source omits material definitions.
    #[get(type(copy))]
    pub(crate) fallback_material: PbrMaterial,
    /// Optional continuous Y-spin speed in radians/sec.
    #[get(type(copy))]
    pub(crate) spin_speed: f32,
}

/// Instanced 3D scene object placed inside an open-world chunk.
#[derive(Clone, Data, Debug, PartialEq)]
pub struct SceneObject3D {
    /// Human-readable object label.
    pub(crate) name: String,
    /// Index into `World3D::mesh_library` enabling GPU instancing batching.
    #[get(type(copy))]
    pub(crate) mesh_id: usize,
    /// World-space TRS transform.
    #[get(type(copy))]
    pub(crate) transform: Transform3D,
    /// Material override (or default mesh material).
    #[get(type(copy))]
    pub(crate) material: PbrMaterial,
    /// Cached world-space axis-aligned bounding box for O(1) frustum culling and chunk streaming.
    #[get(type(copy))]
    pub(crate) world_bounds: AxisAlignedBox3D,
    /// Spatial open-world chunk coordinate `(chunk_x, chunk_z)`.
    #[get(type(copy))]
    pub(crate) chunk_coord: (i32, i32),
    /// Whether this object casts ray-traced shadows and appears in BVH reflections.
    #[get(type(copy))]
    pub(crate) ray_trace_caster: bool,
    /// Whether this object participates in solid vehicle and camera collision detection.
    #[get(type(copy))]
    pub(crate) solid_collider: bool,
    /// Continuous spin speed in radians/sec for animated hero models or props.
    #[get(type(copy))]
    pub(crate) spin_speed: f32,
    /// Whether this object belongs to the dynamic incrementally-refitted BVH rather than the static world BVH.
    #[get(type(copy))]
    pub(crate) is_dynamic: bool,
    /// Discontinuity counter incremented on teleports so snapshot interpolation snaps cleanly.
    #[get(type(copy))]
    pub(crate) teleport_epoch: u32,
    /// Optional owning hierarchical node index inside `World3D::scene_graph`.
    #[get(type(copy))]
    pub(crate) node_id: Option<u32>,
    /// Optional index into `World3D::principled_materials` for full Principled BSDF shading.
    #[get(type(copy))]
    pub(crate) principled_material_id: Option<u32>,
    /// Optional index into `World3D::skins` for armature LBS/DQS vertex deformation.
    #[get(type(copy))]
    pub(crate) skin_id: Option<u32>,
}

/// Primary sun/moon directional light and atmospheric sky parameters.
#[derive(Clone, Copy, Data, Debug, PartialEq)]
pub struct DirectionalLight3D {
    /// Normalized direction pointing toward the sun.
    #[get(type(copy))]
    pub(crate) direction: Vec3,
    /// Linear HDR sun radiance color.
    #[get(type(copy))]
    pub(crate) color: Vec3,
    /// Ambient sky zenith color.
    #[get(type(copy))]
    pub(crate) sky_zenith: Vec3,
    /// Ambient sky horizon and volumetric fog color.
    #[get(type(copy))]
    pub(crate) sky_horizon: Vec3,
    /// Time of day in `[0.0, 24.0]` hours.
    #[get(type(copy))]
    pub(crate) time_of_day: f32,
}

/// Oriented bounding box in 3D space used for tight rotated collider narrow-phase tests.
#[derive(Clone, Copy, Data, Debug, New, PartialEq)]
pub struct OrientedBox3D {
    /// Box center position in target coordinate space.
    #[get(type(copy))]
    pub(crate) center: Vec3,
    /// Orthonormal local X, Y, and Z basis axes.
    #[get(type(copy))]
    pub(crate) axes: [Vec3; 3],
    /// Positive half-extents along each local axis.
    #[get(type(copy))]
    pub(crate) half_extents: Vec3,
}

/// Real-mesh narrow-phase collision contact reported against a solid `SceneObject3D` triangle.
#[derive(Clone, Copy, Data, Debug, New, PartialEq)]
pub struct MeshCollisionHit3D {
    /// Colliding obstacle index inside `World3D::objects`.
    #[get(type(copy))]
    pub(crate) object_index: usize,
    /// Unit world-space separation normal pointing toward the moving collider.
    #[get(type(copy))]
    pub(crate) normal: Vec3,
    /// Positive penetration depth along `normal` in meters.
    #[get(type(copy))]
    pub(crate) penetration: f32,
    /// World-space contact point on the colliding triangle surface.
    #[get(type(copy))]
    pub(crate) contact_point: Vec3,
}

/// Object-space raytracing instance descriptor enabling exact interpolated dynamic shadows and reflections with zero BVH rebuilds per VSync.
#[derive(Clone, Copy, Debug)]
pub(crate) struct DynamicRayInstance {
    /// Owning scene object index in `World3D::objects`.
    pub(crate) obj_idx: usize,
    /// Registered mesh index referencing `World3D::mesh_local_bvhs`.
    pub(crate) mesh_id: usize,
    /// World-space axis-aligned bounding box for O(1) miss rejection before transforming rays into object space.
    pub(crate) world_bounds: AxisAlignedBox3D,
    /// Exact analytical inverse model matrix (`S^-1 * R^T * T^-1`) mapping world rays to local space.
    pub(crate) inv_model: Mat4,
    /// Inverse-transpose 3x3 normal basis mapping local hit normals back to world space.
    pub(crate) normal_basis: [Vec3; 3],
    /// Surface PBR material override for this instance.
    pub(crate) material: PbrMaterial,
}

/// Complete open-world 3D scene graph with mesh instancing library, chunk streaming, and BVH acceleration.
#[derive(Clone, Data, Debug)]
pub struct World3D {
    /// Shared LOD mesh asset library referenced by `SceneObject3D::mesh_id`.
    pub(crate) mesh_library: Vec<MeshLodChain>,
    /// All world objects partitioned into open-world chunks.
    pub(crate) objects: Vec<SceneObject3D>,
    /// Active 3D perspective camera.
    #[get(type(copy))]
    pub(crate) camera: Camera3D,
    /// Active directional sun/sky lighting.
    #[get(type(copy))]
    pub(crate) sun: DirectionalLight3D,
    /// Flat BVH built over static world-space ray-trace casters (rebuilt only on static geometry edits).
    pub(crate) bvh: Bvh3D,
    /// Separate flat BVH over moving/dynamic ray-trace casters supporting O(N) incremental bottom-up refits.
    pub(crate) dynamic_bvh: Bvh3D,
    /// Lazily constructed local-space BVH4/BVH8 cache indexed by `mesh_id` for zero-rebuild object-space dynamic raytracing.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) mesh_local_bvhs: Vec<Option<Bvh3D>>,
    /// Active object-space dynamic raytracing instances updated via inverse interpolated `Mat4` without BVH rebuilds.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) dynamic_instances: Vec<DynamicRayInstance>,
    /// Dirty flag triggering static BVH rebuild when static casters are added or modified.
    #[get(type(copy))]
    pub(crate) bvh_dirty: bool,
    /// Dirty flag triggering dynamic BVH incremental refit or rebuild when moving casters update.
    #[get(type(copy))]
    pub(crate) dynamic_bvh_dirty: bool,
    /// Topology change flag forcing a fresh dynamic BVH SAH build rather than an in-place refit.
    #[get(type(copy))]
    pub(crate) dynamic_topology_dirty: bool,
    /// Total static BVH full rebuilds executed.
    #[get(type(copy))]
    pub(crate) static_bvh_rebuilds: u64,
    /// Total zero-allocation incremental dynamic BVH refits executed.
    #[get(type(copy))]
    pub(crate) dynamic_bvh_refits: u64,
    /// Total full dynamic BVH rebuilds executed (topology changes or SAH quality resets).
    #[get(type(copy))]
    pub(crate) dynamic_bvh_rebuilds: u64,
    /// Monotonic revision incremented only when 3D world transforms, camera, or lighting change (isolated from HUD dirtiness).
    #[get(type(copy))]
    pub(crate) world_revision: u64,
    /// Reusable scratch buffer holding transformed dynamic caster triangles during incremental BVH refits.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) dynamic_tris_scratch: Vec<BvhTriangle>,
    /// Open-world chunk size in meters (`64.0m` per city block).
    #[get(type(copy))]
    pub(crate) chunk_size: f32,
    /// Index of the drivable player vehicle object if spawned.
    #[get(skip)]
    pub(crate) player_vehicle_index: Option<usize>,
    /// Total imported external 3D models (`.obj` / `.gltf`).
    #[get(type(copy))]
    pub(crate) imported_model_count: usize,
    /// Active 3D camera mode index (`0=Chase`, `1=Hood`, `2=Orbit`, `3=Aerial`, `4=FreeFly`, `5=CinematicDolly`).
    #[get(type(copy))]
    pub(crate) camera_mode: u8,
    /// Continuous orbit angle in radians used for `Orbit` and `CinematicDolly` modes.
    #[get(type(copy))]
    pub(crate) camera_orbit_rad: f32,
    /// Dynamic world-space omnidirectional point lights binned by `LightClusterGrid3D`.
    pub(crate) point_lights: Vec<PointLight3D>,
    /// Dynamic world-space spotlights (vehicle headlights, streetlamps) binned by `LightClusterGrid3D`.
    pub(crate) spot_lights: Vec<SpotLight3D>,
    /// Zero-allocation 3D Niagara particle system for sparks, exhaust trails, and atmospheric effects.
    pub(crate) niagara: NiagaraSystem3D,
    /// Active atmospheric mood preset (`0=Sunset, 1=RainyNight, 2=Noon, 3=Midnight`).
    #[get(type(copy))]
    pub(crate) atmosphere_preset: u8,
    /// Cruising AI traffic vehicles `(object_index, velocity_z_mps, z_min, z_max)` animated smoothly on outer boulevard lanes.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) traffic_vehicles: Vec<(usize, f32, f32, f32)>,
    /// Monotonic simulation clock in seconds driving continuous animated ocean waves, caustics, and shoreline foam.
    #[get(type(copy))]
    pub(crate) world_time_secs: f32,
    /// Hierarchical Blender/glTF scene graph with topological propagation and 64-bit Collections visibility.
    pub(crate) scene_graph: SceneGraph3D,
    /// Full 1:1 Blender Principled BSDF materials referenced by `SceneObject3D::principled_material_id`.
    pub(crate) principled_materials: Vec<PrincipledMaterial3D>,
    /// Mipmapped 2D texture pool referenced by `PrincipledMaterial3D` slots.
    pub(crate) textures: Vec<Texture2D3D>,
    /// Active armature skins evaluated against `scene_graph` joint world matrices.
    pub(crate) skins: Vec<Skin3D>,
    /// Multi-layer glTF/NLA animation mixer ticking directly into `scene_graph`.
    pub(crate) animation_mixer: AnimationMixer3D,
    /// Optional precomputed SH9 + octahedral specular + BRDF LUT IBL environment.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) environment_ibl: Option<EnvironmentIbl3D>,
    /// Physically based rectangular and disk Blender area lights.
    pub(crate) area_lights: Vec<AreaLight3D>,
    /// Imported and user-registered multi-camera list supporting Perspective and Orthographic projections.
    pub(crate) scene_cameras: Vec<SceneCamera3D>,
    /// Optional active camera index inside `scene_cameras` (`None` uses primary `camera`).
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) active_scene_camera: Option<usize>,
    /// Mapping from `scene_graph` node index to spawned `World3D::objects` index for O(1) transform synchronization.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) node_object_map: Vec<Option<usize>>,
    /// Reusable pre-allocated skinning and shape-key scratch arena for zero steady-state heap allocations.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) skin_scratch: SkinPaletteScratch3D,
    /// Per-object deformed mesh cache aligned with `objects` holding live morphed and skinned vertices.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) deformed_meshes: Vec<Option<Mesh3D>>,
    /// Selects Blender AgX filmic view transform (`true`) or ACES Filmic (`false`) during CPU/GPU tonemapping.
    #[get(type(copy))]
    pub(crate) use_agx_tonemap: bool,
    /// Persistent flat scratch buffers eliminating per-frame `Vec<Vec<_>>` allocations and O(N*M) pose scans during GPU pass building.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) gpu_pass_scratch: World3dGpuPassScratch,
}

/// Persistent flat scratch buffers reused by `World3D::build_gpu_scene_pass_into` for zero-allocation O(N) instanced batch building.
#[derive(Clone, Debug, Default)]
pub(crate) struct World3dGpuPassScratch {
    /// Generation-stamped dense lookup epochs indexed directly by `object_index` for O(1) dynamic pose lookup and O(1) clear.
    pub(crate) dynamic_pose_epochs: Vec<u32>,
    /// Interpolated dynamic transforms aligned 1:1 with `dynamic_pose_epochs`.
    pub(crate) dynamic_pose_transforms: Vec<Transform3D>,
    /// Monotonic epoch counter incremented per pass (`0` triggers full reset on wrap).
    pub(crate) current_epoch: u32,
    /// Per-mesh visible instance counts indexed by `mesh_id`.
    pub(crate) mesh_counts: Vec<u32>,
    /// Per-mesh scatter write cursors indexed by `mesh_id`.
    pub(crate) mesh_cursors: Vec<u32>,
    /// Flat single-allocation gather buffer holding visible `(mesh_id, instance)` pairs before O(N) counting-sort scatter.
    pub(crate) visible_scratch: Vec<(u32, GpuWorld3dInstance)>,
}