mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 19:51:26 -05:00
Merge pull request #10972 from dotCooCoo/fix/thumbnail-render-no-copy
Thumbnails: node renders and swatch previews become images without a copy
This commit is contained in:
@@ -47,7 +47,7 @@ pub use effects::stroke::width_outline;
|
||||
pub use fx::pinned_appearance_for_geometry_edit;
|
||||
pub use images::{IMAGE_CACHE_MAX, image_cache_bytes, installed_memory, newly_undecodable, set_image_cache_budget};
|
||||
pub use live::expand_live;
|
||||
pub use pattern::render_pattern_swatch;
|
||||
pub use pattern::{render_pattern_swatch, render_pattern_swatch_words};
|
||||
pub use vectorcraft_effects as effects;
|
||||
pub use vello_cpu;
|
||||
|
||||
|
||||
@@ -243,11 +243,11 @@ pub fn supersample_factor(w: u32, h: u32) -> Option<u32> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Average each `k`×`k` block of `src` (`w`×`h` pixels of 4 premultiplied bytes) into one pixel.
|
||||
pub(crate) fn downsample(src: &[u8], w: usize, h: usize, k: usize) -> Vec<u8> {
|
||||
let (ow, oh) = (w / k.max(1), h / k.max(1));
|
||||
/// Average each `k`×`k` block of `src` (pixels of 4 premultiplied bytes in rows `w` wide) into one
|
||||
/// pixel of `out`, whose rows are `w` / `k` pixels wide.
|
||||
pub(crate) fn downsample(src: &[u8], w: usize, k: usize, out: &mut [u8]) {
|
||||
let ow = w / k.max(1);
|
||||
let n = (k * k).max(1) as u32;
|
||||
let mut out = vec![0u8; ow * oh * 4];
|
||||
for (o, px) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() {
|
||||
let (ox, oy) = (o % ow.max(1), o / ow.max(1));
|
||||
let mut acc = [0u32; 4];
|
||||
@@ -263,7 +263,6 @@ pub(crate) fn downsample(src: &[u8], w: usize, h: usize, k: usize) -> Vec<u8> {
|
||||
*d = ((a + n / 2) / n).min(255) as u8;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// For each of `to` pixels spread over `from` (both above 0), the `from` pixels under it and the
|
||||
|
||||
@@ -28,6 +28,7 @@ use vello_cpu::{Pixmap, RenderContext};
|
||||
|
||||
use crate::ink::Ink;
|
||||
use crate::lru::{self, FrameCache};
|
||||
use crate::renderer::FramePixels;
|
||||
use crate::{Frame, RenderOptions, Rendered, Renderer};
|
||||
|
||||
/// Largest super-tile raster side (pixels).
|
||||
@@ -170,15 +171,21 @@ pub(crate) fn raster_scale(s: f64, period: (f64, f64)) -> f64 {
|
||||
|
||||
/// Rasterize `region` (pattern space) of the infinite tiling into a `w`×`h` pixmap, colours as
|
||||
/// `ink` paints them.
|
||||
fn rasterize(
|
||||
fn rasterize(r: &mut Renderer, doc: &Document, def: &PatternDef, region: Rect, size: (u16, u16), ink: Ink, images: (bool, bool)) -> (Pixmap, bool) {
|
||||
rasterize_as(r, doc, def, (region, size), ink, images, |r, ctx| r.finish(ctx, r.raster))
|
||||
}
|
||||
|
||||
/// [`rasterize`] of `region` into `size` pixels, with the pixels taken from the context by
|
||||
/// `finish`.
|
||||
fn rasterize_as<T>(
|
||||
r: &mut Renderer,
|
||||
doc: &Document,
|
||||
def: &PatternDef,
|
||||
region: Rect,
|
||||
size: (u16, u16),
|
||||
(region, size): (Rect, (u16, u16)),
|
||||
ink: Ink,
|
||||
(mark_undecoded_images, smooth_images): (bool, bool),
|
||||
) -> (Pixmap, bool) {
|
||||
finish: impl FnOnce(&mut Renderer, &mut RenderContext) -> T,
|
||||
) -> (T, bool) {
|
||||
let (w, h) = (size.0.max(1), size.1.max(1));
|
||||
let mut ctx = crate::single_threaded_context(w, h);
|
||||
let view = Affine::scale_non_uniform(w as f64 / region.width().max(1e-9), h as f64 / region.height().max(1e-9))
|
||||
@@ -213,7 +220,7 @@ fn rasterize(
|
||||
r.draw_arc(&mut ctx, &frame, a);
|
||||
}
|
||||
}
|
||||
(r.finish(&mut ctx, r.raster), r.image_left_out.take().unwrap_or(false) || images_left_out() > pattern_images_left_out)
|
||||
(finish(r, &mut ctx), r.image_left_out.take().unwrap_or(false) || images_left_out() > pattern_images_left_out)
|
||||
}
|
||||
|
||||
/// Run `f` with the shared off-screen renderer (None when nested too deep: a pattern whose art
|
||||
@@ -334,13 +341,23 @@ pub(crate) fn set_pattern_paint(ctx: &mut RenderContext, name: &str, xf: Affine,
|
||||
|
||||
/// A swatch thumbnail of pattern `name`: the tiling around the tile, fitted into `size`².
|
||||
pub fn render_pattern_swatch(doc: &Document, name: &str, size: u32) -> Option<Rendered> {
|
||||
pattern_swatch(doc, name, size)
|
||||
}
|
||||
|
||||
/// [`render_pattern_swatch`] with the pixels in words of four bytes, as
|
||||
/// [`Renderer::render_words`] returns them.
|
||||
pub fn render_pattern_swatch_words(doc: &Document, name: &str, size: u32) -> Option<Rendered<Vec<u32>>> {
|
||||
pattern_swatch(doc, name, size)
|
||||
}
|
||||
|
||||
fn pattern_swatch<P: FramePixels>(doc: &Document, name: &str, size: u32) -> Option<Rendered<P>> {
|
||||
let def = doc.pattern(name)?;
|
||||
let (w, h) = (def.width(), def.height());
|
||||
let side = w.max(h);
|
||||
let region = Rect::from_center_size((w / 2.0, h / 2.0), (side, side));
|
||||
let px = size.clamp(1, 1024) as u16;
|
||||
let (pm, _) = with_tile_renderer(|r| rasterize(r, doc, def, region, (px, px), Ink::Display, (false, true)))?;
|
||||
Some(Rendered { width: px as u32, height: px as u32, pixels: crate::group::into_bytes(pm) })
|
||||
let (pixels, _) = with_tile_renderer(|r| rasterize_as(r, doc, def, (region, (px, px)), Ink::Display, (false, true), P::finish))?;
|
||||
Some(Rendered { width: px as u32, height: px as u32, pixels })
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
|
||||
@@ -189,9 +189,11 @@ impl Renderer {
|
||||
let hairline = std::mem::replace(&mut self.hairline, f64::from(k));
|
||||
let big: Rendered = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k, patch);
|
||||
self.hairline = hairline;
|
||||
let pixels = downsample(&big.pixels, big.width as usize, big.height as usize, k as usize);
|
||||
let mut pixels = P::blank(w as usize * h as usize);
|
||||
downsample(&big.pixels, big.width as usize, k as usize, pixels.bytes_mut());
|
||||
#[cfg(test)]
|
||||
group::FINISHED.with(|p| p.set(pixels.bytes_mut().as_ptr() as usize));
|
||||
drop(big);
|
||||
let pixels = P::from_bytes(pixels);
|
||||
self.stats.micros = now().saturating_sub(start);
|
||||
return Rendered { width: w, height: h, pixels };
|
||||
}
|
||||
@@ -455,6 +457,12 @@ impl Renderer {
|
||||
self.region(doc, region, scale, opts)
|
||||
}
|
||||
|
||||
/// [`Self::render_region_with`] with the pixels in words of four bytes, as
|
||||
/// [`Self::render_words`] returns them.
|
||||
pub fn render_region_with_words(&mut self, doc: &Document, region: Rect, scale: f64, opts: &RenderOptions) -> Rendered<Vec<u32>> {
|
||||
self.region(doc, region, scale, opts)
|
||||
}
|
||||
|
||||
fn region<P: FramePixels>(&mut self, doc: &Document, region: Rect, scale: f64, opts: &RenderOptions) -> Rendered<P> {
|
||||
let (w, h) = region_pixels(region, scale);
|
||||
let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0));
|
||||
@@ -485,6 +493,16 @@ impl Renderer {
|
||||
|
||||
/// [`Self::render_node`] with `opts` (e.g. [`RenderOptions::mark_undecoded_images`]).
|
||||
pub fn render_node_with(&mut self, doc: &Document, n: &Arc<Node>, w: u16, h: u16, view: Affine, opts: &RenderOptions) -> Option<Rendered> {
|
||||
self.node(doc, n, w, h, view, opts)
|
||||
}
|
||||
|
||||
/// [`Self::render_node`] with the pixels in words of four bytes, as [`Self::render_words`]
|
||||
/// returns them.
|
||||
pub fn render_node_words(&mut self, doc: &Document, n: &Arc<Node>, w: u16, h: u16, view: Affine) -> Option<Rendered<Vec<u32>>> {
|
||||
self.node(doc, n, w, h, view, &RenderOptions::default())
|
||||
}
|
||||
|
||||
fn node<P: FramePixels>(&mut self, doc: &Document, n: &Arc<Node>, w: u16, h: u16, view: Affine, opts: &RenderOptions) -> Option<Rendered<P>> {
|
||||
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
|
||||
self.check_plugins(doc);
|
||||
self.check_symbols(doc);
|
||||
@@ -499,7 +517,7 @@ impl Renderer {
|
||||
/// averaged down, and [`RenderOptions::precise`] picks the quality render mode, as in a page
|
||||
/// render ([`Self::render_as`], [`Self::draw_frame`]). `cell` is as in [`Self::render_as`].
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn node_pixels(
|
||||
fn node_pixels<P: FramePixels>(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
n: &Arc<Node>,
|
||||
@@ -509,7 +527,7 @@ impl Renderer {
|
||||
opts: &RenderOptions,
|
||||
forced: bool,
|
||||
cell: u32,
|
||||
) -> Vec<u8> {
|
||||
) -> P {
|
||||
if opts.supersample
|
||||
&& opts.anti_alias == AntiAlias::Art
|
||||
&& let Some(k) = supersample_factor(u32::from(w), u32::from(h))
|
||||
@@ -518,9 +536,13 @@ impl Renderer {
|
||||
// `supersample_factor` keeps each side within MAX_CONTEXT_SIDE, so it fits in a u16.
|
||||
let (bw, bh) = (u32::from(w) * k, u32::from(h) * k);
|
||||
let hairline = std::mem::replace(&mut self.hairline, f64::from(k));
|
||||
let big = self.node_pixels(doc, n, (bw as u16, bh as u16), Affine::scale(f64::from(k)) * view, visible, &hard, forced, k);
|
||||
let big: Vec<u8> = self.node_pixels(doc, n, (bw as u16, bh as u16), Affine::scale(f64::from(k)) * view, visible, &hard, forced, k);
|
||||
self.hairline = hairline;
|
||||
return downsample(&big, bw as usize, bh as usize, k as usize);
|
||||
let mut pixels = P::blank(usize::from(w) * usize::from(h));
|
||||
downsample(&big, bw as usize, k as usize, pixels.bytes_mut());
|
||||
#[cfg(test)]
|
||||
group::FINISHED.with(|p| p.set(pixels.bytes_mut().as_ptr() as usize));
|
||||
return pixels;
|
||||
}
|
||||
let px = 1.0 / view.determinant().abs().sqrt().max(1e-12);
|
||||
let mut ctx = single_threaded_context(w, h);
|
||||
@@ -538,10 +560,10 @@ impl Renderer {
|
||||
} else {
|
||||
self.draw_arc(&mut ctx, &frame, n);
|
||||
}
|
||||
let pm = self.finish(&mut ctx, self.raster);
|
||||
let pixels = P::finish(self, &mut ctx);
|
||||
self.end_frame();
|
||||
self.raster = raster;
|
||||
group::into_bytes(pm)
|
||||
pixels
|
||||
}
|
||||
|
||||
/// Render any node (also one outside the tree, e.g. opacity-mask art) fitted into
|
||||
@@ -565,6 +587,42 @@ impl Renderer {
|
||||
background: Option<[u8; 4]>,
|
||||
opts: &RenderOptions,
|
||||
) -> Option<Rendered> {
|
||||
self.node_thumbnail(doc, n, size, background, opts)
|
||||
}
|
||||
|
||||
/// [`Self::render_node_thumbnail`] with the pixels in words of four bytes, as
|
||||
/// [`Self::render_words`] returns them.
|
||||
pub fn render_node_thumbnail_words(&mut self, doc: &Document, n: &Node, size: u32, background: Option<[u8; 4]>) -> Option<Rendered<Vec<u32>>> {
|
||||
self.node_thumbnail(doc, n, size, background, &RenderOptions::default())
|
||||
}
|
||||
|
||||
/// [`Self::render_thumbnail`] with the pixels in words of four bytes, as
|
||||
/// [`Self::render_words`] returns them.
|
||||
pub fn render_thumbnail_words(&mut self, doc: &Document, id: NodeId, size: u32) -> Option<Rendered<Vec<u32>>> {
|
||||
self.node_thumbnail(doc, doc.node(id)?, size, None, &RenderOptions::default())
|
||||
}
|
||||
|
||||
/// [`Self::render_node_thumbnail_with`] with the pixels in words of four bytes, as
|
||||
/// [`Self::render_words`] returns them.
|
||||
pub fn render_node_thumbnail_words_with(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
n: &Node,
|
||||
size: u32,
|
||||
background: Option<[u8; 4]>,
|
||||
opts: &RenderOptions,
|
||||
) -> Option<Rendered<Vec<u32>>> {
|
||||
self.node_thumbnail(doc, n, size, background, opts)
|
||||
}
|
||||
|
||||
fn node_thumbnail<P: FramePixels>(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
n: &Node,
|
||||
size: u32,
|
||||
background: Option<[u8; 4]>,
|
||||
opts: &RenderOptions,
|
||||
) -> Option<Rendered<P>> {
|
||||
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
|
||||
self.check_plugins(doc);
|
||||
self.check_symbols(doc);
|
||||
@@ -573,9 +631,9 @@ impl Renderer {
|
||||
// A 1-pixel margin on each side, unless the thumbnail is too small to keep one.
|
||||
let s = (w as f64 - 2.0).max(1.0) / b.width().max(b.height()).max(1e-6);
|
||||
let view = Affine::translate((w as f64 / 2.0, w as f64 / 2.0)) * Affine::scale(s) * Affine::translate(-b.center().to_vec2());
|
||||
let mut pixels = self.node_pixels(doc, &Arc::new(n.clone()), (w, w), view, b.inflate(1.0, 1.0), opts, true, 1);
|
||||
let mut pixels: P = self.node_pixels(doc, &Arc::new(n.clone()), (w, w), view, b.inflate(1.0, 1.0), opts, true, 1);
|
||||
if let Some(bg) = background {
|
||||
over_background(&mut pixels, bg);
|
||||
over_background(pixels.bytes_mut(), bg);
|
||||
}
|
||||
Some(Rendered { width: w as u32, height: w as u32, pixels })
|
||||
}
|
||||
@@ -605,6 +663,8 @@ pub(crate) trait FramePixels: Sized {
|
||||
fn finish(r: &mut Renderer, ctx: &mut RenderContext) -> Self;
|
||||
/// The pixels in `bytes` (four a pixel).
|
||||
fn from_bytes(bytes: Vec<u8>) -> Self;
|
||||
/// `pixels` transparent pixels, to be written through [`Self::bytes_mut`].
|
||||
fn blank(pixels: usize) -> Self;
|
||||
/// The pixels as bytes, four a pixel.
|
||||
fn bytes_mut(&mut self) -> &mut [u8];
|
||||
}
|
||||
@@ -618,6 +678,10 @@ impl FramePixels for Vec<u8> {
|
||||
bytes
|
||||
}
|
||||
|
||||
fn blank(pixels: usize) -> Self {
|
||||
vec![0; pixels * 4]
|
||||
}
|
||||
|
||||
fn bytes_mut(&mut self) -> &mut [u8] {
|
||||
self
|
||||
}
|
||||
@@ -646,6 +710,10 @@ impl FramePixels for Vec<u32> {
|
||||
bytes.as_chunks::<4>().0.iter().map(|p| u32::from_ne_bytes(*p)).collect()
|
||||
}
|
||||
|
||||
fn blank(pixels: usize) -> Self {
|
||||
vec![0; pixels]
|
||||
}
|
||||
|
||||
fn bytes_mut(&mut self) -> &mut [u8] {
|
||||
bytemuck::cast_slice_mut(self)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
//! A frame rendered in words ([`Renderer::render_words`]): the bytes [`Renderer::render`] returns,
|
||||
//! rendered straight into the words.
|
||||
//! rendered straight into the words. Node renders, thumbnails, regions with options and pattern
|
||||
//! swatches render in words the same way.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
use vectorcraft_color::{BlendMode as Blend, Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, ColorMode, Node};
|
||||
use vectorcraft_doc::pattern::pattern_paint;
|
||||
use vectorcraft_doc::{Appearance, ColorMode, Node, PatternDef};
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
use crate::group::FINISHED;
|
||||
@@ -95,3 +97,91 @@ fn a_region_in_words_holds_the_bytes_of_the_region_in_bytes() {
|
||||
let words = Renderer::new().render_region_words(&plain, region, 1.3, false);
|
||||
assert_eq!(words.pixels.as_ptr() as usize, finished(), "a region's words are returned without a copy");
|
||||
}
|
||||
|
||||
/// The page of [`page`] with [`square`], [`blending_group`] and a square filled with the pattern
|
||||
/// "Checks" (a red square in a 20 pt tile) on it.
|
||||
fn patterned() -> Document {
|
||||
page(ColorMode::Rgb, |d| {
|
||||
let red = rect(d, Rect::new(0.0, 0.0, 10.0, 10.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
let mut def = PatternDef::new("Checks", vec![Arc::new(red)]);
|
||||
def.tile = Rect::new(0.0, 0.0, 20.0, 20.0);
|
||||
d.patterns.push(def);
|
||||
let filled = Appearance::basic(pattern_paint("Checks"), Paint::None, 0.0);
|
||||
let filled = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(30.0, 30.0, 90.0, 90.0)), filled);
|
||||
vec![square(d), blending_group(d), filled]
|
||||
})
|
||||
}
|
||||
|
||||
fn same_bytes(words: &Rendered<Vec<u32>>, bytes: &Rendered, what: &str) {
|
||||
assert_eq!((words.width, words.height), (bytes.width, bytes.height), "{what}: the size");
|
||||
assert!(bytemuck::cast_slice::<u32, u8>(&words.pixels) == bytes.pixels.as_slice(), "{what}: the same bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nodes_thumbnails_and_swatches_in_words_hold_the_bytes_of_the_same_renders_in_bytes() {
|
||||
let d = patterned();
|
||||
let nodes = d.layers[0].children().expect("a layer").to_vec();
|
||||
let view = Affine::scale(0.7) * Affine::translate((-4.0, -9.0));
|
||||
let supersampled = RenderOptions { supersample: true, precise: true, image_mips: true, ..Default::default() };
|
||||
for (i, n) in nodes.iter().enumerate() {
|
||||
let bytes = Renderer::new().render_node(&d, n, 53, 41, view).expect("a node render");
|
||||
let words = Renderer::new().render_node_words(&d, n, 53, 41, view).expect("a node render");
|
||||
same_bytes(&words, &bytes, &format!("node {i}"));
|
||||
for (what, background, opts) in [
|
||||
("transparent", None, RenderOptions::default()),
|
||||
("on white", Some([255; 4]), RenderOptions::default()),
|
||||
("on a translucent color", Some([10, 200, 90, 128]), RenderOptions::default()),
|
||||
("supersampled", None, supersampled.clone()),
|
||||
("supersampled on white", Some([255; 4]), supersampled.clone()),
|
||||
] {
|
||||
let bytes = Renderer::new().render_node_thumbnail_with(&d, n, 37, background, &opts).expect("a thumbnail");
|
||||
let words = Renderer::new().render_node_thumbnail_words_with(&d, n, 37, background, &opts).expect("a thumbnail");
|
||||
same_bytes(&words, &bytes, &format!("node {i}'s thumbnail, {what}"));
|
||||
}
|
||||
let bytes = Renderer::new().render_node_thumbnail(&d, n, 31, Some([255; 4])).expect("a thumbnail");
|
||||
let words = Renderer::new().render_node_thumbnail_words(&d, n, 31, Some([255; 4])).expect("a thumbnail");
|
||||
same_bytes(&words, &bytes, &format!("node {i}'s thumbnail on white, default options"));
|
||||
let bytes = Renderer::new().render_thumbnail(&d, n.id, 29).expect("a thumbnail");
|
||||
let words = Renderer::new().render_thumbnail_words(&d, n.id, 29).expect("a thumbnail");
|
||||
same_bytes(&words, &bytes, &format!("node {i}'s thumbnail by id"));
|
||||
}
|
||||
let region = Rect::new(5.0, 15.0, 70.0, 90.0);
|
||||
for (what, opts) in [("outline", RenderOptions { outline: true, ..Default::default() }), ("supersampled", supersampled)] {
|
||||
let bytes = Renderer::new().render_region_with(&d, region, 1.3, &opts);
|
||||
let words = Renderer::new().render_region_with_words(&d, region, 1.3, &opts);
|
||||
same_bytes(&words, &bytes, &format!("the region, {what}"));
|
||||
}
|
||||
let bytes = render_pattern_swatch(&d, "Checks", 23).expect("a swatch");
|
||||
let words = render_pattern_swatch_words(&d, "Checks", 23).expect("a swatch");
|
||||
same_bytes(&words, &bytes, "the pattern swatch");
|
||||
assert!(render_pattern_swatch_words(&d, "Missing", 23).is_none(), "a pattern the document lacks has no swatch");
|
||||
assert!(Renderer::new().render_thumbnail_words(&d, NodeId(u64::MAX), 29).is_none(), "a node the document lacks has no thumbnail");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nodes_thumbnails_and_swatches_in_words_are_returned_in_the_buffer_they_rendered_into() {
|
||||
let d = patterned();
|
||||
let n = d.layers[0].children().expect("a layer")[1].clone();
|
||||
let mut r = Renderer::new();
|
||||
let out = r.render_node_words(&d, &n, 40, 40, Affine::IDENTITY).expect("a node render");
|
||||
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a node's words are returned without a copy");
|
||||
let supersampled = RenderOptions { supersample: true, ..Default::default() };
|
||||
for background in [None, Some([255; 4])] {
|
||||
for (what, opts) in [("", RenderOptions::default()), (" supersampled", supersampled.clone())] {
|
||||
let out = r.render_node_thumbnail_words_with(&d, &n, 48, background, &opts).expect("a thumbnail");
|
||||
let at = out.pixels.as_ptr() as usize;
|
||||
assert_eq!(at, finished(), "background {background:?}{what}: a thumbnail's words are returned without a copy");
|
||||
}
|
||||
}
|
||||
let out = r.render_node_thumbnail_words(&d, &n, 48, Some([255; 4])).expect("a thumbnail");
|
||||
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a thumbnail on a color's words are returned without a copy");
|
||||
let out = r.render_words(&d, 64, 48, Affine::IDENTITY, &supersampled);
|
||||
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a supersampled frame's words are returned without a copy");
|
||||
let out = r.render_thumbnail_words(&d, n.id, 32).expect("a thumbnail");
|
||||
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a thumbnail's words by id are returned without a copy");
|
||||
let plain = page(ColorMode::Rgb, |d| vec![square(d)]);
|
||||
let out = r.render_region_with_words(&plain, Rect::new(5.0, 15.0, 70.0, 90.0), 1.3, &RenderOptions::default());
|
||||
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a region's words with options are returned without a copy");
|
||||
let out = render_pattern_swatch_words(&d, "Checks", 20).expect("a swatch");
|
||||
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a swatch's words are returned without a copy");
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ vectorcraft-cad = { workspace = true }
|
||||
vectorcraft-eps = { workspace = true }
|
||||
vectorcraft-format = { workspace = true }
|
||||
egui = { workspace = true, features = ["bytemuck", "default_fonts", "monochrome_emoji_fonts"] }
|
||||
# With egui's `bytemuck`: copies rendered rasters into egui images whole (`canvas::color_image`).
|
||||
# With egui's `bytemuck`: hands rendered rasters to egui images in their own buffers (`canvas::color_image_owned`).
|
||||
# `default_fonts`: egui 0.37 makes its bundled faces opt-in, and a dependency's dev-features do not
|
||||
# reach our tests; `theme::install_fonts` starts from `FontDefinitions::default()`, which is empty
|
||||
# without them (production would lay out tofu, and the no-interface-fonts tests would bind nothing).
|
||||
|
||||
@@ -51,7 +51,9 @@ pub use fill::Fill;
|
||||
use home::home;
|
||||
pub use panes::{Layout as TileLayout, Panes};
|
||||
pub(crate) use panes::{consolidate, pane, tile, tiled_area};
|
||||
pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job};
|
||||
pub(crate) use raster::{KeptFrame, color_image_owned, render_job};
|
||||
#[cfg(test)]
|
||||
pub(crate) use raster::{assert_handed_over, clear_handed_over};
|
||||
pub(crate) use rulers::{general_lengths, stroke_lengths};
|
||||
pub use selection::HoverObjectKey;
|
||||
pub(crate) use task_bar::{TASK_BAR_ACTIONS, TASK_BAR_CHIPS, has_colors, is_task_bar_action, read_hidden_task_bar_actions};
|
||||
|
||||
@@ -18,25 +18,13 @@ use super::{BodyKind, in_gesture};
|
||||
use crate::doc_windows::Win;
|
||||
use crate::{CacheKey, VectorcraftApp};
|
||||
|
||||
/// The rendered raster `img` as an egui image. Both are premultiplied RGBA8, so its bytes are copied
|
||||
/// over whole instead of pixel by pixel, which costs milliseconds for a canvas on a large screen.
|
||||
/// A raster whose bytes don't match its size gives an empty image of that size.
|
||||
pub(crate) fn color_image(img: &vectorcraft_render::Rendered) -> egui::ColorImage {
|
||||
let size = [img.width as usize, img.height as usize];
|
||||
let expected = size[0].saturating_mul(size[1]).saturating_mul(4);
|
||||
if expected == img.pixels.len() {
|
||||
let pixels: Vec<egui::Color32> = bytemuck::cast_slice(&img.pixels).to_vec();
|
||||
egui::ColorImage::new(size, pixels)
|
||||
} else {
|
||||
egui::ColorImage::new(size, vec![egui::Color32::TRANSPARENT; size[0].saturating_mul(size[1])])
|
||||
}
|
||||
}
|
||||
|
||||
/// The raster `img` rendered in words ([`vectorcraft_render::Renderer::render_words`]) as an egui
|
||||
/// image, in the buffer `img` holds: a word and a [`egui::Color32`] are both four bytes aligned to
|
||||
/// four, so the pixels are not copied. A raster whose pixels don't match its size gives an empty
|
||||
/// image of that size.
|
||||
pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered<Vec<u32>>) -> egui::ColorImage {
|
||||
#[cfg(test)]
|
||||
HANDED_OVER.with(|p| p.set(img.pixels.as_ptr() as usize));
|
||||
let size = [img.width as usize, img.height as usize];
|
||||
if size[0].saturating_mul(size[1]) == img.pixels.len() {
|
||||
let pixels: Vec<egui::Color32> = bytemuck::allocation::try_cast_vec(img.pixels).unwrap_or_else(|(_, v)| bytemuck::cast_slice(&v).to_vec());
|
||||
@@ -764,6 +752,24 @@ thread_local! {
|
||||
/// frame the test finished before it lands in the wait. A test that answers the job from
|
||||
/// another thread sets [`std::time::Duration::MAX`] to wait for that answer.
|
||||
pub(crate) static TEST_FIRST_FRAME_GRACE: std::cell::Cell<std::time::Duration> = const { std::cell::Cell::new(std::time::Duration::ZERO) };
|
||||
/// The address of the words the last [`color_image_owned`] on this thread was given.
|
||||
static HANDED_OVER: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Clears what [`assert_handed_over`] checks, before the image it checks is made.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn clear_handed_over() {
|
||||
HANDED_OVER.with(|p| p.set(0));
|
||||
}
|
||||
|
||||
/// Asserts that `image` was made by [`color_image_owned`] on this thread since
|
||||
/// [`clear_handed_over`], in the words it was given: the pixels were handed over, not copied.
|
||||
#[cfg(test)]
|
||||
#[track_caller]
|
||||
pub(crate) fn assert_handed_over(image: &egui::ColorImage, what: &str) {
|
||||
let given = HANDED_OVER.with(std::cell::Cell::get);
|
||||
assert!(given != 0, "{what}: the image is made from words handed over");
|
||||
assert_eq!(image.pixels.as_ptr() as usize, given, "{what}: the image holds the words it was given, not a copy");
|
||||
}
|
||||
|
||||
/// [`render_ms`] in unit tests: the time [`TEST_RENDER_MS`] holds.
|
||||
|
||||
@@ -7400,7 +7400,7 @@ fn the_worker_s_frame_reaches_its_texture_image_in_the_buffer_it_was_rendered_in
|
||||
let color = color_image_owned(frame);
|
||||
assert_eq!(color.pixels.as_ptr() as usize, at, "the frame's pixels are handed to the image, not copied");
|
||||
let bytes = vectorcraft_render::Renderer::new().render(&doc, job.w, job.h, job.view, &job.opts);
|
||||
assert!(color.pixels == color_image(&bytes).pixels, "the image holds the frame's pixels");
|
||||
assert!(bytemuck::cast_slice::<Color32, u8>(&color.pixels) == bytes.pixels.as_slice(), "the image holds the frame's pixels");
|
||||
assert_eq!(color.size, [256, 128]);
|
||||
// A raster whose pixels don't match its size gives an empty image of that size.
|
||||
let short = vectorcraft_render::Rendered { width: 3, height: 2, pixels: vec![u32::MAX; 5] };
|
||||
|
||||
@@ -349,22 +349,21 @@ fn image(f: &CompositeFont, zoom: u64, marks: &[Mark], ppp: f32, ink: Color32) -
|
||||
mark_line(&mut rendered, ((base - y) as f32 * ppp).round(), ppp.ceil().max(1.0) as usize, m.color());
|
||||
}
|
||||
}
|
||||
crate::canvas::color_image(&rendered)
|
||||
crate::canvas::color_image_owned(rendered)
|
||||
}
|
||||
|
||||
/// Draws a horizontal line `thickness` pixels thick from row `y` across `image`; a row outside it draws nothing.
|
||||
fn mark_line(image: &mut vectorcraft_render::Rendered, y: f32, thickness: usize, color: Color32) {
|
||||
fn mark_line(image: &mut vectorcraft_render::Rendered<Vec<u32>>, y: f32, thickness: usize, color: Color32) {
|
||||
if !y.is_finite() || y < 0.0 {
|
||||
return;
|
||||
}
|
||||
let (width, height) = (image.width as usize, image.height as usize);
|
||||
let first = y as usize;
|
||||
let word = u32::from_ne_bytes(color.to_array());
|
||||
for row in first..first.saturating_add(thickness).min(height) {
|
||||
let start = row.saturating_mul(width).saturating_mul(4);
|
||||
if let Some(line) = image.pixels.get_mut(start..start.saturating_add(width.saturating_mul(4))) {
|
||||
for pixel in line.as_chunks_mut::<4>().0 {
|
||||
pixel.copy_from_slice(&color.to_array());
|
||||
}
|
||||
let start = row.saturating_mul(width);
|
||||
if let Some(line) = image.pixels.get_mut(start..start.saturating_add(width)) {
|
||||
line.fill(word);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -372,7 +371,7 @@ fn mark_line(image: &mut vectorcraft_render::Rendered, y: f32, thickness: usize,
|
||||
/// The sample of `f` set at `size` points in `ink`, its baseline `baseline` points down from the
|
||||
/// top, drawn by the renderer as the canvas draws type (color and bitmap glyphs in their own
|
||||
/// colors) into `px` pixels at `ppp` pixels per point.
|
||||
pub(super) fn draw(f: &CompositeFont, size: f64, baseline: f64, px: (u16, u16), ppp: f32, ink: Color32) -> vectorcraft_render::Rendered {
|
||||
pub(super) fn draw(f: &CompositeFont, size: f64, baseline: f64, px: (u16, u16), ppp: f32, ink: Color32) -> vectorcraft_render::Rendered<Vec<u32>> {
|
||||
let (w, h) = px;
|
||||
let mut doc = vectorcraft_doc::Document::new(f64::from(w) / f64::from(ppp), f64::from(h) / f64::from(ppp));
|
||||
let font = sample_font(f);
|
||||
@@ -384,8 +383,8 @@ pub(super) fn draw(f: &CompositeFont, size: f64, baseline: f64, px: (u16, u16),
|
||||
let t = TextObject::point(Point::new(INSET, baseline), &sample, style);
|
||||
let node = std::sync::Arc::new(vectorcraft_doc::Node::new(doc.alloc_id(), vectorcraft_doc::NodeKind::Text(Box::new(t))));
|
||||
let view = Affine::scale(f64::from(ppp));
|
||||
let empty = || vectorcraft_render::Rendered { width: u32::from(w), height: u32::from(h), pixels: vec![0; usize::from(w) * usize::from(h) * 4] };
|
||||
RENDERER.with(|r| r.borrow_mut().render_node(&doc, &node, w, h, view)).unwrap_or_else(empty)
|
||||
let empty = || vectorcraft_render::Rendered { width: u32::from(w), height: u32::from(h), pixels: vec![0; usize::from(w) * usize::from(h)] };
|
||||
RENDERER.with(|r| r.borrow_mut().render_node_words(&doc, &node, w, h, view)).unwrap_or_else(empty)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -477,4 +476,16 @@ mod zoom_tests {
|
||||
assert_eq!(fields(&panel)["zoom"], json!(400), "canceling an older popup must not undo the later automation edit");
|
||||
assert_eq!(panel.value_role("Zoom", Role::COMBO_BOX).as_deref(), Some("400%"));
|
||||
}
|
||||
|
||||
/// The sample's image holds the pixels the sample was rendered into, with its lines drawn in.
|
||||
#[test]
|
||||
fn the_sample_image_is_handed_over_with_its_lines_drawn_in() {
|
||||
let f = CompositeFont::new("Sample draft", "Source Sans 3", "Regular");
|
||||
crate::canvas::clear_handed_over();
|
||||
let image = image(&f, 100, &[Mark::Baseline], 1.0, Color32::BLACK);
|
||||
crate::canvas::assert_handed_over(&image, "the sample");
|
||||
let [w, _] = image.size;
|
||||
let line = image.pixels.chunks(w).any(|row| row.iter().all(|p| *p == Mark::Baseline.color()));
|
||||
assert!(line, "the baseline is drawn across the sample");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -585,6 +585,7 @@ fn the_sample_draws_color_glyphs_in_their_colors() {
|
||||
colr.size = 300.0;
|
||||
f.custom = vec![CustomCharSet { name: "Color".into(), characters: COLOUR_CHAR.to_string(), part: colr }];
|
||||
let img = sample::draw(&f, 36.0, 120.0, (900, 160), 1.0, egui::Color32::BLACK);
|
||||
let img = vectorcraft_render::Rendered { width: img.width, height: img.height, pixels: bytemuck::cast_slice::<u32, u8>(&img.pixels).to_vec() };
|
||||
let red = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).any(|(x, y)| {
|
||||
let p = img.pixel(x, y);
|
||||
p[0] > 200 && p[1] < 60 && p[2] < 60 && p[3] > 200
|
||||
|
||||
@@ -672,8 +672,8 @@ fn thumbnail(doc: &Document, art: &Node) -> egui::ColorImage {
|
||||
static RENDERER: RefCell<vectorcraft_render::Renderer> = RefCell::new(vectorcraft_render::Renderer::new());
|
||||
}
|
||||
RENDERER
|
||||
.with(|r| r.borrow_mut().render_node_thumbnail(doc, art, PREVIEW_PX, Some([255, 255, 255, 255])))
|
||||
.map_or_else(blank, |img| crate::canvas::color_image(&img))
|
||||
.with(|r| r.borrow_mut().render_node_thumbnail_words(doc, art, PREVIEW_PX, Some([255, 255, 255, 255])))
|
||||
.map_or_else(blank, crate::canvas::color_image_owned)
|
||||
}
|
||||
|
||||
/// The designs among `selection`'s rows.
|
||||
@@ -909,6 +909,18 @@ mod tests {
|
||||
app.run("select.set", json!({"ids": [g]})).unwrap();
|
||||
}
|
||||
|
||||
/// A design's preview holds the pixels it was rendered into.
|
||||
#[test]
|
||||
fn a_designs_preview_is_handed_to_its_image_without_a_copy() {
|
||||
let (app, _ctx) = app_with_design();
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
let design = doc.graph_designs.first().expect("the new design");
|
||||
crate::canvas::clear_handed_over();
|
||||
let image = super::thumbnail(doc, &design.art);
|
||||
assert_eq!(image.size, [super::PREVIEW_PX as usize; 2], "the preview's size");
|
||||
crate::canvas::assert_handed_over(&image, "the design's preview");
|
||||
}
|
||||
|
||||
/// The open dialog's fields, as automation lists them.
|
||||
fn fields(app: &VectorcraftApp) -> Value {
|
||||
app.dialogs().unwrap().with(|host| host.open_dialogs()).last().unwrap().fields.clone().unwrap()
|
||||
|
||||
@@ -143,17 +143,7 @@ pub(crate) fn paint_thumb(painter: &egui::Painter, revision: Revision, doc: &Doc
|
||||
let key = (nodes, px);
|
||||
let tex = CACHE.with(|c| c.borrow().get(&key).cloned()).or_else(|| {
|
||||
let art: Vec<&Node> = ids().iter().filter_map(|id| doc.node(*id)).collect();
|
||||
// Same Art Optimized supersample as assets.export (#983): abutting fills leave no seam in
|
||||
// the tile (Layers row thumbs stay cheap without it).
|
||||
let opts = vectorcraft_render::RenderOptions { image_mips: true, precise: true, supersample: true, ..Default::default() };
|
||||
let img = RENDERER.with(|rr| match art.as_slice() {
|
||||
[one] => rr.borrow_mut().render_node_thumbnail_with(doc, one, px, None, &opts),
|
||||
many => {
|
||||
let group = Node::group(NodeId(0), many.iter().map(|n| Arc::new((*n).clone())).collect());
|
||||
rr.borrow_mut().render_node_thumbnail_with(doc, &group, px, None, &opts)
|
||||
}
|
||||
})?;
|
||||
let color = crate::canvas::color_image(&img);
|
||||
let color = RENDERER.with(|rr| thumb_image(&mut rr.borrow_mut(), doc, &art, px))?;
|
||||
let tex = painter.ctx().load_texture(format!("asset-thumb-{}", a.id), color, egui::TextureOptions::LINEAR);
|
||||
CACHE.with(|c| {
|
||||
let mut c = c.borrow_mut();
|
||||
@@ -169,6 +159,22 @@ pub(crate) fn paint_thumb(painter: &egui::Painter, revision: Revision, doc: &Doc
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects `art` of `doc` (back to front) fitted into `px` pixels square, transparent: the
|
||||
/// image of an asset's tile. `None` when they have no bounds.
|
||||
pub(super) fn thumb_image(r: &mut vectorcraft_render::Renderer, doc: &Document, art: &[&Node], px: u32) -> Option<egui::ColorImage> {
|
||||
// Same Art Optimized supersample as assets.export (#983): abutting fills leave no seam in
|
||||
// the tile (Layers row thumbs stay cheap without it).
|
||||
let opts = vectorcraft_render::RenderOptions { image_mips: true, precise: true, supersample: true, ..Default::default() };
|
||||
let img = match art {
|
||||
[one] => r.render_node_thumbnail_words_with(doc, one, px, None, &opts),
|
||||
many => {
|
||||
let group = Node::group(NodeId(0), many.iter().map(|n| Arc::new((*n).clone())).collect());
|
||||
r.render_node_thumbnail_words_with(doc, &group, px, None, &opts)
|
||||
}
|
||||
}?;
|
||||
Some(crate::canvas::color_image_owned(img))
|
||||
}
|
||||
|
||||
/// The document's assets as the tile grid's items.
|
||||
struct Assets {
|
||||
ids: Vec<u64>,
|
||||
|
||||
@@ -384,8 +384,8 @@ fn render_object(app: &VectorcraftApp, doc: &Document, n: &Node, g: &GraphicStyl
|
||||
} else {
|
||||
styled_node(n, g, app.session.prefs.override_char_color)
|
||||
};
|
||||
let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail(doc, &styled, px, Some([255; 4])))?;
|
||||
let mut img = crate::canvas::color_image(&img);
|
||||
let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail_words(doc, &styled, px, Some([255; 4])))?;
|
||||
let mut img = crate::canvas::color_image_owned(img);
|
||||
if empty {
|
||||
slash(&mut img);
|
||||
}
|
||||
@@ -1321,13 +1321,17 @@ mod tests {
|
||||
// The large preview on the selected rectangle.
|
||||
let st = app.session.active().unwrap();
|
||||
let n = st.doc.node(st.selection.objects[0]).unwrap();
|
||||
crate::canvas::clear_handed_over();
|
||||
let img = render_object(&app, &st.doc, n, &empty, 60).unwrap();
|
||||
crate::canvas::assert_handed_over(&img, "the large preview with the slash");
|
||||
assert!(red(px(&img, 30, 30)));
|
||||
assert!(dark(px(&img, 1, 30)), "{:?}", px(&img, 1, 30));
|
||||
assert_eq!(px(&img, 10, 10), Color32::WHITE);
|
||||
// A style that paints keeps its own look there, without the slash.
|
||||
let blue = GraphicStyle::new("Blue", Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 1.0));
|
||||
crate::canvas::clear_handed_over();
|
||||
let img = render_object(&app, &st.doc, n, &blue, 60).unwrap();
|
||||
crate::canvas::assert_handed_over(&img, "the large preview");
|
||||
assert_eq!(px(&img, 30, 30), Color32::from_rgb(0, 0, 255));
|
||||
}
|
||||
|
||||
|
||||
@@ -128,7 +128,7 @@ pub(crate) fn render(node: Arc<Node>, doc: Arc<Document>, request: &ThumbRequest
|
||||
static RENDERER: std::cell::RefCell<vectorcraft_render::Renderer> = std::cell::RefCell::new(vectorcraft_render::Renderer::new());
|
||||
}
|
||||
return match RENDERER.with(|r| render_thumb(&mut r.borrow_mut(), &doc, &node, side)) {
|
||||
Some(img) => ThumbRender::Ready(crate::canvas::color_image(&img)),
|
||||
Some(img) => ThumbRender::Ready(crate::canvas::color_image_owned(img)),
|
||||
None => ThumbRender::Blank,
|
||||
};
|
||||
}
|
||||
@@ -141,7 +141,7 @@ pub(crate) fn render(node: Arc<Node>, doc: Arc<Document>, request: &ThumbRequest
|
||||
if cancel.is_cancelled() {
|
||||
return Err(cancelled());
|
||||
}
|
||||
Ok(img.map_or(LoadedPicture::Blank, |img| LoadedPicture::Image(crate::canvas::color_image(&img))))
|
||||
Ok(img.map_or(LoadedPicture::Blank, |img| LoadedPicture::Image(crate::canvas::color_image_owned(img))))
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -309,8 +309,8 @@ fn light_row(n: &Node, quick: Option<bool>, doc: &Document) -> bool {
|
||||
}
|
||||
|
||||
/// The thumbnail of `n` (`px` pixels square) as `r` renders it, on the UI thread or a lane.
|
||||
fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, n: &Node, px: u32) -> Option<vectorcraft_render::Rendered> {
|
||||
r.render_node_thumbnail_with(doc, n, px, None, &thumb_options())
|
||||
fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, n: &Node, px: u32) -> Option<vectorcraft_render::Rendered<Vec<u32>>> {
|
||||
r.render_node_thumbnail_words_with(doc, n, px, None, &thumb_options())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -598,7 +598,7 @@ mod tests {
|
||||
let ThumbRender::Later(job) = rendered(doc, n, &request) else { panic!("a heavy node is made on a lane") };
|
||||
let Ok(LoadedPicture::Image(there)) = job(&Cancel::new()) else { panic!("the job draws the node") };
|
||||
let here = render_thumb(&mut vectorcraft_render::Renderer::new(), doc, n, request.side).expect("this thread draws the node");
|
||||
let here = crate::canvas::color_image(&here);
|
||||
let here = crate::canvas::color_image_owned(here);
|
||||
assert!(here.pixels.iter().any(|p| p.a() > 0), "the thumbnail shows the art");
|
||||
assert_eq!((there.size, &there.pixels), (here.size, &here.pixels), "the same pixels");
|
||||
}
|
||||
@@ -642,4 +642,18 @@ mod tests {
|
||||
assert!(matches!(before.render(&key, &request), ThumbRender::Ready(_)));
|
||||
assert!(matches!(after.render(&key, &request), ThumbRender::Later(_)), "and a long path is made on a lane");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rows_thumbnail_is_handed_to_its_image_without_a_copy() {
|
||||
let request = ThumbRequest::for_cell(24.0, 1.0);
|
||||
let (doc, n) = doc_with(|id| rect(id.0));
|
||||
crate::canvas::clear_handed_over();
|
||||
let ThumbRender::Ready(here) = rendered(&doc, &n, &request) else { panic!("a small object's thumbnail is made at once") };
|
||||
crate::canvas::assert_handed_over(&here, "a thumbnail made here");
|
||||
let (doc, n) = doc_with(|id| path(id.0, 50_000));
|
||||
let ThumbRender::Later(job) = rendered(&doc, &n, &request) else { panic!("a long path is made on a lane") };
|
||||
crate::canvas::clear_handed_over();
|
||||
let Ok(LoadedPicture::Image(there)) = job(&Cancel::new()) else { panic!("the job draws the node") };
|
||||
crate::canvas::assert_handed_over(&there, "a thumbnail made on a lane");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,8 +173,8 @@ impl ThumbSource<NavKey> for NavThumbs {
|
||||
ThumbRender::Later(Box::new(move |_cancel| {
|
||||
let options = image_options(key);
|
||||
let renderer = if key.solid_dashes { &SOLID_RENDERER } else { &NAV_RENDERER };
|
||||
let image = renderer.with(|r| r.borrow_mut().render_region_with(&doc, region, scale, &options));
|
||||
Ok(LoadedPicture::Image(crate::canvas::color_image(&image)))
|
||||
let image = renderer.with(|r| r.borrow_mut().render_region_with_words(&doc, region, scale, &options));
|
||||
Ok(LoadedPicture::Image(crate::canvas::color_image_owned(image)))
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -293,6 +293,20 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The navigator's picture, with and without solid dashes, holds the pixels it was rendered into.
|
||||
#[test]
|
||||
fn the_navigator_picture_is_handed_to_its_image_without_a_copy() {
|
||||
let doc = Arc::new(vectorcraft_doc::Document::new(200.0, 100.0));
|
||||
let source = NavThumbs::new(&doc, 1, DRect::new(-10.0, -10.0, 210.0, 110.0));
|
||||
for solid_dashes in [false, true] {
|
||||
let key = NavKey { uid: 1, artboard_only: false, solid_dashes };
|
||||
let ThumbRender::Later(job) = source.render(&key, &ThumbRequest::for_cell(60.0, 1.0)) else { panic!("the picture is made on a lane") };
|
||||
crate::canvas::clear_handed_over();
|
||||
let Ok(LoadedPicture::Image(image)) = job(&craft::host::queue::Cancel::new()) else { panic!("the job draws the document") };
|
||||
crate::canvas::assert_handed_over(&image, if solid_dashes { "with solid dashes" } else { "with dashes" });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn navigator_reports_a_malformed_zoom_entry() {
|
||||
assert_malformed_zoom_entry_reported(show);
|
||||
|
||||
@@ -682,10 +682,8 @@ fn pattern_thumb_in(doc: &Document, cx: &ContentPainterCx<'_>, r: Rect, paint: &
|
||||
px,
|
||||
);
|
||||
let tex = CACHE.with(|c| c.borrow().get(&key).cloned()).unwrap_or_else(|| {
|
||||
let tex = vectorcraft_render::render_pattern_swatch(doc, pattern, px).map(|img| {
|
||||
let color = crate::canvas::color_image(&img);
|
||||
ctx.load_texture(format!("pattern-swatch-{pattern}-{px}"), color, egui::TextureOptions::LINEAR)
|
||||
});
|
||||
let tex = pattern_image(doc, pattern, px)
|
||||
.map(|color| ctx.load_texture(format!("pattern-swatch-{pattern}-{px}"), color, egui::TextureOptions::LINEAR));
|
||||
CACHE.with(|c| {
|
||||
let mut c = c.borrow_mut();
|
||||
if c.len() > 256 {
|
||||
@@ -701,6 +699,11 @@ fn pattern_thumb_in(doc: &Document, cx: &ContentPainterCx<'_>, r: Rect, paint: &
|
||||
true
|
||||
}
|
||||
|
||||
/// The swatch image of pattern `name` in `doc`, `px` pixels square; `None` when `doc` has no such pattern.
|
||||
fn pattern_image(doc: &Document, name: &str, px: u32) -> Option<egui::ColorImage> {
|
||||
vectorcraft_render::render_pattern_swatch_words(doc, name, px).map(crate::canvas::color_image_owned)
|
||||
}
|
||||
|
||||
/// The red of None's slash on a swatch tile and of a disabled opacity mask's cross, drawn on the document's white or
|
||||
/// black paper. It is the same in every theme.
|
||||
pub(super) const OFF_MARK: Color32 = Color32::from_rgb(0xe0, 0x20, 0x20);
|
||||
|
||||
@@ -1716,3 +1716,18 @@ fn idle_frames_replay_the_swatch_rows() {
|
||||
assert!(panel.shows(red), "and they show the swatch again");
|
||||
idle(&mut panel, "after an undo");
|
||||
}
|
||||
|
||||
/// A pattern swatch's image holds the pixels the swatch was rendered into; a pattern the document
|
||||
/// lacks has no image.
|
||||
#[test]
|
||||
fn a_pattern_swatch_image_is_handed_over_without_a_copy() {
|
||||
let mut app = app();
|
||||
let square = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("object.pattern.make", json!({"ids": [square], "name": "Dots", "edit": false})).unwrap();
|
||||
let doc = doc(&app);
|
||||
crate::canvas::clear_handed_over();
|
||||
let image = pattern_image(&doc, "Dots", 24).expect("the pattern draws");
|
||||
assert_eq!(image.size, [24, 24], "the swatch's size");
|
||||
crate::canvas::assert_handed_over(&image, "the pattern swatch");
|
||||
assert!(pattern_image(&doc, "Missing", 24).is_none(), "no image for a pattern the document lacks");
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ impl ThumbSource<SymbolThumb> for SymbolPictures<'_> {
|
||||
render_art(&mut renderer, self.doc, self.name, vectorcraft_geom::Rect::new(x0, y0, x1, y1), (*w, *h))
|
||||
}
|
||||
};
|
||||
img.map_or(ThumbRender::Blank, |img| ThumbRender::Ready(crate::canvas::color_image(&img)))
|
||||
img.map_or(ThumbRender::Blank, |img| ThumbRender::Ready(crate::canvas::color_image_owned(img)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,7 +198,7 @@ pub(crate) mod counters {
|
||||
/// Symbol `name` of `doc` rendered `px` pixels wide: an instance at its natural size, alone on a
|
||||
/// copy of `doc` that keeps its resources (the symbols it nests, patterns, images, swatches,
|
||||
/// brushes, graphic styles) but none of its art.
|
||||
fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, name: &str, px: u32) -> Option<vectorcraft_render::Rendered> {
|
||||
fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, name: &str, px: u32) -> Option<vectorcraft_render::Rendered<Vec<u32>>> {
|
||||
let (w, h) = symbol_size(doc, name);
|
||||
let mut d = doc.clone();
|
||||
let layer = d.alloc_id();
|
||||
@@ -206,7 +206,7 @@ fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, name: &str
|
||||
let id = d.alloc_id();
|
||||
let xf = vectorcraft_geom::Affine::scale_non_uniform(w / 20.0, h / 20.0);
|
||||
d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf })).ok()?;
|
||||
r.render_thumbnail(&d, id, px)
|
||||
r.render_thumbnail_words(&d, id, px)
|
||||
}
|
||||
|
||||
/// Symbol `name` of `doc` (an instance at its natural size, as [`render_thumb`] places it) drawn
|
||||
@@ -218,7 +218,7 @@ fn render_art(
|
||||
name: &str,
|
||||
art: vectorcraft_geom::Rect,
|
||||
(w, h): (u32, u32),
|
||||
) -> Option<vectorcraft_render::Rendered> {
|
||||
) -> Option<vectorcraft_render::Rendered<Vec<u32>>> {
|
||||
let (aw, ah) = (art.width(), art.height());
|
||||
if !(aw.is_finite() && ah.is_finite() && aw > 0.0 && ah > 0.0) {
|
||||
return None;
|
||||
@@ -232,7 +232,7 @@ fn render_art(
|
||||
let n = Arc::new(Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf }));
|
||||
let view =
|
||||
vectorcraft_geom::Affine::scale_non_uniform(f64::from(w) / aw, f64::from(h) / ah) * vectorcraft_geom::Affine::translate((-art.x0, -art.y0));
|
||||
r.render_node(&d, &n, u16::try_from(w).ok()?, u16::try_from(h).ok()?, view)
|
||||
r.render_node_words(&d, &n, u16::try_from(w).ok()?, u16::try_from(h).ok()?, view)
|
||||
}
|
||||
|
||||
/// The active document's current symbol (`symbol.list`'s `current`), read without running a
|
||||
|
||||
@@ -13,8 +13,9 @@ fn symbols(app: &mut VectorcraftApp) -> Vec<String> {
|
||||
}
|
||||
|
||||
/// Pixels of `img` that something paints opaquely, and those of them that are red.
|
||||
fn painted(img: &vectorcraft_render::Rendered) -> (usize, usize) {
|
||||
let painted: Vec<&[u8; 4]> = img.pixels.as_chunks::<4>().0.iter().filter(|p| p[3] > 200).collect();
|
||||
fn painted(img: &vectorcraft_render::Rendered<Vec<u32>>) -> (usize, usize) {
|
||||
let bytes: &[u8] = bytemuck::cast_slice(&img.pixels);
|
||||
let painted: Vec<&[u8; 4]> = bytes.as_chunks::<4>().0.iter().filter(|p| p[3] > 200).collect();
|
||||
let red = painted.iter().filter(|p| p[0] > 150 && p[1] < 80 && p[2] < 80).count();
|
||||
(painted.len(), red)
|
||||
}
|
||||
@@ -1320,6 +1321,26 @@ fn an_imported_symbols_thumbnail_frames_its_whole_art() {
|
||||
assert!(orange(inset_x, inset_y) && orange(w - 1 - inset_x, h - 1 - inset_y), "{w} × {h}");
|
||||
}
|
||||
|
||||
/// Both pictures of a symbol become images in the pixels they were rendered into.
|
||||
#[test]
|
||||
fn a_symbols_pictures_are_handed_to_their_images_without_a_copy() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Wide"})).unwrap();
|
||||
let doc = &*s.doc().unwrap().doc;
|
||||
let art = vectorcraft_effects::graphic_bounds(doc, "Wide").expect("the art's bounds");
|
||||
let pictures = SymbolPictures { doc, name: "Wide" };
|
||||
for (what, key) in [
|
||||
("the symbol", SymbolThumb::Symbol { key: 1 }),
|
||||
("its art", SymbolThumb::Art { key: 1, w: 40, h: 30, art: [art.x0, art.y0, art.x1, art.y1].map(f64::to_bits) }),
|
||||
] {
|
||||
crate::canvas::clear_handed_over();
|
||||
let ThumbRender::Ready(image) = pictures.render(&key, &ThumbRequest::for_cell(40.0, 1.0)) else { panic!("{what} renders at once") };
|
||||
crate::canvas::assert_handed_over(&image, what);
|
||||
}
|
||||
}
|
||||
|
||||
/// A document with symbol "Leaf", whose instance stands where its rectangle was, and symbol
|
||||
/// "Dot", which no instance uses; "Dot" is current.
|
||||
fn leaf_and_dot() -> VectorcraftApp {
|
||||
|
||||
@@ -11,7 +11,7 @@ use craft::ui::runtime::commands::CommandStates;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use super::asset_export::{menu_rows, menu_states};
|
||||
use super::asset_export::{menu_rows, menu_states, thumb_image};
|
||||
use crate::dialogs::ExportForScreensDialog;
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use crate::{Services, VectorcraftApp};
|
||||
@@ -1158,3 +1158,19 @@ fn tile_menu_collects_canvas_art_as_one_or_multiple_assets_and_disables_empty_se
|
||||
assert_eq!(picked(&p).len(), if single { 1 } else { 2 });
|
||||
}
|
||||
}
|
||||
|
||||
/// A tile's image is made in the words its objects were rendered into, for one object and for several.
|
||||
#[test]
|
||||
fn an_assets_tile_image_holds_the_rendered_words_without_a_copy() {
|
||||
let (app, _, [a, b]) = app(false);
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
let node = |id: u64| doc.node(vectorcraft_doc::NodeId(id)).expect("the square");
|
||||
let mut r = vectorcraft_render::Renderer::new();
|
||||
for (what, art) in [("one object", vec![node(a)]), ("two objects", vec![node(a), node(b)])] {
|
||||
crate::canvas::clear_handed_over();
|
||||
let image = thumb_image(&mut r, doc, &art, 40).expect("the squares draw");
|
||||
assert_eq!(image.size, [40, 40], "{what}: the tile's size");
|
||||
assert!(image.pixels.iter().any(|p| p.a() > 0), "{what}: the tile shows the art");
|
||||
crate::canvas::assert_handed_over(&image, what);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,8 +122,8 @@ fn thumb_image(doc: &Arc<Document>, obj: &Node, own_mask: bool, px: u32, bg: Opt
|
||||
} else {
|
||||
obj
|
||||
};
|
||||
let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail_with(doc, n, px.max(8), bg, &super::layers::thumb_options()))?;
|
||||
Some(crate::canvas::color_image(&img))
|
||||
let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail_words_with(doc, n, px.max(8), bg, &super::layers::thumb_options()))?;
|
||||
Some(crate::canvas::color_image_owned(img))
|
||||
}
|
||||
|
||||
impl ThumbSource<MaskKey> for MaskThumbs<'_> {
|
||||
@@ -914,6 +914,25 @@ mod tests {
|
||||
assert!(Arc::ptr_eq(&undone, &held(&app, n.id)), "the node Undo put back");
|
||||
}
|
||||
|
||||
/// The object and mask thumbnails, on a background or none, hold the pixels they were rendered into.
|
||||
#[test]
|
||||
fn object_and_mask_thumbnails_are_handed_to_their_images_without_a_copy() {
|
||||
let mut app = new_app();
|
||||
let a = run_cmd(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone();
|
||||
let b = run_cmd(&mut app, "shape.ellipse", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].clone();
|
||||
run_cmd(&mut app, "select.set", json!({"ids": [a, b]}));
|
||||
run_cmd(&mut app, "transparency.makeOpacityMask", json!({}));
|
||||
let n = state(&mut app).1.expect("the masked object");
|
||||
let doc = app.session.active().unwrap().doc.clone();
|
||||
for own_mask in [false, true] {
|
||||
for bg in [None, Some([255; 4])] {
|
||||
crate::canvas::clear_handed_over();
|
||||
let image = thumb_image(&doc, &n, own_mask, 44, bg).expect("the thumbnail draws");
|
||||
crate::canvas::assert_handed_over(&image, &format!("mask {own_mask}, background {bg:?}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_highlighted_blend_mode_applies_only_once_it_is_chosen() {
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
Reference in New Issue
Block a user