lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
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
//! Actual closed paint ranges from the native serializer's four buffers.

use super::PlannedCall;
use crate::layout::{InkExtent, PaintBatch, PaintBatchRef, Rect};
use crate::render::coordinates::CanonicalPoint;
use crate::render::primitives::{CanonicalMarkers, CanonicalPlannedText};
use crate::render::svg_backend::{CountBuffer, SvgSerializer};
use crate::{Error, Result};

pub(super) struct PaintCapture {
    pub reference: PaintBatchRef,
    pub start: usize,
    pub end: usize,
}

fn bounds(points: impl IntoIterator<Item = (f64, f64)>, outset: f64) -> Result<InkExtent> {
    let mut points = points.into_iter();
    let Some((x, y)) = points.next() else {
        return Ok(InkExtent::Empty);
    };
    let mut edges = [x, y, x, y];
    for (index, (x, y)) in points.enumerate() {
        if index.is_multiple_of(1024) {
            crate::operation::check()?;
        }
        edges[0] = edges[0].min(x);
        edges[1] = edges[1].min(y);
        edges[2] = edges[2].max(x);
        edges[3] = edges[3].max(y);
    }
    let width = edges[2] - edges[0] + 2.0 * outset;
    let height = edges[3] - edges[1] + 2.0 * outset;
    if width <= 0.0 || height <= 0.0 {
        return Ok(InkExtent::Empty);
    }
    Ok(InkExtent::Bounds(Rect::new(
        edges[0] - outset,
        edges[1] - outset,
        width,
        height,
    )?))
}

fn coordinates(points: &[CanonicalPoint]) -> impl Iterator<Item = (f64, f64)> + '_ {
    points
        .iter()
        .map(|point| (point.x.value(), point.y.value()))
}

fn stroke(paint: crate::Color, width: f64) -> f64 {
    if paint.get_alpha() > 0.0 {
        width
    } else {
        0.0
    }
}

#[expect(
    clippy::cast_precision_loss,
    reason = "frozen glyph bounds are exact spatial quanta"
)]
fn text_extent(text: &CanonicalPlannedText, clip: Rect) -> Result<InkExtent> {
    let text = &text.0;
    if text.suppressed || text.text.style.paint.get_alpha() == 0.0 {
        return Ok(InkExtent::Empty);
    }
    let clip = if let Some(local) = text.clip {
        let Some(clip) = clip.intersection(Rect::from_canonical(local)?) else {
            return Ok(InkExtent::Empty);
        };
        clip
    } else {
        clip
    };
    let center = text.center.value();
    let (sin, cos) = text.rotation_sin_cos;
    let mut ink = InkExtent::Empty;
    for (line, placed) in text.text.lines.iter().zip(&text.lines) {
        let Some(extent) = line.ink_quanta else {
            continue;
        };
        let origin = placed.origin.value();
        let left = origin.x + extent.left as f64 / 1024.;
        let right = origin.x + extent.right as f64 / 1024.;
        let top = origin.y - extent.top as f64 / 1024.;
        let bottom = origin.y - extent.bottom as f64 / 1024.;
        let corners = [(left, top), (left, bottom), (right, top), (right, bottom)];
        ink = ink.union(
            bounds(
                corners.map(|(x, y)| {
                    let x = x - center.x;
                    let y = y - center.y;
                    (center.x + x * cos - y * sin, center.y + x * sin + y * cos)
                }),
                0.,
            )?
            .clipped(clip),
        );
    }
    Ok(ink)
}

// Clip each independent marker or line segment before taking the aggregate
// envelope. An aggregate may straddle the viewport although every member is
// outside it. No per-member index is retained in the report.
fn path_extents<'a>(
    paths: impl IntoIterator<Item = &'a [CanonicalPoint]>,
    outset: f64,
    clip: Rect,
) -> Result<InkExtent> {
    let mut ink = InkExtent::Empty;
    for (index, path) in paths.into_iter().enumerate() {
        if index.is_multiple_of(1024) {
            crate::operation::check()?;
        }
        ink = ink.union(bounds(coordinates(path), outset)?.clipped(clip));
    }
    Ok(ink)
}

fn extent(call: &PlannedCall, viewport: Rect, clip: Rect) -> Result<InkExtent> {
    use crate::render::backend::SurfaceRole;
    Ok(match call {
        PlannedCall::Surface {
            bounds,
            paint,
            role,
        } => {
            if paint.get_alpha() == 0.0 {
                InkExtent::Empty
            } else if *role == SurfaceRole::CanvasRoot {
                InkExtent::Bounds(viewport)
            } else {
                InkExtent::Bounds(Rect::from_canonical(*bounds)?)
            }
        }
        PlannedCall::Scatter(scatter) => {
            let stroke = scatter
                .outline
                .map_or(0., |(paint, width)| stroke(paint, width.value()));
            if scatter.color.get_alpha() == 0.0 && stroke == 0.0 {
                InkExtent::Empty
            } else {
                match &scatter.markers {
                    CanonicalMarkers::Circles { points, radius } => path_extents(
                        points.iter().map(std::slice::from_ref),
                        radius.value() + stroke / 2.,
                        clip,
                    )?,
                    CanonicalMarkers::Triangles(triangles) => path_extents(
                        triangles.iter().map(<[CanonicalPoint; 3]>::as_slice),
                        stroke * crate::render::backend::POLYGON_MITER_LIMIT / 2.,
                        clip,
                    )?,
                }
            }
        }
        PlannedCall::Line { points, style } => {
            let stroke = stroke(style.color, style.width.value());
            if stroke == 0.0 {
                InkExtent::Empty
            } else {
                path_extents(points.windows(2), stroke / 2., clip)?
            }
        }
        PlannedCall::Polygon { points, style } => {
            let stroke = if points.windows(2).any(|pair| pair[0] != pair[1]) {
                stroke(style.stroke, style.stroke_width.value())
            } else {
                0.
            };
            if stroke == 0.0
                && (style.color.get_alpha() == 0.0
                    || !crate::render::geometry::polygon_has_positive_area(points)?)
            {
                InkExtent::Empty
            } else {
                bounds(
                    coordinates(points),
                    stroke * crate::render::backend::POLYGON_MITER_LIMIT / 2.,
                )?
            }
        }
        PlannedCall::LinearGradient(gradient) => {
            InkExtent::Bounds(Rect::from_canonical(gradient.bounds)?)
        }
        PlannedCall::PlannedText(text) => text_extent(&text.canonical, clip)?,
        PlannedCall::RoundedRect(rounded) => {
            let stroke = stroke(rounded.stroke, rounded.stroke_width.value());
            if rounded.bounds.width.units() == 0
                || rounded.bounds.height.units() == 0
                || (rounded.color.get_alpha() == 0.0 && stroke == 0.0)
            {
                InkExtent::Empty
            } else {
                let rect = Rect::from_canonical(rounded.bounds)?;
                bounds(
                    [
                        (rect.left(), rect.top()),
                        (rect.left() + rect.width(), rect.top() + rect.height()),
                    ],
                    stroke / 2.,
                )?
            }
        }
        PlannedCall::PlannedBracket(bracket) => {
            let canonical = &bracket.canonical;
            let stroke = stroke(canonical.color, canonical.width.value());
            let path = if stroke == 0.0 {
                InkExtent::Empty
            } else {
                bounds(coordinates(&canonical.points), stroke / 2.)?
            };
            path.union(text_extent(&canonical.text, clip)?)
        }
        PlannedCall::Fixed(content) => content.ink(),
        _ => InkExtent::Empty,
    })
}

fn batch_geometry(calls: &[PlannedCall], viewport: Rect) -> Result<(InkExtent, Vec<Rect>)> {
    let mut ink = InkExtent::Empty;
    let mut clips = Vec::new();
    let mut stack = vec![Some(viewport)];
    for (index, call) in calls.iter().enumerate() {
        if index.is_multiple_of(64) {
            crate::operation::checkpoint()?;
        }
        match call {
            PlannedCall::BeginClip(clip) => {
                let rect = Rect::from_canonical(*clip)?;
                crate::data::source::reserve_source(&mut clips, 1)?;
                clips.push(rect);
                let effective = stack
                    .last()
                    .copied()
                    .flatten()
                    .and_then(|prior| prior.intersection(rect));
                crate::data::source::reserve_source(&mut stack, 1)?;
                stack.push(effective);
            }
            PlannedCall::EndClip => {
                stack.pop();
            }
            _ => {
                if let PlannedCall::Fixed(content) = call {
                    crate::data::source::reserve_source(&mut clips, 1)?;
                    clips.push(content.frame);
                }
                let text_clip = match call {
                    PlannedCall::PlannedText(text) => text.canonical.0.clip,
                    PlannedCall::PlannedBracket(bracket) => bracket.canonical.text.0.clip,
                    _ => None,
                };
                if let Some(clip) = text_clip {
                    crate::data::source::reserve_source(&mut clips, 1)?;
                    clips.push(Rect::from_canonical(clip)?);
                }
                if let Some(clip) = stack.last().copied().flatten() {
                    ink = ink.union(extent(call, viewport, clip)?.clipped(clip));
                }
            }
        }
    }
    if stack.len() != 1 {
        return Err(Error::Render("paint batch has unclosed clip scopes".into()));
    }
    Ok((ink, clips))
}

fn emit_calls(calls: &[PlannedCall], serializer: &mut SvgSerializer<CountBuffer>) -> Result<()> {
    for call in calls {
        call.emit_svg(serializer)?;
        #[cfg(test)]
        serializer.overflow_count_after_text_for_test();
    }
    Ok(())
}

// Counting and actual emission use the same admitted native calls. The
// serialization buffers reorder root paper, panel paper and grids before the
// ordinary body. Record their physical ranges here rather than infer order
// from SVG element names or equal clip rectangles.
pub(super) fn emit(
    calls: &[PlannedCall],
    captures: &[PaintCapture],
    serializer: &mut SvgSerializer<CountBuffer>,
    viewport: Option<Rect>,
) -> Result<Vec<PaintBatch>> {
    let Some(viewport) = viewport else {
        emit_calls(calls, serializer)?;
        return Ok(Vec::new());
    };
    let mut batches = Vec::new();
    crate::data::source::reserve_source(&mut batches, captures.len())?;
    let mut cursor = 0;
    for capture in captures {
        if cursor != capture.start || serializer.paint_scope_depth() != 0 {
            return Err(Error::Render(
                "native paint inventory has an unclosed or unowned range".into(),
            ));
        }
        let before = serializer.paint_offsets();
        let batch_calls = &calls[capture.start..capture.end];
        emit_calls(batch_calls, serializer)?;
        cursor = capture.end;
        if serializer.paint_scope_depth() != 0 {
            return Err(Error::Render(
                "native paint batch leaves a scope open".into(),
            ));
        }
        let (ink, clips) = batch_geometry(batch_calls, viewport)?;
        if ink == InkExtent::Empty {
            continue;
        }
        let after = serializer.paint_offsets();
        let mut changed = (0..before.len()).filter(|&index| before[index] != after[index]);
        let buffer = changed
            .next()
            .ok_or_else(|| Error::Render("painted batch produced no native paint range".into()))?;
        if changed.next().is_some() {
            return Err(Error::Render(
                "paint batch crosses reordered native emission buffers".into(),
            ));
        }
        batches.push(PaintBatch {
            reference: capture.reference.clone(),
            clips,
            ink,
            buffer,
            range: before[buffer]..after[buffer],
        });
    }
    if cursor != calls.len() {
        return Err(Error::Render(
            "native paint inventory omitted final drawing calls".into(),
        ));
    }
    Ok(batches)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::render::{
        coordinates::{CanonicalBox, CanonicalCoordinate, CanonicalRoundedBox},
        primitives::{CanonicalFillStyle, CanonicalScatter},
    };
    use crate::Color;

    fn point(x: i64, y: i64) -> CanonicalPoint {
        CanonicalPoint {
            x: CanonicalCoordinate::from_quanta(x * 1024),
            y: CanonicalCoordinate::from_quanta(y * 1024),
        }
    }

    #[test]
    fn individually_clipped_markers_do_not_manufacture_an_ink_extent() {
        let viewport = Rect::new(0., 0., 100., 100.).unwrap();
        let call = PlannedCall::Scatter(CanonicalScatter {
            markers: CanonicalMarkers::Circles {
                points: vec![point(-10, 50), point(110, 50)],
                radius: CanonicalCoordinate::from_quanta(1024),
            },
            color: Color::rgb(0, 0, 0),
            outline: None,
        });
        assert_eq!(
            batch_geometry(&[call], viewport).unwrap().0,
            InkExtent::Empty
        );
    }

    #[test]
    fn retraced_polygon_and_degenerate_rectangle_have_no_ink() {
        let viewport = Rect::new(0., 0., 100., 100.).unwrap();
        let black = Color::rgb(0, 0, 0);
        let fill = PlannedCall::Polygon {
            points: vec![point(10, 10), point(90, 90), point(50, 50)],
            style: CanonicalFillStyle {
                color: black,
                stroke: black,
                stroke_width: CanonicalCoordinate::from_quanta(0),
            },
        };
        assert_eq!(extent(&fill, viewport, viewport).unwrap(), InkExtent::Empty);
        let zero = CanonicalCoordinate::from_quanta(0);
        let rounded = PlannedCall::RoundedRect(CanonicalRoundedBox {
            bounds: CanonicalBox {
                x: zero,
                y: zero,
                width: CanonicalCoordinate::from_quanta(10 * 1024),
                height: zero,
            },
            radius: zero,
            stroke_width: CanonicalCoordinate::from_quanta(1024),
            color: black,
            stroke: black,
        });
        assert_eq!(
            extent(&rounded, viewport, viewport).unwrap(),
            InkExtent::Empty
        );
    }
}