canvist_paint 0.2.0

Rendering for the canvist canvas: a culled, level-of-detail scene walker over vello (GPU), vello_cpu (PNG), and SVG backends
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! The scene walker: one page of a scene, culled to the viewport, as
//! [`Painter`] calls in paint order.
//!
//! Subtrees outside the viewport are skipped by their extent. Nodes smaller
//! than a pixel on screen are skipped; nodes smaller than [`LOD_PIXELS`]
//! draw as a box in their main colour; text smaller than
//! [`GREEK_PIXELS`](crate::GREEK_PIXELS) draws as bars. In
//! [`Quality::Interactive`] (while the camera moves) shadows are skipped
//! too.

use std::borrow::Cow;

use canvist_canvas::Camera;
use canvist_canvas::NodeGeometry;
use canvist_canvas::SceneIndex;
use canvist_canvas::TextLayouts;
use canvist_scene::EffectKind;
use canvist_scene::Node;
use canvist_scene::NodeId;
use canvist_scene::NodeKind;
use canvist_scene::Paint;
use canvist_scene::PaintKind;
use canvist_scene::Props;
use canvist_scene::Scene;
use canvist_scene::Shape;
use canvist_scene::StrokeAlign;
use kurbo::Affine;
use kurbo::BezPath;
use kurbo::Point;
use kurbo::Rect;
use kurbo::Shape as _;
use kurbo::Size;
use peniko::Brush;

use crate::Assets;
use crate::convert;
use crate::display::DisplayStyle;
use crate::display::paint_display_list;
use crate::painter::BoxShadow;
use crate::painter::Draw;
use crate::painter::Image;
use crate::painter::Layer;
use crate::painter::Painter;

/// Nodes smaller than this many screen pixels are not drawn.
pub const MIN_PIXELS: f64 = 0.5;
/// Nodes smaller than this many screen pixels draw as a box in their main
/// colour.
pub const LOD_PIXELS: f64 = 3.0;
/// How deeply instances may nest before the walker stops, so a component
/// that contains an instance of itself cannot recurse forever.
const MAX_INSTANCE_DEPTH: usize = 8;
/// The light grey shown where an image has not loaded.
const PLACEHOLDER: peniko::Color = peniko::Color::from_rgba8(229, 229, 229, 255);

/// How much detail to draw.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Quality {
	/// Everything.
	#[default]
	Full,
	/// Skip shadows, for frames drawn while the camera moves.
	Interactive,
}

/// What to draw: a camera over a viewport.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct View {
	/// The camera.
	pub camera: Camera,
	/// The viewport size in screen pixels.
	pub viewport: Size,
	/// How much detail to draw.
	pub quality: Quality,
}

/// The scene and everything derived from it that painting reads.
#[derive(Clone, Copy, Debug)]
pub struct Sources<'a> {
	/// The scene.
	pub scene: &'a Scene,
	/// Its index.
	pub index: &'a SceneIndex,
	/// Its text frame layouts.
	pub texts: &'a TextLayouts,
	/// Decoded images by asset id.
	pub assets: &'a Assets,
}

/// Paint `page` as `view` sees it.
pub fn paint_page<P: Painter + ?Sized>(
	painter: &mut P,
	sources: &Sources<'_>,
	page: NodeId,
	view: &View,
) {
	let visible = view.camera.visible(view.viewport);
	let mut walker = Walker {
		painter,
		sources,
		view,
		visible,
		to_screen: view.camera.world_to_screen(),
		depth: 0,
	};

	walker.background(page);

	for &child in sources.scene.children(page) {
		walker.walk(child, &Placement::default());
	}
}

/// Paint the subtrees of `nodes` with `world_to_target` mapping world
/// coordinates to the output, with no culling: for exports.
pub fn paint_nodes<P: Painter + ?Sized>(
	painter: &mut P,
	sources: &Sources<'_>,
	nodes: &[NodeId],
	world_to_target: Affine,
) {
	let view = View {
		camera: Camera::default(),
		viewport: Size::new(f64::MAX, f64::MAX),
		quality: Quality::Full,
	};
	let mut walker = Walker {
		painter,
		sources,
		view: &view,
		visible: Rect::new(f64::MIN, f64::MIN, f64::MAX, f64::MAX),
		to_screen: world_to_target,
		depth: 0,
	};

	for &node in nodes {
		walker.walk(node, &Placement::default());
	}
}

/// Where a subtree is drawn from: an instance places its component's nodes
/// elsewhere and overrides their props.
#[derive(Clone, Default)]
struct Placement<'a> {
	/// Applied before each node's world transform.
	extra: Option<Affine>,
	/// The instance whose overrides apply.
	instance: Option<&'a Props>,
}

/// A shape being painted: its outline, its box size, and where it goes.
struct Surface<'a> {
	outline: &'a BezPath,
	size: kurbo::Vec2,
	transform: Affine,
}

struct Walker<'a, P: ?Sized> {
	painter: &'a mut P,
	sources: &'a Sources<'a>,
	view: &'a View,
	visible: Rect,
	to_screen: Affine,
	depth: usize,
}

impl<P: Painter + ?Sized> Walker<'_, P> {
	/// Fill the viewport with the page's fills.
	fn background(&mut self, page: NodeId) {
		let Some(node) = self.sources.scene.node(page) else {
			return;
		};
		let area = self.visible.to_path(geometry_tolerance());
		let origin = Affine::translate(self.visible.origin().to_vec2());

		for paint in node.props().fills.iter().filter(|paint| paint.visible) {
			if let Some((brush, unit)) = convert::brush(paint, self.visible.size().to_vec2()) {
				let brush_transform = unit.map(|unit| origin * unit);
				self.painter.fill(
					&draw(&area, self.to_screen, &brush, brush_transform),
					peniko::Fill::NonZero,
				);
			}
		}
	}

	fn walk(&mut self, id: NodeId, placement: &Placement<'_>) {
		let scene = self.sources.scene;
		let (Some(node), Some(geometry)) = (scene.node(id), self.sources.index.get(id)) else {
			return;
		};
		let props = effective_props(node, placement.instance);

		if !props.visible {
			return;
		}

		let world = placement
			.extra
			.map_or(geometry.world, |extra| extra * geometry.world);
		let extent = placement.extra.map_or(geometry.extent, |extra| {
			transformed_bounds(extra, geometry.extent)
		});

		if !extent.overlaps(self.visible) && !extent.contains(self.visible.origin()) {
			return;
		}

		let pixels = extent.width().max(extent.height()) * self.view.camera.zoom;

		if pixels < MIN_PIXELS {
			return;
		}

		let transform = self.to_screen * world;
		let kind = scene.kind(id).unwrap_or(NodeKind::Group);
		let leaf = scene.children(id).is_empty();

		if pixels < LOD_PIXELS && leaf {
			self.summary(geometry, &props, transform);

			return;
		}

		let layered = self.open_layer(&props, geometry, transform, leaf);
		self.body(id, kind, &props, geometry, transform);
		self.children(id, kind, &props, world, placement);

		if layered {
			self.painter.pop_layer();
		}
	}

	/// Draw a node too small to detail as its box in its main colour.
	fn summary(&mut self, geometry: &NodeGeometry, props: &Props, transform: Affine) {
		let Some(color) = convert::summary_color(&props.fills) else {
			return;
		};
		let size = geometry.size;
		let rect =
			Rect::new(0.0, 0.0, size.x.max(1.0), size.y.max(1.0)).to_path(geometry_tolerance());
		self.painter.fill(
			&draw(&rect, transform, &Brush::Solid(color), None),
			peniko::Fill::NonZero,
		);
	}

	/// Start a layer when the node fades, blends, or clips its children.
	fn open_layer(
		&mut self,
		props: &Props,
		geometry: &NodeGeometry,
		transform: Affine,
		leaf: bool,
	) -> bool {
		let clips = props.clip && !leaf;
		let needed =
			props.opacity < 1.0 || props.blend != canvist_scene::BlendMode::Normal || clips;

		if !needed {
			return false;
		}

		let clip = clips.then_some(geometry.outline.as_deref()).flatten();
		self.painter.push_layer(&Layer {
			clip,
			transform,
			blend: convert::blend(props.blend),
			alpha: props.opacity as f32,
		});
		true
	}

	fn body(
		&mut self,
		id: NodeId,
		kind: NodeKind,
		props: &Props,
		geometry: &NodeGeometry,
		transform: Affine,
	) {
		if self.view.quality == Quality::Full {
			self.shadows(props, geometry, transform);
		}

		let Some(outline) = geometry.outline.as_deref() else {
			return;
		};
		let surface = Surface {
			outline,
			size: geometry.size,
			transform,
		};

		// Outside strokes go behind the fill, the others on top of it.
		self.strokes(&surface, props, StrokeAlign::Outside);
		self.fills(&surface, props, kind);
		self.strokes(&surface, props, StrokeAlign::Center);
		self.strokes(&surface, props, StrokeAlign::Inside);

		if kind == NodeKind::Text {
			self.text(id, props, transform);
		}
	}

	fn shadows(&mut self, props: &Props, geometry: &NodeGeometry, transform: Affine) {
		let radius = props.radius.iter().copied().fold(0.0, f64::max);

		for effect in props.effects.iter().filter(|effect| effect.visible) {
			let EffectKind::DropShadow(shadow) = effect.kind else {
				continue;
			};
			let rect = Rect::from_origin_size(Point::ORIGIN, geometry.size.to_size())
				.inflate(shadow.spread, shadow.spread)
				+ shadow.offset;

			self.painter.shadow(&BoxShadow {
				rect,
				radius,
				transform,
				color: convert::color(shadow.color),
				blur: shadow.blur,
			});
		}
	}

	/// Paint each visible fill. Text frames' fills colour their text instead.
	fn fills(&mut self, surface: &Surface<'_>, props: &Props, kind: NodeKind) {
		if kind == NodeKind::Text {
			return;
		}

		let rule = convert::fill_rule(crate::fill_rule_of(&props.shape));

		for paint in props.fills.iter().filter(|paint| paint.visible) {
			match &paint.kind {
				PaintKind::Image { asset, fit } => {
					self.image_fill(surface, asset, *fit, paint.opacity);
				}
				_ => self.blended(paint, |painter| solid_fill(painter, surface, paint, rule)),
			}
		}
	}

	/// Run `paint_with` inside a blend layer when the paint blends.
	fn blended(&mut self, paint: &Paint, paint_with: impl FnOnce(&mut P)) {
		let layered = paint.blend != canvist_scene::BlendMode::Normal;

		if layered {
			self.painter.push_layer(&Layer {
				clip: None,
				transform: Affine::IDENTITY,
				blend: convert::blend(paint.blend),
				alpha: 1.0,
			});
		}

		paint_with(self.painter);

		if layered {
			self.painter.pop_layer();
		}
	}

	/// An image paint, clipped to the outline and placed by its fit.
	fn image_fill(
		&mut self,
		surface: &Surface<'_>,
		asset: &str,
		fit: canvist_scene::ImageFit,
		opacity: f64,
	) {
		let Some(data) = self.sources.assets.get(asset) else {
			self.placeholder(surface);

			return;
		};
		let image_size = Size::new(f64::from(data.width), f64::from(data.height));
		let placed = crate::fit::image_transform(fit, image_size, surface.size.to_size());

		self.painter.push_layer(&clip_layer(surface));
		self.painter.image(&Image {
			asset,
			data,
			transform: surface.transform * placed,
			alpha: opacity as f32,
		});
		self.painter.pop_layer();
	}

	/// A light grey box where an image that is not loaded goes.
	fn placeholder(&mut self, surface: &Surface<'_>) {
		let grey = Brush::Solid(PLACEHOLDER);
		self.painter.fill(
			&draw(surface.outline, surface.transform, &grey, None),
			peniko::Fill::NonZero,
		);
	}

	/// Paint the strokes aligned with `align`. Inside and outside strokes
	/// draw twice as wide: inside ones clipped to the outline, outside ones
	/// behind the fill.
	fn strokes(&mut self, surface: &Surface<'_>, props: &Props, align: StrokeAlign) {
		if props.stroke.align != align || props.stroke.width <= 0.0 {
			return;
		}

		let scale = if align == StrokeAlign::Center {
			1.0
		} else {
			2.0
		};

		let style = convert::stroke(&props.stroke, scale);
		let clipped = align == StrokeAlign::Inside;

		if clipped {
			self.painter.push_layer(&clip_layer(surface));
		}

		for paint in props.strokes.iter().filter(|paint| paint.visible) {
			let Some((brush, brush_transform)) = convert::brush(paint, surface.size) else {
				continue;
			};
			self.painter.stroke(
				&draw(surface.outline, surface.transform, &brush, brush_transform),
				&style,
			);
		}

		if clipped {
			self.painter.pop_layer();
		}
	}

	/// Draw a text frame's laid-out runs, decorations, and backgrounds.
	fn text(&mut self, id: NodeId, props: &Props, transform: Affine) {
		let Some(frame) = self.sources.texts.get(id) else {
			return;
		};
		let style = DisplayStyle {
			transform,
			fill: convert::summary_color(&props.fills),
		};

		paint_display_list(self.painter, &frame.display, &style);
	}

	fn children(
		&mut self,
		id: NodeId,
		kind: NodeKind,
		props: &Props,
		world: Affine,
		placement: &Placement<'_>,
	) {
		match kind {
			// A boolean's children draw only as its outline.
			NodeKind::Boolean => {}
			NodeKind::Instance => self.instance(props, world),
			_ => self.walk_all(self.sources.scene.children(id), placement),
		}
	}

	fn walk_all(&mut self, ids: &[NodeId], placement: &Placement<'_>) {
		for &child in ids {
			self.walk(child, placement);
		}
	}

	/// Draw an instance's component in the instance's place, with its
	/// overrides.
	fn instance(&mut self, props: &Props, world: Affine) {
		let Shape::Instance { component } = props.shape else {
			return;
		};
		let Some(source) = self.sources.index.get(component) else {
			return;
		};

		if self.depth >= MAX_INSTANCE_DEPTH {
			return;
		}

		let placement = Placement {
			extra: Some(world * source.world.inverse()),
			instance: Some(props),
		};
		self.depth += 1;
		self.walk(component, &placement);
		self.depth -= 1;
	}
}

/// Fill `surface` with a non-image paint.
fn solid_fill<P: Painter + ?Sized>(
	painter: &mut P,
	surface: &Surface<'_>,
	paint: &Paint,
	rule: peniko::Fill,
) {
	if let Some((brush, brush_transform)) = convert::brush(paint, surface.size) {
		painter.fill(
			&draw(surface.outline, surface.transform, &brush, brush_transform),
			rule,
		);
	}
}

/// A plain layer clipped to `surface`'s outline.
fn clip_layer<'a>(surface: &Surface<'a>) -> Layer<'a> {
	Layer {
		clip: Some(surface.outline),
		transform: surface.transform,
		blend: peniko::BlendMode::default(),
		alpha: 1.0,
	}
}

/// A node's props with an instance's overrides for it applied.
fn effective_props<'a>(node: &'a Node, instance: Option<&Props>) -> Cow<'a, Props> {
	let Some(instance) = instance else {
		return Cow::Borrowed(node.props());
	};
	let overrides: Vec<_> = instance
		.overrides
		.iter()
		.filter(|((target, _), _)| *target == node.id())
		.map(|(_, prop)| prop.clone())
		.collect();

	if overrides.is_empty() {
		return Cow::Borrowed(node.props());
	}

	let mut props = node.props().clone();

	for prop in overrides {
		props.set(prop);
	}

	Cow::Owned(props)
}

fn draw<'a>(
	path: &'a BezPath,
	transform: Affine,
	brush: &'a Brush,
	brush_transform: Option<Affine>,
) -> Draw<'a> {
	Draw {
		path,
		transform,
		brush,
		brush_transform,
	}
}

/// The bounding box of `rect` after `transform`.
fn transformed_bounds(transform: Affine, rect: Rect) -> Rect {
	let corners = [
		Point::new(rect.x0, rect.y0),
		Point::new(rect.x1, rect.y0),
		Point::new(rect.x1, rect.y1),
		Point::new(rect.x0, rect.y1),
	]
	.map(|corner| transform * corner);

	corners.iter().skip(1).fold(
		Rect::from_points(corners[0], corners[0]),
		|bounds, &corner| bounds.union_pt(corner),
	)
}

fn geometry_tolerance() -> f64 {
	canvist_canvas::geometry::TOLERANCE
}