1use std::collections::{HashMap, HashSet};
8use std::sync::Arc;
9use crate::{scene, stage_transform, stage_values, ImportError, ImportIdentity,
10 ImportedAssembly, ImportedDefinition, ImportedSource, RawMatrix, RawMesh};
11
12#[derive(Clone, Debug)]
13pub struct Node { pub path: String, pub children: Vec<(String, u32)> }
14#[derive(Clone, Debug, Default)]
15pub struct NodeReply {
16 pub has_entity: bool,
17 pub original_step_instance: Option<String>,
18 pub visibility: Option<String>,
19 pub diffuse: Option<Vec<f64>>,
20 pub opacity: f64,
21 pub local_transform: Option<RawMatrix>,
22 pub has_mesh: bool,
23 pub has_points: bool,
24}
25#[derive(Clone, Debug)]
26pub struct PointsReply {
27 pub positions: Vec<f64>, pub colors: Option<Vec<f64>>, pub count: f64,
28 pub precision: String, pub encoding: String,
29}
30#[derive(Clone, Debug)]
31pub struct PointMetadata {
32 pub colors: Option<Vec<f64>>, pub count: f64, pub precision: String, pub encoding: String,
33}
34#[derive(Debug)]
35pub struct RetainedSource {
36 pub identity: ImportIdentity, pub transform_stack: Vec<RawMatrix>,
37 pub source: Arc<ImportedSource>, pub points: Option<Arc<PointMetadata>>,
38}
39#[derive(Clone, Debug, PartialEq, Eq)]
40pub struct LineageEntry { pub node: u32, pub edge: Option<String> }
41#[derive(Clone, Debug)]
42pub enum EventKind {
43 Node(Vec<LineageEntry>),
44 Key { transform: Option<[f32; 16]>, color: Option<[f64; 4]> },
45 MeshSource,
46 PointsSource,
47 MeshOutput { output: crate::MeshOutput, color: Option<[f64; 4]> },
48 PointsOutput { output: crate::PointsOutput, colors: Option<Vec<f32>>, count: f64 },
49}
50#[derive(Clone, Debug)]
51pub struct Event {
52 pub sequence: u32, pub frame: u64, pub node: u32, pub context: Option<u32>, pub kind: EventKind,
53}
54impl Event {
55 pub fn reply_kind(&self) -> u32 {
56 match self.kind {
57 EventKind::Node(_) => 102, EventKind::Key { .. } => 103,
58 EventKind::MeshSource => 104, EventKind::PointsSource => 105,
59 EventKind::MeshOutput { .. } | EventKind::PointsOutput { .. } => 106,
60 }
61 }
62}
63pub const MAX_DEPTH: usize = 4096;
70pub const MAX_FRAMES: u64 = 10_000_000;
72pub const MAX_QUEUED_BYTES: usize = 256 << 20;
74pub const MAX_RETAINED_BYTES: usize = 512 << 20;
77pub const MAX_TRANSFORM_ROWS: usize = 4;
79pub const MAX_TRANSFORM_COLUMNS: usize = 4;
80#[derive(Clone, Copy, Debug)]
81struct Limits { depth: usize, frames: u64, queued_bytes: usize, retained_bytes: usize }
82const LIMITS: Limits = Limits { depth: MAX_DEPTH, frames: MAX_FRAMES, queued_bytes: MAX_QUEUED_BYTES, retained_bytes: MAX_RETAINED_BYTES };
83const FRAME_BYTES: usize = 160;
84const ENTRY_BYTES: usize = 32;
85pub(crate) fn oversized_transform(matrix: &RawMatrix) -> bool {
87 matrix.len() > MAX_TRANSFORM_ROWS || matrix.iter().any(|row| row.len() > MAX_TRANSFORM_COLUMNS)
88}
89fn matrix_bytes(matrix: &RawMatrix) -> usize {
90 24 + matrix.iter().map(|row| 24 + row.len() * 8).sum::<usize>()
91}
92
93#[derive(Clone, Debug, Default)]
94struct Frame {
95 occurrence: u64, node: u32, lineage: Vec<LineageEntry>, context: Option<u32>,
96 is_type: bool, invisible: bool, color: Option<[f64; 4]>, stack: Vec<RawMatrix>,
97 bytes: usize,
99}
100#[derive(Debug)]
101pub struct GraphProgram {
102 store: u64, revision: u64, nodes: Vec<Node>, seeds: Vec<u32>, passes: Vec<bool>, pass: usize,
103 queue: Vec<Frame>, current: Option<Frame>, pending: Option<Event>,
104 sequence: u32, occurrence: u64, emitted: HashSet<String>, retained: Vec<RetainedSource>, failure: Option<ImportError>,
105 definitions: HashMap<(u64, bool), Arc<ImportedSource>>,
106 point_metadata: HashMap<u64, Arc<PointMetadata>>,
107 limits: Limits, queued_bytes: usize, retained_bytes: usize,
108}
109
110fn seeds(nodes: &[Node], candidates: usize) -> Result<Vec<u32>, ImportError> {
111 if candidates > nodes.len() { return Err(ImportError::InvalidPacket); }
112 if nodes.iter().any(|node| node.children.iter().any(|(_, child)| *child as usize >= nodes.len())) {
113 return Err(ImportError::InvalidPacket);
114 }
115 let mut child_paths = HashSet::new();
116 for node in &nodes[..candidates] { for (_, child) in &node.children {
117 let child = nodes.get(*child as usize).ok_or(ImportError::InvalidPacket)?;
118 child_paths.insert(child.path.as_str());
119 }}
120 let roots: Vec<u32> = nodes[..candidates].iter().enumerate()
123 .filter(|(_, node)| !child_paths.contains(node.path.as_str()))
124 .map(|(index, _)| index as u32).collect();
125 let mut reachable = HashSet::new();
126 let mut result = Vec::new();
127 for root in roots { result.push(root); mark_reachable(root, nodes, &mut reachable)?; }
128 for candidate in 0..candidates as u32 {
129 if reachable.contains(nodes[candidate as usize].path.as_str()) { continue; }
130 result.push(candidate); mark_reachable(candidate, nodes, &mut reachable)?;
131 }
132 Ok(result)
133}
134fn mark_reachable<'a>(root: u32, nodes: &'a [Node], reachable: &mut HashSet<&'a str>) -> Result<(), ImportError> {
135 let mut work = vec![root];
136 while let Some(id) = work.pop() {
137 let node = nodes.get(id as usize).ok_or(ImportError::InvalidPacket)?;
138 if !reachable.insert(node.path.as_str()) { continue; }
139 work.extend(node.children.iter().map(|(_, child)| *child));
140 }
141 Ok(())
142}
143
144fn same_values(left: &[f64], right: &[f64]) -> bool {
145 left.len() == right.len() && left.iter().zip(right).all(|(a, b)| a.to_bits() == b.to_bits())
146}
147fn same_optional(left: &Option<Vec<f64>>, right: &Option<Vec<f64>>) -> bool {
148 match (left, right) { (Some(a), Some(b)) => same_values(a, b), (None, None) => true, _ => false }
149}
150fn same_rows(left: &[Vec<f64>], right: &[Vec<f64>]) -> bool {
151 left.len() == right.len() && left.iter().zip(right).all(|(a, b)| same_values(a, b))
152}
153fn same_source(left: &ImportedSource, right: &ImportedSource) -> bool {
154 match (left, right) {
155 (ImportedSource::Points(a), ImportedSource::Points(b)) => same_values(a, b),
156 (ImportedSource::Mesh(a), ImportedSource::Mesh(b)) => {
157 same_rows(&a.points, &b.points) && same_values(&a.face_vertex_indices, &b.face_vertex_indices)
158 && same_optional(&a.face_vertex_counts, &b.face_vertex_counts)
159 && match (&a.normals, &b.normals) {
160 (Some(a), Some(b)) => same_rows(a, b), (None, None) => true, _ => false,
161 }
162 }
163 _ => false,
164 }
165}
166
167fn is_type(source: &str) -> bool {
168 source.as_bytes().split(|byte| *byte == b'=').skip(1).any(|tail| {
170 let length = tail.iter().take_while(|b| b.is_ascii_alphanumeric() || **b == b'_').count();
171 length >= 4 && tail[length-4..length].eq_ignore_ascii_case(b"type") && tail.get(length) == Some(&b'(')
172 })
173}
174
175impl GraphProgram {
176 pub fn new(store: u64, revision: u64, mode: u32, nodes: Vec<Node>) -> Result<Self, ImportError> {
177 let candidates = nodes.len();
178 Self::with_candidates(store, revision, mode, nodes, candidates)
179 }
180 pub fn with_candidates(store: u64, revision: u64, mode: u32, nodes: Vec<Node>, candidates: usize) -> Result<Self, ImportError> {
181 if !(1..=3).contains(&mode) || u32::try_from(nodes.len()).is_err() { return Err(ImportError::InvalidPacket); }
182 let seeds = seeds(&nodes, candidates)?;
183 let passes = match mode { 1 => vec![true], 2 => vec![false], _ => vec![true, false] };
184 let mut program = Self { store, revision, nodes, seeds, passes, pass: 0, queue: Vec::new(),
185 current: None, pending: None, sequence: 0, occurrence: 0, emitted: HashSet::new(), retained: Vec::new(), failure: None, definitions: HashMap::new(), point_metadata: HashMap::new(), limits: LIMITS, queued_bytes: 0, retained_bytes: 0 };
186 program.seed_pass()?;
187 Ok(program)
188 }
189 fn seed_pass(&mut self) -> Result<(), ImportError> {
192 let bytes = self.seeds.len().checked_mul(FRAME_BYTES + ENTRY_BYTES)
193 .and_then(|bytes| bytes.checked_add(self.queued_bytes));
194 if bytes.is_none_or(|bytes| bytes > self.limits.queued_bytes) || self.seeds.len() as u64 > self.limits.frames {
195 return Err(self.fail(ImportError::InvalidPacket));
196 }
197 let frames: Vec<Frame> = self.seeds.iter().rev().map(|node| Frame {
198 node: *node, lineage: vec![LineageEntry { node: *node, edge: None }],
199 bytes: FRAME_BYTES + ENTRY_BYTES, ..Frame::default()
200 }).collect();
201 self.queued_bytes = self.queued_bytes.saturating_add(frames.iter().map(|f| f.bytes).sum());
202 self.queue.extend(frames);
203 Ok(())
204 }
205 fn issue(&mut self, kind: EventKind) -> Result<(), ImportError> {
206 let frame = self.current.as_ref().ok_or(ImportError::IdentityMismatch)?;
207 self.sequence = self.sequence.checked_add(1).ok_or(ImportError::InvalidPacket)?;
208 self.pending = Some(Event { sequence: self.sequence, frame: frame.occurrence,
209 node: frame.node, context: frame.context, kind });
210 Ok(())
211 }
212 pub fn poll(&mut self) -> Result<Option<&Event>, ImportError> {
214 self.check_failure()?;
215 if self.pending.is_some() { return Ok(self.pending.as_ref()); }
216 while self.queue.is_empty() {
217 if self.pass + 1 == self.passes.len() { return Ok(None); }
218 self.pass += 1;
219 self.seed_pass()?;
220 }
221 let mut frame = self.queue.pop().ok_or(ImportError::IdentityMismatch)?;
222 self.queued_bytes = self.queued_bytes.saturating_sub(frame.bytes);
223 self.occurrence = self.occurrence.checked_add(1).ok_or(ImportError::InvalidPacket)?;
224 if self.occurrence > self.limits.frames { return Err(self.fail(ImportError::InvalidPacket)); }
225 frame.occurrence = self.occurrence;
226 let lineage = frame.lineage.clone();
227 self.current = Some(frame);
228 self.issue(EventKind::Node(lineage))?;
229 Ok(self.pending.as_ref())
230 }
231 fn check_failure(&self) -> Result<(), ImportError> {
232 self.failure.clone().map_or(Ok(()), Err)
233 }
234 pub fn check_reply(&self, sequence: u32, kind: u32) -> Result<(), ImportError> {
235 self.check_failure()?;
236 match &self.pending {
237 Some(event) if event.sequence == sequence && event.reply_kind() == kind => Ok(()),
238 _ => Err(ImportError::IdentityMismatch),
239 }
240 }
241 pub fn node_reply(&mut self, sequence: u32, reply: NodeReply) -> Result<(), ImportError> {
242 self.check_reply(sequence, 102)?;
243 if reply.local_transform.as_ref().is_some_and(crate::graph::oversized_transform) {
244 return Err(self.fail(ImportError::InvalidPacket));
245 }
246 let frame = self.current.as_mut().ok_or(ImportError::IdentityMismatch)?;
247 if reply.has_entity {
248 frame.context = Some(frame.node);
249 frame.is_type |= reply.original_step_instance.as_deref().is_some_and(is_type);
250 }
251 if let Some(visibility) = reply.visibility {
254 if !visibility.eq_ignore_ascii_case("inherited") { frame.invisible = visibility.eq_ignore_ascii_case("invisible"); }
255 }
256 if let Some(color) = reply.diffuse {
257 frame.color = Some([color.first().copied().unwrap_or(f64::NAN),
258 color.get(1).copied().unwrap_or(f64::NAN), color.get(2).copied().unwrap_or(f64::NAN), reply.opacity]); }
260 if let Some(local) = reply.local_transform { frame.bytes = frame.bytes.saturating_add(matrix_bytes(&local)); frame.stack.push(local); }
261 let transform = stage_transform(&frame.stack, self.passes[self.pass]);
263 let eligible = frame.context.is_some() && !frame.is_type && !frame.invisible;
264 let next = if eligible && self.passes[self.pass] && reply.has_mesh {
265 Some(EventKind::Key { transform, color: frame.color })
266 } else if eligible && !self.passes[self.pass] && reply.has_points {
267 Some(EventKind::PointsSource)
268 } else { None };
269 self.pending = None;
270 if let Some(kind) = next { self.issue(kind) } else { self.finish_frame() }
271 }
272 pub fn key_reply(&mut self, sequence: u32, key: String) -> Result<(), ImportError> {
273 self.check_reply(sequence, 103)?;
274 self.pending = None;
275 if self.emitted.insert(key) { self.issue(EventKind::MeshSource) } else { self.finish_frame() }
276 }
277 fn definition(&self, source: ImportedSource) -> Result<ImportedDefinition, ImportError> {
278 let frame = self.current.as_ref().ok_or(ImportError::IdentityMismatch)?;
279 Ok(ImportedDefinition { identity: ImportIdentity { store: self.store, revision: self.revision,
280 definition: u64::from(frame.node) + 1, occurrence: frame.occurrence },
281 source, transform_stack: frame.stack.clone() })
282 }
283 fn fail(&mut self, error: ImportError) -> ImportError {
284 self.failure = Some(error.clone());
285 self.pending = None;
286 self.current = None;
287 self.queue.clear();
288 self.retained.clear();
290 self.definitions.clear();
291 self.point_metadata.clear();
292 self.retained_bytes = 0;
293 error
294 }
295 fn evaluate(&mut self, source: ImportedSource) -> Result<ImportedAssembly, ImportError> {
296 let definition = self.definition(source)?;
297 let key = (definition.identity.definition, matches!(definition.source, ImportedSource::Points(_)));
298 if self.definitions.get(&key).is_some_and(|known| !same_source(known, &definition.source)) {
299 return Err(self.fail(ImportError::IdentityMismatch));
300 }
301 match scene::evaluate(definition) {
302 Ok(assembly) => Ok(assembly),
303 Err(error) => Err(self.fail(error)),
304 }
305 }
306 pub fn mesh_reply(&mut self, sequence: u32, source: RawMesh) -> Result<(), ImportError> {
307 self.check_reply(sequence, 104)?;
308 let ImportedAssembly { definition, output } = self.evaluate(ImportedSource::Mesh(source))?;
309 let crate::ImportedOutput::Mesh(output) = output else { return Err(ImportError::IdentityMismatch); };
310 let kind = EventKind::MeshOutput { output, color: self.current.as_ref().and_then(|frame| frame.color) };
311 self.retain(definition, None)?;
312 self.issue(kind)
313 }
314 pub fn points_reply(&mut self, sequence: u32, source: Option<PointsReply>) -> Result<(), ImportError> {
315 self.check_reply(sequence, 105)?;
316 let Some(source) = source else { self.pending = None; return self.finish_frame(); };
317 let PointsReply { positions, colors, count, precision, encoding } = source;
318 let id = self.current.as_ref().ok_or(ImportError::IdentityMismatch)?.node as u64 + 1;
319 if self.point_metadata.get(&id).is_some_and(|known| known.count.to_bits() != count.to_bits()
320 || known.precision != precision || known.encoding != encoding || !same_optional(&known.colors, &colors)) {
321 return Err(self.fail(ImportError::IdentityMismatch));
322 }
323 let ImportedAssembly { definition, output } = self.evaluate(ImportedSource::Points(positions))?;
324 let crate::ImportedOutput::Points(output) = output else { return Err(ImportError::IdentityMismatch); };
325 let kind = EventKind::PointsOutput { output, colors: colors.as_deref().map(stage_values), count };
326 let points = Some(PointMetadata { colors, count, precision, encoding });
327 self.retain(definition, points)?;
328 self.issue(kind)
329 }
330 fn retain(&mut self, definition: ImportedDefinition, points: Option<PointMetadata>) -> Result<(), ImportError> {
332 let ImportedDefinition { identity, source, transform_stack } = definition;
333 let bytes = transform_stack.iter().map(matrix_bytes).sum::<usize>().saturating_add(ENTRY_BYTES);
334 self.retained_bytes = self.retained_bytes.saturating_add(bytes);
335 if self.retained_bytes > self.limits.retained_bytes { return Err(self.fail(ImportError::InvalidPacket)); }
336 let is_points = matches!(source, ImportedSource::Points(_));
337 let source = Arc::clone(self.definitions.entry((identity.definition, is_points))
338 .or_insert_with(|| Arc::new(source)));
339 let points = points.map(|metadata| Arc::clone(self.point_metadata.entry(identity.definition)
340 .or_insert_with(|| Arc::new(metadata))));
341 self.retained.push(RetainedSource { identity, transform_stack, source, points });
342 Ok(())
343 }
344 pub fn ack(&mut self, sequence: u32) -> Result<(), ImportError> {
345 self.check_reply(sequence, 106)?;
346 self.pending = None;
347 self.finish_frame()
348 }
349 fn finish_frame(&mut self) -> Result<(), ImportError> {
350 let frame = self.current.take().ok_or(ImportError::IdentityMismatch)?;
351 for (edge, child) in self.nodes[frame.node as usize].children.iter().rev() {
352 if frame.lineage.iter().any(|entry| self.nodes[entry.node as usize].path == self.nodes[*child as usize].path) { continue; }
354 if frame.lineage.len() >= self.limits.depth { return Err(self.fail(ImportError::InvalidPacket)); }
355 let bytes = frame.bytes.saturating_add(ENTRY_BYTES).saturating_add(edge.len());
356 self.queued_bytes = self.queued_bytes.saturating_add(bytes);
358 if self.queued_bytes > self.limits.queued_bytes { return Err(self.fail(ImportError::InvalidPacket)); }
359 let mut next = frame.clone();
360 next.node = *child;
361 next.bytes = bytes;
362 next.lineage.push(LineageEntry { node: *child, edge: Some(edge.clone()) });
363 self.queue.push(next);
364 }
365 Ok(())
366 }
367 pub fn retained(&self) -> &[RetainedSource] { &self.retained }
368}
369
370#[cfg(test)]
371#[path = "graph_tests.rs"]
372mod tests;