Skip to main content

euv_core/game/engine3d/world/
struct.rs

1use super::*;
2
3/// Gimbal-lock-free 3D world-space transform backed by a unit Hamilton quaternion (`position`, `rotation`, `scale`).
4#[derive(Clone, Copy, Data, Debug, PartialEq)]
5pub struct Transform3D {
6    /// World-space translation `(x, y, z)`.
7    #[get(type(copy))]
8    pub(crate) position: Vec3,
9    /// Unit Hamilton quaternion orientation `(x, y, z, w)`.
10    #[get(type(copy))]
11    pub(crate) rotation: Quat,
12    /// Scale multiplier along `(x, y, z)`.
13    #[get(type(copy))]
14    pub(crate) scale: Vec3,
15}
16
17/// Multi-camera scene registry entry supporting both Perspective and Orthographic Blender/glTF cameras.
18#[derive(Clone, Data, Debug, PartialEq)]
19pub struct SceneCamera3D {
20    /// Human-readable camera label.
21    pub(crate) name: String,
22    /// Optional owning node index inside `World3D::scene_graph`.
23    #[get(type(copy))]
24    pub(crate) node_id: Option<u32>,
25    /// World-space camera eye position.
26    #[get(type(copy))]
27    pub(crate) position: Vec3,
28    /// World-space camera orientation quaternion (glTF camera looks along local `-Z`, up `+Y`).
29    #[get(type(copy))]
30    pub(crate) rotation: Quat,
31    /// Perspective or orthographic projection parameters.
32    #[get(type(copy))]
33    pub(crate) projection: GltfCameraProjection,
34}
35
36/// Fluent descriptor for spawning a `SceneObject3D` into `World3D`.
37#[derive(Clone, Data, Debug, PartialEq)]
38pub struct SpawnObjectDesc {
39    /// Human-readable object label.
40    pub(crate) name: String,
41    /// Registered mesh identifier from `World3D::register_mesh`.
42    #[get(type(copy))]
43    pub(crate) mesh_id: usize,
44    /// World-space TRS transform.
45    #[get(type(copy))]
46    pub(crate) transform: Transform3D,
47    /// Surface PBR material.
48    #[get(type(copy))]
49    pub(crate) material: PbrMaterial,
50    /// Whether this object casts ray-traced shadows and appears in BVH reflections.
51    #[get(type(copy))]
52    pub(crate) ray_trace_caster: bool,
53    /// Whether this object participates in solid vehicle and camera collision detection.
54    #[get(type(copy))]
55    pub(crate) solid_collider: bool,
56    /// Continuous spin speed in radians/sec.
57    #[get(type(copy))]
58    pub(crate) spin_speed: f32,
59    /// Whether this object moves dynamically and belongs in the incrementally refitted dynamic BVH.
60    #[get(type(copy))]
61    pub(crate) is_dynamic: bool,
62}
63
64/// Fluent descriptor for importing a 3D `.obj` or `.gltf` model into `World3D`.
65#[derive(Clone, Data, Debug, PartialEq)]
66pub struct ImportModelDesc {
67    /// Source model interchange format.
68    #[get(type(copy))]
69    pub(crate) format: ModelFormat,
70    /// Raw `.obj` or `.gltf` text content.
71    pub(crate) source: String,
72    /// World-space placement transform.
73    #[get(type(copy))]
74    pub(crate) transform: Transform3D,
75    /// Fallback PBR material when source omits material definitions.
76    #[get(type(copy))]
77    pub(crate) fallback_material: PbrMaterial,
78    /// Optional continuous Y-spin speed in radians/sec.
79    #[get(type(copy))]
80    pub(crate) spin_speed: f32,
81}
82
83/// Instanced 3D scene object placed inside an open-world chunk.
84#[derive(Clone, Data, Debug, PartialEq)]
85pub struct SceneObject3D {
86    /// Human-readable object label.
87    pub(crate) name: String,
88    /// Index into `World3D::mesh_library` enabling GPU instancing batching.
89    #[get(type(copy))]
90    pub(crate) mesh_id: usize,
91    /// World-space TRS transform.
92    #[get(type(copy))]
93    pub(crate) transform: Transform3D,
94    /// Material override (or default mesh material).
95    #[get(type(copy))]
96    pub(crate) material: PbrMaterial,
97    /// Cached world-space axis-aligned bounding box for O(1) frustum culling and chunk streaming.
98    #[get(type(copy))]
99    pub(crate) world_bounds: AxisAlignedBox3D,
100    /// Spatial open-world chunk coordinate `(chunk_x, chunk_z)`.
101    #[get(type(copy))]
102    pub(crate) chunk_coord: (i32, i32),
103    /// Whether this object casts ray-traced shadows and appears in BVH reflections.
104    #[get(type(copy))]
105    pub(crate) ray_trace_caster: bool,
106    /// Whether this object participates in solid vehicle and camera collision detection.
107    #[get(type(copy))]
108    pub(crate) solid_collider: bool,
109    /// Continuous spin speed in radians/sec for animated hero models or props.
110    #[get(type(copy))]
111    pub(crate) spin_speed: f32,
112    /// Whether this object belongs to the dynamic incrementally-refitted BVH rather than the static world BVH.
113    #[get(type(copy))]
114    pub(crate) is_dynamic: bool,
115    /// Discontinuity counter incremented on teleports so snapshot interpolation snaps cleanly.
116    #[get(type(copy))]
117    pub(crate) teleport_epoch: u32,
118    /// Optional owning hierarchical node index inside `World3D::scene_graph`.
119    #[get(type(copy))]
120    pub(crate) node_id: Option<u32>,
121    /// Optional index into `World3D::principled_materials` for full Principled BSDF shading.
122    #[get(type(copy))]
123    pub(crate) principled_material_id: Option<u32>,
124    /// Optional index into `World3D::skins` for armature LBS/DQS vertex deformation.
125    #[get(type(copy))]
126    pub(crate) skin_id: Option<u32>,
127}
128
129/// Primary sun/moon directional light and atmospheric sky parameters.
130#[derive(Clone, Copy, Data, Debug, PartialEq)]
131pub struct DirectionalLight3D {
132    /// Normalized direction pointing toward the sun.
133    #[get(type(copy))]
134    pub(crate) direction: Vec3,
135    /// Linear HDR sun radiance color.
136    #[get(type(copy))]
137    pub(crate) color: Vec3,
138    /// Ambient sky zenith color.
139    #[get(type(copy))]
140    pub(crate) sky_zenith: Vec3,
141    /// Ambient sky horizon and volumetric fog color.
142    #[get(type(copy))]
143    pub(crate) sky_horizon: Vec3,
144    /// Time of day in `[0.0, 24.0]` hours.
145    #[get(type(copy))]
146    pub(crate) time_of_day: f32,
147}
148
149/// Oriented bounding box in 3D space used for tight rotated collider narrow-phase tests.
150#[derive(Clone, Copy, Data, Debug, New, PartialEq)]
151pub struct OrientedBox3D {
152    /// Box center position in target coordinate space.
153    #[get(type(copy))]
154    pub(crate) center: Vec3,
155    /// Orthonormal local X, Y, and Z basis axes.
156    #[get(type(copy))]
157    pub(crate) axes: [Vec3; 3],
158    /// Positive half-extents along each local axis.
159    #[get(type(copy))]
160    pub(crate) half_extents: Vec3,
161}
162
163/// Real-mesh narrow-phase collision contact reported against a solid `SceneObject3D` triangle.
164#[derive(Clone, Copy, Data, Debug, New, PartialEq)]
165pub struct MeshCollisionHit3D {
166    /// Colliding obstacle index inside `World3D::objects`.
167    #[get(type(copy))]
168    pub(crate) object_index: usize,
169    /// Unit world-space separation normal pointing toward the moving collider.
170    #[get(type(copy))]
171    pub(crate) normal: Vec3,
172    /// Positive penetration depth along `normal` in meters.
173    #[get(type(copy))]
174    pub(crate) penetration: f32,
175    /// World-space contact point on the colliding triangle surface.
176    #[get(type(copy))]
177    pub(crate) contact_point: Vec3,
178}
179
180/// Object-space raytracing instance descriptor enabling exact interpolated dynamic shadows and reflections with zero BVH rebuilds per VSync.
181#[derive(Clone, Copy, Debug)]
182pub(crate) struct DynamicRayInstance {
183    /// Owning scene object index in `World3D::objects`.
184    pub(crate) obj_idx: usize,
185    /// Registered mesh index referencing `World3D::mesh_local_bvhs`.
186    pub(crate) mesh_id: usize,
187    /// World-space axis-aligned bounding box for O(1) miss rejection before transforming rays into object space.
188    pub(crate) world_bounds: AxisAlignedBox3D,
189    /// Exact analytical inverse model matrix (`S^-1 * R^T * T^-1`) mapping world rays to local space.
190    pub(crate) inv_model: Mat4,
191    /// Inverse-transpose 3x3 normal basis mapping local hit normals back to world space.
192    pub(crate) normal_basis: [Vec3; 3],
193    /// Surface PBR material override for this instance.
194    pub(crate) material: PbrMaterial,
195}
196
197/// Complete open-world 3D scene graph with mesh instancing library, chunk streaming, and BVH acceleration.
198#[derive(Clone, Data, Debug)]
199pub struct World3D {
200    /// Shared LOD mesh asset library referenced by `SceneObject3D::mesh_id`.
201    pub(crate) mesh_library: Vec<MeshLodChain>,
202    /// All world objects partitioned into open-world chunks.
203    pub(crate) objects: Vec<SceneObject3D>,
204    /// Active 3D perspective camera.
205    #[get(type(copy))]
206    pub(crate) camera: Camera3D,
207    /// Active directional sun/sky lighting.
208    #[get(type(copy))]
209    pub(crate) sun: DirectionalLight3D,
210    /// Flat BVH built over static world-space ray-trace casters (rebuilt only on static geometry edits).
211    pub(crate) bvh: Bvh3D,
212    /// Separate flat BVH over moving/dynamic ray-trace casters supporting O(N) incremental bottom-up refits.
213    pub(crate) dynamic_bvh: Bvh3D,
214    /// Lazily constructed local-space BVH4/BVH8 cache indexed by `mesh_id` for zero-rebuild object-space dynamic raytracing.
215    #[get(skip)]
216    #[get_mut(skip)]
217    #[set(skip)]
218    pub(crate) mesh_local_bvhs: Vec<Option<Bvh3D>>,
219    /// Active object-space dynamic raytracing instances updated via inverse interpolated `Mat4` without BVH rebuilds.
220    #[get(skip)]
221    #[get_mut(skip)]
222    #[set(skip)]
223    pub(crate) dynamic_instances: Vec<DynamicRayInstance>,
224    /// Dirty flag triggering static BVH rebuild when static casters are added or modified.
225    #[get(type(copy))]
226    pub(crate) bvh_dirty: bool,
227    /// Dirty flag triggering dynamic BVH incremental refit or rebuild when moving casters update.
228    #[get(type(copy))]
229    pub(crate) dynamic_bvh_dirty: bool,
230    /// Topology change flag forcing a fresh dynamic BVH SAH build rather than an in-place refit.
231    #[get(type(copy))]
232    pub(crate) dynamic_topology_dirty: bool,
233    /// Total static BVH full rebuilds executed.
234    #[get(type(copy))]
235    pub(crate) static_bvh_rebuilds: u64,
236    /// Total zero-allocation incremental dynamic BVH refits executed.
237    #[get(type(copy))]
238    pub(crate) dynamic_bvh_refits: u64,
239    /// Total full dynamic BVH rebuilds executed (topology changes or SAH quality resets).
240    #[get(type(copy))]
241    pub(crate) dynamic_bvh_rebuilds: u64,
242    /// Monotonic revision incremented only when 3D world transforms, camera, or lighting change (isolated from HUD dirtiness).
243    #[get(type(copy))]
244    pub(crate) world_revision: u64,
245    /// Reusable scratch buffer holding transformed dynamic caster triangles during incremental BVH refits.
246    #[get(skip)]
247    #[get_mut(skip)]
248    #[set(skip)]
249    pub(crate) dynamic_tris_scratch: Vec<BvhTriangle>,
250    /// Open-world chunk size in meters (`64.0m` per city block).
251    #[get(type(copy))]
252    pub(crate) chunk_size: f32,
253    /// Index of the drivable player vehicle object if spawned.
254    #[get(skip)]
255    pub(crate) player_vehicle_index: Option<usize>,
256    /// Total imported external 3D models (`.obj` / `.gltf`).
257    #[get(type(copy))]
258    pub(crate) imported_model_count: usize,
259    /// Active 3D camera mode index (`0=Chase`, `1=Hood`, `2=Orbit`, `3=Aerial`, `4=FreeFly`, `5=CinematicDolly`).
260    #[get(type(copy))]
261    pub(crate) camera_mode: u8,
262    /// Continuous orbit angle in radians used for `Orbit` and `CinematicDolly` modes.
263    #[get(type(copy))]
264    pub(crate) camera_orbit_rad: f32,
265    /// Dynamic world-space omnidirectional point lights binned by `LightClusterGrid3D`.
266    pub(crate) point_lights: Vec<PointLight3D>,
267    /// Dynamic world-space spotlights (vehicle headlights, streetlamps) binned by `LightClusterGrid3D`.
268    pub(crate) spot_lights: Vec<SpotLight3D>,
269    /// Zero-allocation 3D Niagara particle system for sparks, exhaust trails, and atmospheric effects.
270    pub(crate) niagara: NiagaraSystem3D,
271    /// Active atmospheric mood preset (`0=Sunset, 1=RainyNight, 2=Noon, 3=Midnight`).
272    #[get(type(copy))]
273    pub(crate) atmosphere_preset: u8,
274    /// Cruising AI traffic vehicles `(object_index, velocity_z_mps, z_min, z_max)` animated smoothly on outer boulevard lanes.
275    #[get(skip)]
276    #[get_mut(skip)]
277    #[set(skip)]
278    pub(crate) traffic_vehicles: Vec<(usize, f32, f32, f32)>,
279    /// Monotonic simulation clock in seconds driving continuous animated ocean waves, caustics, and shoreline foam.
280    #[get(type(copy))]
281    pub(crate) world_time_secs: f32,
282    /// Hierarchical Blender/glTF scene graph with topological propagation and 64-bit Collections visibility.
283    pub(crate) scene_graph: SceneGraph3D,
284    /// Full 1:1 Blender Principled BSDF materials referenced by `SceneObject3D::principled_material_id`.
285    pub(crate) principled_materials: Vec<PrincipledMaterial3D>,
286    /// Mipmapped 2D texture pool referenced by `PrincipledMaterial3D` slots.
287    pub(crate) textures: Vec<Texture2D3D>,
288    /// Active armature skins evaluated against `scene_graph` joint world matrices.
289    pub(crate) skins: Vec<Skin3D>,
290    /// Multi-layer glTF/NLA animation mixer ticking directly into `scene_graph`.
291    pub(crate) animation_mixer: AnimationMixer3D,
292    /// Optional precomputed SH9 + octahedral specular + BRDF LUT IBL environment.
293    #[get(skip)]
294    #[get_mut(skip)]
295    #[set(skip)]
296    pub(crate) environment_ibl: Option<EnvironmentIbl3D>,
297    /// Physically based rectangular and disk Blender area lights.
298    pub(crate) area_lights: Vec<AreaLight3D>,
299    /// Imported and user-registered multi-camera list supporting Perspective and Orthographic projections.
300    pub(crate) scene_cameras: Vec<SceneCamera3D>,
301    /// Optional active camera index inside `scene_cameras` (`None` uses primary `camera`).
302    #[get(skip)]
303    #[get_mut(skip)]
304    #[set(skip)]
305    pub(crate) active_scene_camera: Option<usize>,
306    /// Mapping from `scene_graph` node index to spawned `World3D::objects` index for O(1) transform synchronization.
307    #[get(skip)]
308    #[get_mut(skip)]
309    #[set(skip)]
310    pub(crate) node_object_map: Vec<Option<usize>>,
311    /// Reusable pre-allocated skinning and shape-key scratch arena for zero steady-state heap allocations.
312    #[get(skip)]
313    #[get_mut(skip)]
314    #[set(skip)]
315    pub(crate) skin_scratch: SkinPaletteScratch3D,
316    /// Per-object deformed mesh cache aligned with `objects` holding live morphed and skinned vertices.
317    #[get(skip)]
318    #[get_mut(skip)]
319    #[set(skip)]
320    pub(crate) deformed_meshes: Vec<Option<Mesh3D>>,
321    /// Selects Blender AgX filmic view transform (`true`) or ACES Filmic (`false`) during CPU/GPU tonemapping.
322    #[get(type(copy))]
323    pub(crate) use_agx_tonemap: bool,
324    /// Persistent flat scratch buffers eliminating per-frame `Vec<Vec<_>>` allocations and O(N*M) pose scans during GPU pass building.
325    #[get(skip)]
326    #[get_mut(skip)]
327    #[set(skip)]
328    pub(crate) gpu_pass_scratch: World3dGpuPassScratch,
329}
330
331/// Persistent flat scratch buffers reused by `World3D::build_gpu_scene_pass_into` for zero-allocation O(N) instanced batch building.
332#[derive(Clone, Debug, Default)]
333pub(crate) struct World3dGpuPassScratch {
334    /// Generation-stamped dense lookup epochs indexed directly by `object_index` for O(1) dynamic pose lookup and O(1) clear.
335    pub(crate) dynamic_pose_epochs: Vec<u32>,
336    /// Interpolated dynamic transforms aligned 1:1 with `dynamic_pose_epochs`.
337    pub(crate) dynamic_pose_transforms: Vec<Transform3D>,
338    /// Monotonic epoch counter incremented per pass (`0` triggers full reset on wrap).
339    pub(crate) current_epoch: u32,
340    /// Per-mesh visible instance counts indexed by `mesh_id`.
341    pub(crate) mesh_counts: Vec<u32>,
342    /// Per-mesh scatter write cursors indexed by `mesh_id`.
343    pub(crate) mesh_cursors: Vec<u32>,
344    /// Flat single-allocation gather buffer holding visible `(mesh_id, instance)` pairs before O(N) counting-sort scatter.
345    pub(crate) visible_scratch: Vec<(u32, GpuWorld3dInstance)>,
346}