oxframe-2d 0.20.0

2D scene graph and nodes for oxframe
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
446
447
448
449
450
//! A frame's draw list as a pass graph.
//!
//! Vector items stay in one pass. A layer (opacity on a group, a blend, a
//! blur, a shadow, a clip) becomes a composite pass that runs after the
//! vector pass of its contents. A shader node is painted into an image in
//! that vector pass. A shader that reads the frame, or an effect on a
//! node, is an effect pass: it runs on the pixels drawn before it.

use std::hash::{Hash, Hasher};

use kurbo::PathEl;
use oxframe_core::BlendMode;

use crate::draw::{DrawItem, Paint, Primitive, StrokeStyle};
use crate::graph::NodeId;

/// What a pass draws.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PassKind {
    /// Fills, strokes and images, in paint order, into the current target.
    Vector,
    /// A layer composited over the target after its contents.
    Composite,
    /// A shader run on drawn pixels: the frame so far (`lens_drops`), or a
    /// node drawn alone (`ripple`), which is then laid over the frame.
    Effect,
}

impl PassKind {
    /// `"vector"`, `"composite"` or `"effect"`.
    pub fn name(self) -> &'static str {
        match self {
            Self::Vector => "vector",
            Self::Composite => "composite",
            Self::Effect => "effect",
        }
    }
}

/// One pass in topological order: contents before the composite that uses them.
#[derive(Debug, Clone, PartialEq)]
pub struct Pass {
    /// Vector or composite.
    pub kind: PassKind,
    /// Node that opened the layer. The root vector pass uses the view.
    pub node: NodeId,
    /// Draw items this pass owns. A composite counts the items inside it.
    pub items: u32,
    /// Nesting. 0 is the frame.
    pub depth: u32,
    /// Layer opacity. 1 for a vector pass.
    pub opacity: f64,
    /// Layer blend. `"normal"` for a vector pass.
    pub blend: &'static str,
    /// The layer blurs, clips or casts a shadow.
    pub filtered: bool,
    /// Shader of an effect pass, such as `"lens_drops"` or `"ripple"`.
    pub shader: Option<&'static str>,
}

/// Passes for `items`, in the order they must run.
///
/// A list with no layer is exactly one vector pass.
pub fn pass_graph(items: &[DrawItem]) -> Vec<Pass> {
    let mut stack = vec![Scope::frame()];
    for item in items {
        match &item.prim {
            Primitive::PushLayer(layer) => {
                flush(&mut stack);
                stack.push(Scope {
                    node: item.node,
                    items: 0,
                    run: 0,
                    depth: stack.len() as u32,
                    layer: Some(LayerInfo {
                        opacity: layer.opacity,
                        blend: blend_name(layer.blend),
                        filtered: layer.has_filter() || layer.clip.is_some(),
                    }),
                    shader: None,
                    passes: Vec::new(),
                });
            }
            Primitive::BeginEffect(shade) => {
                flush(&mut stack);
                stack.push(Scope {
                    node: item.node,
                    items: 0,
                    run: 0,
                    depth: stack.len() as u32,
                    layer: None,
                    shader: Some(shade.op.name()),
                    passes: Vec::new(),
                });
            }
            Primitive::ReadFrame(shade) => {
                flush(&mut stack);
                let scope = stack.last_mut().expect("frame scope");
                scope.passes.push(Pass {
                    kind: PassKind::Effect,
                    node: item.node,
                    items: 0,
                    depth: scope.depth,
                    opacity: shade.opacity,
                    blend: "normal",
                    filtered: false,
                    shader: Some(shade.op.name()),
                });
            }
            Primitive::PopLayer | Primitive::EndEffect => {
                flush(&mut stack);
                let Some(mut scope) = stack.pop() else {
                    continue;
                };
                if stack.is_empty() {
                    stack.push(scope);
                    continue;
                }
                let info = scope.layer.unwrap_or(LayerInfo {
                    opacity: 1.0,
                    blend: "normal",
                    filtered: false,
                });
                let parent = stack.last_mut().expect("frame scope");
                parent.items += scope.items;
                parent.passes.append(&mut scope.passes);
                parent.passes.push(Pass {
                    kind: if scope.shader.is_some() {
                        PassKind::Effect
                    } else {
                        PassKind::Composite
                    },
                    node: scope.node,
                    items: scope.items,
                    depth: scope.depth - 1,
                    opacity: info.opacity,
                    blend: info.blend,
                    filtered: info.filtered,
                    shader: scope.shader,
                });
            }
            _ => {
                let scope = stack.last_mut().expect("frame scope");
                scope.items += 1;
                scope.run += 1;
            }
        }
    }
    flush(&mut stack);
    let mut passes = stack.pop().map(|s| s.passes).unwrap_or_default();
    if passes.is_empty() {
        passes.push(Pass {
            kind: PassKind::Vector,
            node: NodeId(0),
            items: 0,
            depth: 0,
            opacity: 1.0,
            blend: "normal",
            filtered: false,
            shader: None,
        });
    }
    passes
}

struct LayerInfo {
    opacity: f64,
    blend: &'static str,
    filtered: bool,
}

struct Scope {
    node: NodeId,
    items: u32,
    run: u32,
    depth: u32,
    layer: Option<LayerInfo>,
    shader: Option<&'static str>,
    passes: Vec<Pass>,
}

impl Scope {
    fn frame() -> Self {
        Self {
            node: NodeId(0),
            items: 0,
            run: 0,
            depth: 0,
            layer: None,
            shader: None,
            passes: Vec::new(),
        }
    }
}

fn flush(stack: &mut [Scope]) {
    let Some(scope) = stack.last_mut() else {
        return;
    };
    if scope.run == 0 {
        return;
    }
    let run = scope.run;
    scope.run = 0;
    scope.passes.push(Pass {
        kind: PassKind::Vector,
        node: scope.node,
        items: run,
        depth: scope.depth,
        opacity: 1.0,
        blend: "normal",
        filtered: false,
        shader: None,
    });
}

fn blend_name(blend: BlendMode) -> &'static str {
    match blend {
        BlendMode::Normal => "normal",
        BlendMode::Multiply => "multiply",
        BlendMode::Screen => "screen",
        BlendMode::Overlay => "overlay",
        BlendMode::Darken => "darken",
        BlendMode::Lighten => "lighten",
        BlendMode::ColorDodge => "color_dodge",
        BlendMode::ColorBurn => "color_burn",
        BlendMode::HardLight => "hard_light",
        BlendMode::SoftLight => "soft_light",
        BlendMode::Difference => "difference",
        BlendMode::Exclusion => "exclusion",
        BlendMode::Hue => "hue",
        BlendMode::Saturation => "saturation",
        BlendMode::Color => "color",
        BlendMode::Luminosity => "luminosity",
    }
}

/// Identity of a layer slice, including its `PushLayer` at `start` through the
/// matching `PopLayer`. Used to reuse a layer whose vectors did not change.
pub fn layer_fingerprint(items: &[DrawItem], start: usize) -> u64 {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    let mut depth = 0usize;
    for item in &items[start..] {
        item.node.0.hash(&mut hasher);
        for c in item.transform.as_coeffs() {
            c.to_bits().hash(&mut hasher);
        }
        match &item.prim {
            Primitive::PushLayer(layer) => {
                depth += 1;
                hash_layer(&mut hasher, layer);
            }
            Primitive::PopLayer => {
                2u8.hash(&mut hasher);
                depth -= 1;
                if depth == 0 {
                    break;
                }
            }
            Primitive::Fill { path, paint } => {
                3u8.hash(&mut hasher);
                hash_path(&mut hasher, path);
                hash_paint(&mut hasher, paint);
            }
            Primitive::Stroke { path, paint, style } => {
                4u8.hash(&mut hasher);
                hash_path(&mut hasher, path);
                hash_paint(&mut hasher, paint);
                hash_stroke(&mut hasher, style);
            }
            Primitive::Image {
                image,
                rect,
                opacity,
            } => {
                5u8.hash(&mut hasher);
                image.id.hash(&mut hasher);
                rect.x0.to_bits().hash(&mut hasher);
                rect.y0.to_bits().hash(&mut hasher);
                rect.x1.to_bits().hash(&mut hasher);
                rect.y1.to_bits().hash(&mut hasher);
                opacity.to_bits().hash(&mut hasher);
            }
            Primitive::ReadFrame(_) | Primitive::BeginEffect(_) | Primitive::EndEffect => {
                6u8.hash(&mut hasher);
            }
        }
    }
    hasher.finish()
}

fn hash_layer(hasher: &mut impl Hasher, layer: &crate::draw::Layer) {
    1u8.hash(hasher);
    layer.opacity.to_bits().hash(hasher);
    blend_name(layer.blend).hash(hasher);
    layer.blur.to_bits().hash(hasher);
    if let Some(path) = &layer.clip {
        hash_path(hasher, path);
    }
    if let Some(shadow) = &layer.shadow {
        hash_color(hasher, shadow.color);
        shadow.blur.to_bits().hash(hasher);
        shadow.offset.x.to_bits().hash(hasher);
        shadow.offset.y.to_bits().hash(hasher);
    }
}

fn hash_path(hasher: &mut impl Hasher, path: &kurbo::BezPath) {
    for el in path.elements() {
        match el {
            PathEl::MoveTo(p) => {
                0u8.hash(hasher);
                hash_point(hasher, *p);
            }
            PathEl::LineTo(p) => {
                1u8.hash(hasher);
                hash_point(hasher, *p);
            }
            PathEl::QuadTo(a, b) => {
                2u8.hash(hasher);
                hash_point(hasher, *a);
                hash_point(hasher, *b);
            }
            PathEl::CurveTo(a, b, c) => {
                3u8.hash(hasher);
                hash_point(hasher, *a);
                hash_point(hasher, *b);
                hash_point(hasher, *c);
            }
            PathEl::ClosePath => 4u8.hash(hasher),
        }
    }
}

fn hash_point(hasher: &mut impl Hasher, p: kurbo::Point) {
    p.x.to_bits().hash(hasher);
    p.y.to_bits().hash(hasher);
}

fn hash_paint(hasher: &mut impl Hasher, paint: &Paint) {
    match paint {
        Paint::Solid(c) => {
            0u8.hash(hasher);
            hash_color(hasher, *c);
        }
        Paint::Gradient(g) => {
            1u8.hash(hasher);
            match g.kind {
                oxframe_core::GradientKind::Linear { from, to } => {
                    0u8.hash(hasher);
                    hash_point(hasher, from);
                    hash_point(hasher, to);
                }
                oxframe_core::GradientKind::Radial { center, radius } => {
                    1u8.hash(hasher);
                    hash_point(hasher, center);
                    radius.to_bits().hash(hasher);
                }
            }
            for (offset, color) in &g.stops {
                offset.to_bits().hash(hasher);
                hash_color(hasher, *color);
            }
        }
    }
}

fn hash_color(hasher: &mut impl Hasher, c: oxframe_core::Color) {
    c.r.to_bits().hash(hasher);
    c.g.to_bits().hash(hasher);
    c.b.to_bits().hash(hasher);
    c.a.to_bits().hash(hasher);
}

fn hash_stroke(hasher: &mut impl Hasher, style: &StrokeStyle) {
    style.width.to_bits().hash(hasher);
    cap_tag(style.cap).hash(hasher);
    join_tag(style.join).hash(hasher);
    style.dash_offset.to_bits().hash(hasher);
    for d in &style.dash {
        d.to_bits().hash(hasher);
    }
}

fn cap_tag(cap: crate::draw::LineCap) -> u8 {
    use crate::draw::LineCap::{Butt, Round, Square};
    match cap {
        Butt => 0,
        Round => 1,
        Square => 2,
    }
}

fn join_tag(join: crate::draw::LineJoin) -> u8 {
    use crate::draw::LineJoin::{Bevel, Miter, Round};
    match join {
        Miter => 0,
        Round => 1,
        Bevel => 2,
    }
}

#[cfg(test)]
mod tests {
    use oxframe_core::Color;

    use super::*;
    use crate::graph::SceneGraph;
    use crate::{NodeBuilder, Rect, View};

    #[test]
    fn a_scene_without_effects_is_one_vector_pass() {
        let graph = SceneGraph::new(80, 80);
        graph.enter(|| {
            View::current().add(Rect::new().size(20.0).fill(Color::WHITE));
            View::current().add(Rect::new().size(10.0).x(15.0).fill(Color::BLACK));
        });
        let passes = pass_graph(&graph.draw_list());
        assert_eq!(passes.len(), 1);
        assert_eq!(passes[0].kind, PassKind::Vector);
        assert!(passes[0].items >= 2);
    }

    #[test]
    fn a_blur_is_a_composite_after_its_contents() {
        let graph = SceneGraph::new(80, 80);
        graph.enter(|| {
            View::current().add(
                Rect::new()
                    .size(20.0)
                    .fill(Color::WHITE)
                    .blur(2.0)
                    .name("soft"),
            );
        });
        let passes = pass_graph(&graph.draw_list());
        assert!(
            passes.iter().any(|p| p.kind == PassKind::Vector),
            "{passes:?}"
        );
        let composite = passes
            .iter()
            .find(|p| p.kind == PassKind::Composite)
            .expect("blur opens a layer");
        assert!(composite.filtered);
        let vector_at = passes.iter().position(|p| p.kind == PassKind::Vector);
        let composite_at = passes.iter().position(|p| p.kind == PassKind::Composite);
        assert!(vector_at < composite_at);
    }
}