Skip to main content

qualia_core_db/hypermedia_authoring/
world3d.rs

1//! 3D editing — objects, modelling, rigging, animation, materials, camera/light.
2//!
3//! ~30 required functions.
4
5use std::collections::BTreeMap;
6
7/// A 3D object in the scene.
8#[derive(Debug, Clone)]
9pub struct Object3D {
10    pub id: String,
11    pub name: String,
12    pub mesh_id: Option<String>,
13    pub transform: Transform3D,
14    pub material_id: Option<String>,
15    pub children: Vec<String>,
16    pub parent: Option<String>,
17}
18
19#[derive(Debug, Clone, Default)]
20pub struct Transform3D {
21    pub position: [f32; 3],
22    pub rotation: [f32; 4], // quaternion
23    pub scale: [f32; 3],
24}
25
26impl Default for Object3D {
27    /// Default 3D object (identity transform, no mesh/material).
28    fn default() -> Self {
29        Self {
30            id: String::new(),
31            name: String::new(),
32            mesh_id: None,
33            transform: Transform3D::default(),
34            material_id: None,
35            children: Vec::new(),
36            parent: None,
37        }
38    }
39}
40
41impl Object3D {
42    /// Named object with `id` (identity transform).
43    pub fn new(id: &str, name: &str) -> Self {
44        Self {
45            id: id.to_string(),
46            name: name.to_string(),
47            ..Default::default()
48        }
49    }
50
51    /// Set world-space position.
52    pub fn set_position(&mut self, x: f32, y: f32, z: f32) {
53        self.transform.position = [x, y, z];
54    }
55
56    /// Set rotation quaternion (x, y, z, w).
57    pub fn set_rotation(&mut self, x: f32, y: f32, z: f32, w: f32) {
58        self.transform.rotation = [x, y, z, w];
59    }
60
61    /// Set per-axis scale.
62    pub fn set_scale(&mut self, x: f32, y: f32, z: f32) {
63        self.transform.scale = [x, y, z];
64    }
65
66    /// Assign a mesh by asset id.
67    pub fn set_mesh(&mut self, mesh_id: &str) {
68        self.mesh_id = Some(mesh_id.to_string());
69    }
70
71    /// Assign a material by asset id.
72    pub fn set_material(&mut self, material_id: &str) {
73        self.material_id = Some(material_id.to_string());
74    }
75
76    /// Parent a child object id.
77    pub fn add_child(&mut self, child_id: &str) {
78        self.children.push(child_id.to_string());
79    }
80}
81
82/// A 3D material definition.
83#[derive(Debug, Clone)]
84pub struct Material3D {
85    pub id: String,
86    pub name: String,
87    pub base_colour: [f32; 4],
88    pub metallic: f32,
89    pub roughness: f32,
90    pub emissive: [f32; 3],
91    pub normal_map: Option<String>,
92    pub albedo_map: Option<String>,
93    pub double_sided: bool,
94}
95
96impl Material3D {
97    /// Named material with `id` (default PBR factors).
98    pub fn new(id: &str, name: &str) -> Self {
99        Self {
100            id: id.to_string(),
101            name: name.to_string(),
102            base_colour: [0.8, 0.8, 0.8, 1.0],
103            metallic: 0.0,
104            roughness: 0.5,
105            emissive: [0.0; 3],
106            normal_map: None,
107            albedo_map: None,
108            double_sided: false,
109        }
110    }
111
112    /// Set RGBA base colour.
113    pub fn set_base_colour(&mut self, r: f32, g: f32, b: f32, a: f32) {
114        self.base_colour = [r, g, b, a];
115    }
116
117    /// Set metallic/roughness PBR factors.
118    pub fn set_metallic_roughness(&mut self, metallic: f32, roughness: f32) {
119        self.metallic = metallic.clamp(0.0, 1.0);
120        self.roughness = roughness.clamp(0.0, 1.0);
121    }
122
123    /// Set emissive colour.
124    pub fn set_emissive(&mut self, r: f32, g: f32, b: f32) {
125        self.emissive = [r, g, b];
126    }
127}
128
129/// A 3D camera.
130#[derive(Debug, Clone)]
131pub struct Camera3D {
132    pub id: String,
133    pub transform: Transform3D,
134    pub fov: f32,
135    pub near_plane: f32,
136    pub far_plane: f32,
137    pub aspect_ratio: f32,
138    pub projection: ProjectionType,
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub enum ProjectionType {
143    Perspective,
144    Orthographic,
145}
146
147impl Camera3D {
148    /// Perspective camera, default 60° FOV and clip planes.
149    pub fn new(id: &str) -> Self {
150        Self {
151            id: id.to_string(),
152            transform: Transform3D::default(),
153            fov: 60.0,
154            near_plane: 0.1,
155            far_plane: 1000.0,
156            aspect_ratio: 16.0 / 9.0,
157            projection: ProjectionType::Perspective,
158        }
159    }
160
161    /// Set vertical field-of-view (radians or degrees per the
162    /// scene convention).
163    pub fn set_fov(&mut self, fov: f32) {
164        self.fov = fov.clamp(1.0, 179.0);
165    }
166
167    /// Set near/far clip distances.
168    pub fn set_clip_planes(&mut self, near: f32, far: f32) {
169        self.near_plane = near.max(0.001);
170        self.far_plane = far.max(self.near_plane + 0.001);
171    }
172
173    /// Godot `Camera3D.unproject_position` with an explicit look-at basis.
174    /// World metres → viewport pixels (origin top-left). `None` if behind `near`.
175    pub fn unproject_position_look_at(
176        eye: [f64; 3],
177        target: [f64; 3],
178        up: [f64; 3],
179        fov_v_deg: f64,
180        world: [f64; 3],
181        viewport: (f64, f64),
182        near: f64,
183    ) -> Option<[f64; 2]> {
184        fn sub(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
185            [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
186        }
187        fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
188            a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
189        }
190        fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
191            [
192                a[1] * b[2] - a[2] * b[1],
193                a[2] * b[0] - a[0] * b[2],
194                a[0] * b[1] - a[1] * b[0],
195            ]
196        }
197        fn norm(a: [f64; 3]) -> Option<[f64; 3]> {
198            let len = dot(a, a).sqrt();
199            if len < 1e-12 {
200                None
201            } else {
202                Some([a[0] / len, a[1] / len, a[2] / len])
203            }
204        }
205        let forward = norm(sub(target, eye))?;
206        let right = norm(cross(forward, up))?;
207        let cam_up = cross(right, forward);
208        let delta = sub(world, eye);
209        let cam_x = dot(delta, right);
210        let cam_y = dot(delta, cam_up);
211        let cam_z = dot(delta, forward);
212        if cam_z <= near.max(1e-6) {
213            return None;
214        }
215        let (vw, vh) = viewport;
216        if vw <= 0.0 || vh <= 0.0 {
217            return None;
218        }
219        let fov = fov_v_deg.clamp(1.0, 179.0).to_radians();
220        let scale = 1.0 / (cam_z * (fov * 0.5).tan());
221        let aspect = vw / vh;
222        let ndc_x = cam_x * scale / aspect;
223        let ndc_y = cam_y * scale;
224        Some([(ndc_x + 1.0) * 0.5 * vw, (1.0 - ndc_y) * 0.5 * vh])
225    }
226}
227
228/// A 3D light.
229#[derive(Debug, Clone)]
230pub struct Light3D {
231    pub id: String,
232    pub light_type: LightType3D,
233    pub colour: [f32; 3],
234    pub intensity: f32,
235    pub transform: Transform3D,
236}
237
238#[derive(Debug, Clone, Copy, PartialEq, Eq)]
239pub enum LightType3D {
240    Point,
241    Directional,
242    Spot,
243    Area,
244}
245
246impl Light3D {
247    /// Light of `light_type` with default intensity/colour.
248    pub fn new(id: &str, light_type: LightType3D) -> Self {
249        Self {
250            id: id.to_string(),
251            light_type,
252            colour: [1.0; 3],
253            intensity: 1.0,
254            transform: Transform3D::default(),
255        }
256    }
257}
258
259/// A rig for skeletal animation.
260#[derive(Debug, Clone)]
261pub struct Rig {
262    pub id: String,
263    pub name: String,
264    pub bones: Vec<Bone>,
265    pub root_bone: Option<String>,
266}
267
268#[derive(Debug, Clone)]
269pub struct Bone {
270    pub id: String,
271    pub name: String,
272    pub parent: Option<String>,
273    pub children: Vec<String>,
274    pub rest_transform: Transform3D,
275    pub inverse_bind: [[f32; 4]; 4],
276}
277
278impl Rig {
279    /// Empty skeletal rig.
280    pub fn new(id: &str, name: &str) -> Self {
281        Self {
282            id: id.to_string(),
283            name: name.to_string(),
284            bones: Vec::new(),
285            root_bone: None,
286        }
287    }
288
289    /// Append a bone to the rig.
290    pub fn add_bone(&mut self, bone: Bone) {
291        if self.root_bone.is_none() && bone.parent.is_none() {
292            self.root_bone = Some(bone.id.clone());
293        }
294        self.bones.push(bone);
295    }
296
297    /// Number of bones in the rig.
298    pub fn bone_count(&self) -> usize {
299        self.bones.len()
300    }
301
302    /// Bone lookup by id.
303    pub fn find_bone(&self, id: &str) -> Option<&Bone> {
304        self.bones.iter().find(|b| b.id == id)
305    }
306}
307
308/// An animation clip — keyframes for bones.
309#[derive(Debug, Clone)]
310pub struct AnimationClip {
311    pub id: String,
312    pub name: String,
313    pub duration: f64,
314    pub tracks: Vec<AnimationTrack>,
315}
316
317#[derive(Debug, Clone)]
318pub struct AnimationTrack {
319    pub bone_id: String,
320    pub property: AnimatedProperty,
321    pub keyframes: Vec<Keyframe>,
322}
323
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325pub enum AnimatedProperty {
326    Position,
327    Rotation,
328    Scale,
329}
330
331#[derive(Debug, Clone)]
332pub struct Keyframe {
333    pub time: f64,
334    pub value: [f32; 3], // position/scale or euler rotation
335}
336
337impl AnimationClip {
338    /// Empty animation clip of `duration` seconds.
339    pub fn new(id: &str, name: &str, duration: f64) -> Self {
340        Self {
341            id: id.to_string(),
342            name: name.to_string(),
343            duration,
344            tracks: Vec::new(),
345        }
346    }
347
348    /// Append an animation track.
349    pub fn add_track(&mut self, track: AnimationTrack) {
350        self.tracks.push(track);
351    }
352
353    /// Number of tracks in the clip.
354    pub fn track_count(&self) -> usize {
355        self.tracks.len()
356    }
357}
358
359/// A 3D scene / world container.
360#[derive(Debug, Clone, Default)]
361pub struct Scene3D {
362    pub objects: BTreeMap<String, Object3D>,
363    pub materials: BTreeMap<String, Material3D>,
364    pub cameras: BTreeMap<String, Camera3D>,
365    pub lights: BTreeMap<String, Light3D>,
366    pub rigs: BTreeMap<String, Rig>,
367    pub animations: BTreeMap<String, AnimationClip>,
368}
369
370impl Scene3D {
371    /// Empty scene.
372    pub fn new() -> Self {
373        Self::default()
374    }
375
376    /// Add an object to the scene.
377    pub fn add_object(&mut self, obj: Object3D) {
378        self.objects.insert(obj.id.clone(), obj);
379    }
380
381    /// Add a material asset.
382    pub fn add_material(&mut self, mat: Material3D) {
383        self.materials.insert(mat.id.clone(), mat);
384    }
385
386    /// Add a camera.
387    pub fn add_camera(&mut self, cam: Camera3D) {
388        self.cameras.insert(cam.id.clone(), cam);
389    }
390
391    /// Add a light.
392    pub fn add_light(&mut self, light: Light3D) {
393        self.lights.insert(light.id.clone(), light);
394    }
395
396    /// Add a skeletal rig.
397    pub fn add_rig(&mut self, rig: Rig) {
398        self.rigs.insert(rig.id.clone(), rig);
399    }
400
401    /// Add an animation clip.
402    pub fn add_animation(&mut self, clip: AnimationClip) {
403        self.animations.insert(clip.id.clone(), clip);
404    }
405
406    /// Number of objects in the scene.
407    pub fn object_count(&self) -> usize {
408        self.objects.len()
409    }
410}
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415
416    #[test]
417    fn object_creation() {
418        let obj = Object3D::new("o1", "Cube");
419        assert_eq!(obj.name, "Cube");
420        assert_eq!(obj.transform.position, [0.0; 3]);
421    }
422
423    #[test]
424    fn object_set_transform() {
425        let mut obj = Object3D::new("o1", "Cube");
426        obj.set_position(1.0, 2.0, 3.0);
427        obj.set_scale(2.0, 2.0, 2.0);
428        assert_eq!(obj.transform.position, [1.0, 2.0, 3.0]);
429        assert_eq!(obj.transform.scale, [2.0, 2.0, 2.0]);
430    }
431
432    #[test]
433    fn material_creation() {
434        let mat = Material3D::new("m1", "Metal");
435        assert_eq!(mat.metallic, 0.0);
436        assert_eq!(mat.roughness, 0.5);
437    }
438
439    #[test]
440    fn material_set_metallic_roughness() {
441        let mut mat = Material3D::new("m1", "Metal");
442        mat.set_metallic_roughness(0.9, 0.1);
443        assert_eq!(mat.metallic, 0.9);
444        assert_eq!(mat.roughness, 0.1);
445    }
446
447    #[test]
448    fn camera_creation() {
449        let cam = Camera3D::new("cam1");
450        assert_eq!(cam.fov, 60.0);
451        assert_eq!(cam.projection, ProjectionType::Perspective);
452    }
453
454    #[test]
455    fn camera_set_fov() {
456        let mut cam = Camera3D::new("cam1");
457        cam.set_fov(90.0);
458        assert_eq!(cam.fov, 90.0);
459    }
460
461    #[test]
462    fn camera_unproject_look_at_centers_the_target() {
463        let px = Camera3D::unproject_position_look_at(
464            [0.0, 0.0, 0.0],
465            [0.0, 0.0, 1.0],
466            [0.0, 1.0, 0.0],
467            90.0,
468            [0.0, 0.0, 1.0],
469            (1920.0, 1080.0),
470            0.1,
471        )
472        .expect("target is in front of the camera");
473        assert!((px[0] - 960.0).abs() < 1e-6);
474        assert!((px[1] - 540.0).abs() < 1e-6);
475    }
476
477    #[test]
478    fn camera_unproject_rejects_points_behind_near() {
479        assert!(Camera3D::unproject_position_look_at(
480            [0.0, 0.0, 0.0],
481            [0.0, 0.0, 1.0],
482            [0.0, 1.0, 0.0],
483            60.0,
484            [0.0, 0.0, -1.0],
485            (800.0, 600.0),
486            0.1,
487        )
488        .is_none());
489    }
490
491    #[test]
492    fn light_creation() {
493        let light = Light3D::new("l1", LightType3D::Point);
494        assert_eq!(light.light_type, LightType3D::Point);
495        assert_eq!(light.intensity, 1.0);
496    }
497
498    #[test]
499    fn rig_add_bone() {
500        let mut rig = Rig::new("rig1", "Armature");
501        rig.add_bone(Bone {
502            id: "b1".into(),
503            name: "Root".into(),
504            parent: None,
505            children: vec![],
506            rest_transform: Transform3D::default(),
507            inverse_bind: [[0.0; 4]; 4],
508        });
509        assert_eq!(rig.bone_count(), 1);
510        assert_eq!(rig.root_bone, Some("b1".to_string()));
511    }
512
513    #[test]
514    fn animation_clip() {
515        let mut clip = AnimationClip::new("a1", "Walk", 2.0);
516        clip.add_track(AnimationTrack {
517            bone_id: "b1".into(),
518            property: AnimatedProperty::Position,
519            keyframes: vec![Keyframe {
520                time: 0.0,
521                value: [0.0; 3],
522            }],
523        });
524        assert_eq!(clip.track_count(), 1);
525        assert_eq!(clip.duration, 2.0);
526    }
527
528    #[test]
529    fn scene_add_objects() {
530        let mut scene = Scene3D::new();
531        scene.add_object(Object3D::new("o1", "Cube"));
532        scene.add_material(Material3D::new("m1", "Metal"));
533        scene.add_camera(Camera3D::new("cam1"));
534        scene.add_light(Light3D::new("l1", LightType3D::Point));
535        assert_eq!(scene.object_count(), 1);
536        assert_eq!(scene.materials.len(), 1);
537        assert_eq!(scene.cameras.len(), 1);
538        assert_eq!(scene.lights.len(), 1);
539    }
540}