ezu-graph 0.2.0

Typed DAG evaluator for the Ezu Style Spec
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! The DAG itself: building, type-checking, topology, pad propagation.

use std::collections::VecDeque;

use indexmap::IndexMap;

use crate::node::Node;
use crate::port::PortKind;

/// Identifier for a node in the [`Graph`]. Matches the key used in the
/// style JSON's `nodes` object (e.g. `"water_paint"`).
pub type NodeId = String;

/// Compact internal index assigned during graph build. Stable for the
/// lifetime of the graph; used by topo-sorted operations.
pub type NodeIx = usize;

#[derive(Debug, thiserror::Error)]
pub enum BuildError {
    #[error("unknown node reference `{from}` -> `{to}`")]
    UnknownRef { from: NodeId, to: NodeId },

    #[error("node `{node}` has no input port named `{port}`")]
    UnknownPort { node: NodeId, port: String },

    #[error("port `{node}.{port}` already connected")]
    DuplicateEdge { node: NodeId, port: String },

    #[error(
        "type mismatch on `{node}.{port}`: expected one of [{}], source `{src}` produces {got}",
        accepts.iter().map(|k| k.to_string()).collect::<Vec<_>>().join(", ")
    )]
    TypeMismatch {
        node: NodeId,
        port: String,
        src: NodeId,
        accepts: Vec<PortKind>,
        got: PortKind,
    },

    #[error("required port `{node}.{port}` is not connected")]
    MissingInput { node: NodeId, port: String },

    #[error("cycle detected involving node `{0}`")]
    Cycle(NodeId),

    #[error("output node `{0}` is not in the graph")]
    UnknownOutput(NodeId),

    #[error("graph has no output node")]
    NoOutput,

    #[error(
        "output node `{node}` produces `{got}`, but the document output must produce `raster` (canvas-padded). Pipe a sprite through `place`, `tiling`, or `stamp` first."
    )]
    OutputKindMismatch { node: NodeId, got: PortKind },

    #[error("required pad ({required}) on node `{node}` exceeds limit ({limit})")]
    PadExceeded {
        node: NodeId,
        required: u32,
        limit: u32,
    },
}

/// An edge in the DAG: `src.output` flows into `dst.inputs()[port_ix]`.
#[derive(Debug, Clone, Copy)]
pub struct Edge {
    pub src: NodeIx,
    pub dst: NodeIx,
    pub dst_port: usize,
}

/// A built, type-checked DAG. Tile-independent; build once per style
/// and evaluate many times.
pub struct Graph {
    nodes: IndexMap<NodeId, Box<dyn Node>>,
    /// Per-node, per-input-port edge source (None if unconnected and
    /// the port was optional).
    incoming: Vec<Vec<Option<NodeIx>>>,
    /// Adjacency for downstream walks: outgoing[src] -> list of dst.
    outgoing: Vec<Vec<NodeIx>>,
    /// Output node index.
    output: NodeIx,
    /// Topological order, output last.
    topo: Vec<NodeIx>,
    /// Resolved output [`PortKind`] for every node, indexed by [`NodeIx`].
    /// Polymorphic nodes (e.g. `blur` accepting both `Raster` and
    /// `Sprite`) have their actual output kind decided here at build
    /// time based on their connected inputs.
    output_kinds: Vec<PortKind>,
}

/// Maximum allowed pad propagated to any node, in pixels. Prevents
/// runaway blurs from demanding multi-tile buffers.
pub const MAX_PAD: u32 = 256;

/// Builder for constructing a [`Graph`] programmatically. The style
/// parser will drive this from JSON later; tests use it directly.
pub struct GraphBuilder {
    nodes: IndexMap<NodeId, Box<dyn Node>>,
    /// Pending edges, recorded by name; resolved at `build()` time.
    edges: Vec<EdgeSpec>,
    output: Option<NodeId>,
}

struct EdgeSpec {
    src: NodeId,
    dst: NodeId,
    dst_port: String,
}

impl GraphBuilder {
    pub fn new() -> Self {
        Self {
            nodes: IndexMap::new(),
            edges: Vec::new(),
            output: None,
        }
    }

    pub fn add_node(&mut self, id: impl Into<NodeId>, node: Box<dyn Node>) -> &mut Self {
        self.nodes.insert(id.into(), node);
        self
    }

    pub fn connect(
        &mut self,
        src: impl Into<NodeId>,
        dst: impl Into<NodeId>,
        dst_port: impl Into<String>,
    ) -> &mut Self {
        self.edges.push(EdgeSpec {
            src: src.into(),
            dst: dst.into(),
            dst_port: dst_port.into(),
        });
        self
    }

    pub fn set_output(&mut self, id: impl Into<NodeId>) -> &mut Self {
        self.output = Some(id.into());
        self
    }

    pub fn build(self) -> Result<Graph, BuildError> {
        let n = self.nodes.len();
        let mut incoming: Vec<Vec<Option<NodeIx>>> = self
            .nodes
            .values()
            .map(|node| vec![None; node.inputs().len()])
            .collect();
        let mut outgoing: Vec<Vec<NodeIx>> = vec![Vec::new(); n];

        let ix_of = |id: &str| -> Option<NodeIx> { self.nodes.get_index_of(id) };

        // Pass 1: wire edges (no type check yet — output kinds may be
        // polymorphic and only resolvable in topo order).
        for edge in &self.edges {
            let src_ix = ix_of(&edge.src).ok_or_else(|| BuildError::UnknownRef {
                from: edge.src.clone(),
                to: edge.dst.clone(),
            })?;
            let dst_ix = ix_of(&edge.dst).ok_or_else(|| BuildError::UnknownRef {
                from: edge.src.clone(),
                to: edge.dst.clone(),
            })?;

            let (_, dst_node) = self
                .nodes
                .get_index(dst_ix)
                .expect("dst_ix came from ix_of and is in range");
            let port_ix = dst_node
                .inputs()
                .iter()
                .position(|p| p.name == edge.dst_port)
                .ok_or_else(|| BuildError::UnknownPort {
                    node: edge.dst.clone(),
                    port: edge.dst_port.clone(),
                })?;

            if incoming[dst_ix][port_ix].is_some() {
                return Err(BuildError::DuplicateEdge {
                    node: edge.dst.clone(),
                    port: edge.dst_port.clone(),
                });
            }

            incoming[dst_ix][port_ix] = Some(src_ix);
            outgoing[src_ix].push(dst_ix);
        }

        // Required-port check.
        for (ix, (id, node)) in self.nodes.iter().enumerate() {
            for (port_ix, port) in node.inputs().iter().enumerate() {
                if !port.optional && incoming[ix][port_ix].is_none() {
                    return Err(BuildError::MissingInput {
                        node: id.clone(),
                        port: port.name.to_string(),
                    });
                }
            }
        }

        let topo = topo_sort(n, &incoming, &self.nodes)?;

        // Pass 2: walk topo order, resolve each node's output kind from
        // its (already-resolved) upstream kinds, and check the upstream
        // kind against each input port's `accepts` list.
        let mut output_kinds: Vec<PortKind> = vec![PortKind::Raster; n];
        for &ix in &topo {
            let (id, node) = self.nodes.get_index(ix).expect("ix from topo is in range");
            let specs = node.inputs();
            let mut input_kinds: Vec<Option<PortKind>> = Vec::with_capacity(specs.len());
            for (port_ix, spec) in specs.iter().enumerate() {
                match incoming[ix][port_ix] {
                    Some(src_ix) => {
                        let src_kind = output_kinds[src_ix];
                        if !spec.accepts_kind(src_kind) {
                            let (src_id, _) = self
                                .nodes
                                .get_index(src_ix)
                                .expect("src_ix from incoming is in range");
                            return Err(BuildError::TypeMismatch {
                                node: id.clone(),
                                port: spec.name.to_string(),
                                src: src_id.clone(),
                                accepts: spec.accepts.to_vec(),
                                got: src_kind,
                            });
                        }
                        input_kinds.push(Some(src_kind));
                    }
                    None => input_kinds.push(None),
                }
            }
            output_kinds[ix] = node.output(&input_kinds);
        }

        let output_id = self.output.ok_or(BuildError::NoOutput)?;
        let output_ix = ix_of(&output_id).ok_or(BuildError::UnknownOutput(output_id.clone()))?;
        // Document output must be a canvas-padded raster — anything
        // smaller (e.g. a raw `Sprite`) will alias badly through the
        // host's `raster_to_png` crop. Catch this at build time.
        let output_kind = output_kinds[output_ix];
        if output_kind != PortKind::Raster {
            return Err(BuildError::OutputKindMismatch {
                node: output_id.clone(),
                got: output_kind,
            });
        }

        Ok(Graph {
            nodes: self.nodes,
            incoming,
            outgoing,
            output: output_ix,
            topo,
            output_kinds,
        })
    }
}

impl Default for GraphBuilder {
    fn default() -> Self {
        Self::new()
    }
}

fn topo_sort(
    n: usize,
    incoming: &[Vec<Option<NodeIx>>],
    nodes: &IndexMap<NodeId, Box<dyn Node>>,
) -> Result<Vec<NodeIx>, BuildError> {
    // Kahn's algorithm over the unique upstream set per node.
    let mut indegree: Vec<usize> = incoming
        .iter()
        .map(|ports| {
            let mut srcs: Vec<NodeIx> = ports.iter().filter_map(|p| *p).collect();
            srcs.sort_unstable();
            srcs.dedup();
            srcs.len()
        })
        .collect();

    // Reverse adjacency: for each src, the unique dsts that depend on it.
    let mut rev: Vec<Vec<NodeIx>> = vec![Vec::new(); n];
    for (dst, ports) in incoming.iter().enumerate() {
        let mut srcs: Vec<NodeIx> = ports.iter().filter_map(|p| *p).collect();
        srcs.sort_unstable();
        srcs.dedup();
        for src in srcs {
            rev[src].push(dst);
        }
    }

    let mut queue: VecDeque<NodeIx> = (0..n).filter(|&i| indegree[i] == 0).collect();
    let mut order = Vec::with_capacity(n);
    while let Some(ix) = queue.pop_front() {
        order.push(ix);
        for &dst in &rev[ix] {
            indegree[dst] -= 1;
            if indegree[dst] == 0 {
                queue.push_back(dst);
            }
        }
    }

    if order.len() != n {
        // `order.len() != n` means at least one node still has incoming
        // edges (otherwise topo would have queued it). Find one such
        // node to name in the error.
        let bad = (0..n)
            .find(|&i| indegree[i] != 0)
            .expect("order.len() != n implies some indegree is non-zero");
        let (id, _) = nodes.get_index(bad).expect("bad < n is within nodes range");
        return Err(BuildError::Cycle(id.clone()));
    }
    Ok(order)
}

impl std::fmt::Debug for Graph {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let ids: Vec<&str> = self.nodes.keys().map(String::as_str).collect();
        f.debug_struct("Graph")
            .field("nodes", &ids)
            .field("output", &self.node_id(self.output))
            .field(
                "topo",
                &self
                    .topo
                    .iter()
                    .map(|&i| self.node_id(i))
                    .collect::<Vec<_>>(),
            )
            .finish()
    }
}

impl Graph {
    /// Number of nodes.
    pub fn len(&self) -> usize {
        self.nodes.len()
    }

    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }

    pub fn output(&self) -> NodeIx {
        self.output
    }

    /// Topological order; output node is last.
    pub fn topo_order(&self) -> &[NodeIx] {
        &self.topo
    }

    pub fn node(&self, ix: NodeIx) -> &dyn Node {
        self.nodes
            .get_index(ix)
            .expect("NodeIx is always within self.nodes range")
            .1
            .as_ref()
    }

    pub fn node_id(&self, ix: NodeIx) -> &str {
        self.nodes
            .get_index(ix)
            .expect("NodeIx is always within self.nodes range")
            .0
    }

    /// Upstream nodes feeding `ix`, deduplicated.
    pub fn upstream(&self, ix: NodeIx) -> impl Iterator<Item = NodeIx> + '_ {
        let mut srcs: Vec<NodeIx> = self.incoming[ix].iter().filter_map(|p| *p).collect();
        srcs.sort_unstable();
        srcs.dedup();
        srcs.into_iter()
    }

    /// Downstream nodes consuming `ix`'s output (may contain duplicates
    /// if the same node connects multiple of its input ports to `ix`).
    pub fn downstream(&self, ix: NodeIx) -> &[NodeIx] {
        &self.outgoing[ix]
    }

    /// The source feeding `node.inputs()[port_ix]`, if connected.
    pub fn incoming(&self, ix: NodeIx, port_ix: usize) -> Option<NodeIx> {
        self.incoming[ix][port_ix]
    }

    /// Resolved output [`PortKind`] for `ix`. Decided at build time;
    /// polymorphic nodes' kind is fixed once the graph is built.
    pub fn output_kind(&self, ix: NodeIx) -> PortKind {
        self.output_kinds[ix]
    }

    /// Group nodes into evaluation "levels". A node's level is one more
    /// than the maximum level of its inputs (sources are at level 0).
    /// All nodes in the same level have no edges between them and can
    /// be evaluated in parallel. Returned as `levels[node_ix] = depth`.
    pub fn compute_levels(&self) -> Vec<u32> {
        let mut levels = vec![0u32; self.len()];
        for &ix in &self.topo {
            let max_up = self.upstream(ix).map(|s| levels[s] + 1).max().unwrap_or(0);
            levels[ix] = max_up;
        }
        levels
    }

    /// Bucket nodes by level, preserving topo order within each bucket
    /// for determinism.
    pub fn level_buckets(&self) -> Vec<Vec<NodeIx>> {
        let levels = self.compute_levels();
        let max_level = levels.iter().copied().max().unwrap_or(0);
        let mut buckets: Vec<Vec<NodeIx>> = vec![Vec::new(); (max_level + 1) as usize];
        for &ix in &self.topo {
            buckets[levels[ix] as usize].push(ix);
        }
        buckets
    }

    /// Compute the canvas padding each node must supply, given the
    /// document-level `pad` requested at the output.
    pub fn compute_pad(&self, doc_pad: u32) -> Result<Vec<u32>, BuildError> {
        let mut required = vec![0u32; self.len()];
        required[self.output] = doc_pad;
        for &ix in self.topo.iter().rev() {
            let down = required[ix];
            let up = self.node(ix).required_pad(down);
            if up > MAX_PAD {
                return Err(BuildError::PadExceeded {
                    node: self.node_id(ix).to_string(),
                    required: up,
                    limit: MAX_PAD,
                });
            }
            for src in self.upstream(ix) {
                required[src] = required[src].max(up);
            }
        }
        Ok(required)
    }
}