Skip to main content

webizen_studio/render/
graph.rs

1//! Scene graph — the structural half of the engine dev-kit.
2//!
3//! A [`Scene`] is a tree of [`Node`]s (transform + optional [`Mesh`] + style +
4//! children). [`Scene::render`] walks the tree, composes transforms, and drives
5//! any [`Renderer`] backend (Canvas2D today, WebGPU next). This
6//! replaces the per-app hand-rolled draw loops (e.g. the physics surface) and the
7//! scene-graph role that three.js/Babylon used to play — but in pure Rust, with
8//! geometry that a future native backend can hand to QualiaDB's
9//! `geometric_algebra` SIMD kernel.
10
11use super::mesh::{Mesh, Transform};
12use super::scene::{Camera, Vec3};
13use super::{Renderer, ScreenPoint};
14
15/// Draw style for a node's mesh. Colors are CSS strings (theme `--qualia-*`
16/// variables work) so values flow straight to the Canvas2D backend.
17#[derive(Clone, Debug, PartialEq)]
18pub struct Style {
19    /// Edge/line color, or `None` to skip wireframe.
20    pub stroke: Option<String>,
21    /// Face fill color, or `None` to skip solid faces.
22    pub fill: Option<String>,
23    /// Vertex point color, or `None` to skip points.
24    pub point: Option<String>,
25    pub alpha: f64,
26    pub width: f64,
27    pub point_radius: f64,
28}
29
30impl Default for Style {
31    fn default() -> Self {
32        Self {
33            stroke: Some("var(--qualia-accent)".to_string()),
34            fill: None,
35            point: None,
36            alpha: 1.0,
37            width: 1.0,
38            point_radius: 2.5,
39        }
40    }
41}
42
43impl Style {
44    /// Adds/looks up a wire.
45    pub fn wire(color: impl Into<String>) -> Self {
46        Self {
47            stroke: Some(color.into()),
48            ..Default::default()
49        }
50    }
51    /// `true` for a solid edge.
52    pub fn solid(fill: impl Into<String>) -> Self {
53        Self {
54            stroke: None,
55            fill: Some(fill.into()),
56            ..Default::default()
57        }
58    }
59    /// Builder — sets alpha.
60    pub fn with_alpha(mut self, a: f64) -> Self {
61        self.alpha = a;
62        self
63    }
64}
65
66/// A node in the scene graph.
67#[derive(Clone, Debug, PartialEq)]
68pub struct Node {
69    pub label: String,
70    pub transform: Transform,
71    pub mesh: Option<Mesh>,
72    pub style: Style,
73    pub children: Vec<Node>,
74    /// Stable entity id for multi-observer pick → view_select (0 = unset).
75    pub entity_id: u64,
76    /// Affordance bits from rights filter (0 = unset).
77    pub affordance_bits: u8,
78}
79
80impl Default for Node {
81    fn default() -> Self {
82        Self {
83            label: String::new(),
84            transform: Transform::default(),
85            mesh: None,
86            style: Style::default(),
87            children: Vec::new(),
88            entity_id: 0,
89            affordance_bits: 0,
90        }
91    }
92}
93
94impl Node {
95    /// Creates a new instance.
96    pub fn new(label: impl Into<String>) -> Self {
97        Self {
98            label: label.into(),
99            ..Default::default()
100        }
101    }
102
103    /// Builder — sets entity-id.
104    pub fn with_entity_id(mut self, entity_id: u64) -> Self {
105        self.entity_id = entity_id;
106        self
107    }
108
109    /// Builder — sets affordance-bits.
110    pub fn with_affordance_bits(mut self, bits: u8) -> Self {
111        self.affordance_bits = bits;
112        self
113    }
114    /// Builder — sets mesh.
115    pub fn with_mesh(mut self, mesh: Mesh) -> Self {
116        self.mesh = Some(mesh);
117        self
118    }
119    /// Builder — sets style.
120    pub fn with_style(mut self, style: Style) -> Self {
121        self.style = style;
122        self
123    }
124    /// Builder — sets transform.
125    pub fn with_transform(mut self, t: Transform) -> Self {
126        self.transform = t;
127        self
128    }
129    /// Element access.
130    pub fn at(mut self, position: Vec3) -> Self {
131        self.transform.position = position;
132        self
133    }
134    /// Child node.
135    pub fn child(mut self, node: Node) -> Self {
136        self.children.push(node);
137        self
138    }
139}
140
141/// A renderable scene: background, camera, and root nodes.
142#[derive(Clone, Debug, PartialEq)]
143pub struct Scene {
144    pub background: String,
145    pub camera: Camera,
146    pub roots: Vec<Node>,
147}
148
149impl Default for Scene {
150    fn default() -> Self {
151        Self {
152            background: "var(--qualia-bg)".to_string(),
153            camera: Camera::default(),
154            roots: Vec::new(),
155        }
156    }
157}
158
159impl Scene {
160    /// Creates a new instance.
161    pub fn new(camera: Camera) -> Self {
162        Self {
163            camera,
164            ..Default::default()
165        }
166    }
167    /// Builder — sets background.
168    pub fn with_background(mut self, bg: impl Into<String>) -> Self {
169        self.background = bg.into();
170        self
171    }
172    /// Vector addition.
173    pub fn add(mut self, node: Node) -> Self {
174        self.roots.push(node);
175        self
176    }
177
178    /// Render the whole scene into `r`. Sets the camera, clears, walks the tree.
179    pub fn render<R: Renderer>(&self, r: &mut R) {
180        r.set_camera(self.camera);
181        r.clear(&self.background);
182        for node in &self.roots {
183            render_node(node, &|v| v, r);
184        }
185    }
186}
187
188/// Recursively draw `node`. `world` maps the node's local space into world space
189/// (the composition of all ancestor transforms), so child transforms nest
190/// correctly without matrix bookkeeping.
191fn render_node<R: Renderer>(node: &Node, world: &dyn Fn(Vec3) -> Vec3, r: &mut R) {
192    let to_world = |v: Vec3| world(node.transform.apply(v));
193
194    if let Some(mesh) = &node.mesh {
195        // Faces (drawn first so wireframe/points sit on top).
196        if let Some(fill) = &node.style.fill {
197            for face in &mesh.faces {
198                let pts: Option<Vec<ScreenPoint>> = face
199                    .iter()
200                    .map(|&i| r.project(to_world(mesh.vertices[i])))
201                    .collect();
202                if let Some(pts) = pts {
203                    r.fill_polygon(&pts, fill, node.style.alpha);
204                }
205            }
206        }
207        // Edges.
208        if let Some(stroke) = &node.style.stroke {
209            for &(a, b) in &mesh.edges {
210                if let (Some(pa), Some(pb)) = (
211                    r.project(to_world(mesh.vertices[a])),
212                    r.project(to_world(mesh.vertices[b])),
213                ) {
214                    r.line(pa, pb, stroke, node.style.alpha, node.style.width);
215                }
216            }
217        }
218        // Vertex points.
219        if let Some(point) = &node.style.point {
220            for v in &mesh.vertices {
221                if let Some(p) = r.project(to_world(*v)) {
222                    r.point(p, node.style.point_radius, point, node.style.alpha);
223                }
224            }
225        }
226    }
227
228    for child in &node.children {
229        render_node(child, &to_world, r);
230    }
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    #[test]
238    fn scene_builder_nesting() {
239        let scene = Scene::new(Camera::default()).add(
240            Node::new("parent")
241                .with_mesh(Mesh::cube(1.0))
242                .child(Node::new("child").at(Vec3::new(2.0, 0.0, 0.0))),
243        );
244        assert_eq!(scene.roots.len(), 1);
245        assert_eq!(scene.roots[0].children.len(), 1);
246        assert_eq!(scene.roots[0].children[0].transform.position.x, 2.0);
247    }
248}