mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-06 05:53:08 -05:00
Merge pull request #10840 from dotCooCoo/fix/canvas-upload-no-copy
Canvas: a rendered frame becomes its texture image without a copy
This commit is contained in:
14 files changed
+320
-92
No files matched your search
@@ -285,11 +285,14 @@ fn area_spans(from: usize, to: usize) -> Vec<Vec<(usize, f64)>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A rendered image (premultiplied RGBA8, row-major).
|
||||
pub struct Rendered {
|
||||
/// A rendered image (premultiplied RGBA8, row-major). Its pixels are bytes, or, from
|
||||
/// [`crate::Renderer::render_words`], words of four bytes that hold each pixel's bytes in memory
|
||||
/// in the same order: a buffer aligned to four bytes, which a 4-byte pixel type can take over
|
||||
/// without a copy.
|
||||
pub struct Rendered<P = Vec<u8>> {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub pixels: Vec<u8>,
|
||||
pub pixels: P,
|
||||
}
|
||||
|
||||
impl Rendered {
|
||||
|
||||
+121
-27
@@ -117,9 +117,32 @@ impl Renderer {
|
||||
self.render_document(doc, width, height, view, opts, None)
|
||||
}
|
||||
|
||||
/// [`Self::render`] with the pixels in words of four bytes ([`Rendered`]), rendered into
|
||||
/// that buffer.
|
||||
pub fn render_words(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Rendered<Vec<u32>> {
|
||||
self.render_document(doc, width, height, view, opts, None)
|
||||
}
|
||||
|
||||
/// Render a plain RGB canvas patch using a separate renderer. Raster effects and offscreen
|
||||
/// group compositing require the full render.
|
||||
pub fn render_plain_patch(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Option<Rendered> {
|
||||
self.plain_patch(doc, width, height, view, opts)
|
||||
}
|
||||
|
||||
/// [`Self::render_plain_patch`] with the pixels in words of four bytes, as
|
||||
/// [`Self::render_words`] returns them.
|
||||
pub fn render_plain_patch_words(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
width: u32,
|
||||
height: u32,
|
||||
view: Affine,
|
||||
opts: &RenderOptions,
|
||||
) -> Option<Rendered<Vec<u32>>> {
|
||||
self.plain_patch(doc, width, height, view, opts)
|
||||
}
|
||||
|
||||
fn plain_patch<P: FramePixels>(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Option<Rendered<P>> {
|
||||
if doc.color_mode != vectorcraft_doc::ColorMode::Rgb || opts.mask_view.is_some() || opts.supersample {
|
||||
return None;
|
||||
}
|
||||
@@ -128,7 +151,7 @@ impl Renderer {
|
||||
(!hit.get()).then_some(image)
|
||||
}
|
||||
|
||||
fn render_document(
|
||||
fn render_document<P: FramePixels>(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
width: u32,
|
||||
@@ -136,7 +159,7 @@ impl Renderer {
|
||||
view: Affine,
|
||||
opts: &RenderOptions,
|
||||
patch: Option<&std::cell::Cell<bool>>,
|
||||
) -> Rendered {
|
||||
) -> Rendered<P> {
|
||||
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
|
||||
let _frame = vectorcraft_text::KeptLayoutsFrame::begin();
|
||||
self.render_as(doc, width, height, view, opts, false, 1, patch)
|
||||
@@ -147,7 +170,7 @@ impl Renderer {
|
||||
/// pixel of the output in pixels of this render: the supersampling factor while an export
|
||||
/// draws its art at several times its size, else 1 ([`Frame::output`]).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn render_as(
|
||||
fn render_as<P: FramePixels>(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
width: u32,
|
||||
@@ -157,16 +180,18 @@ impl Renderer {
|
||||
inks: bool,
|
||||
cell: u32,
|
||||
patch: Option<&std::cell::Cell<bool>>,
|
||||
) -> Rendered {
|
||||
) -> Rendered<P> {
|
||||
let start = now();
|
||||
if opts.supersample && opts.anti_alias == AntiAlias::Art && opts.mask_view.is_none() {
|
||||
let (w, h) = (width.clamp(1, MAX_CONTEXT_SIDE), height.clamp(1, MAX_CONTEXT_SIDE));
|
||||
if let Some(k) = supersample_factor(w, h) {
|
||||
let hard = RenderOptions { anti_alias: AntiAlias::None, supersample: false, ..opts.clone() };
|
||||
let hairline = std::mem::replace(&mut self.hairline, f64::from(k));
|
||||
let big = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k, patch);
|
||||
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);
|
||||
drop(big);
|
||||
let pixels = P::from_bytes(pixels);
|
||||
self.stats.micros = now().saturating_sub(start);
|
||||
return Rendered { width: w, height: h, pixels };
|
||||
}
|
||||
@@ -203,12 +228,13 @@ impl Renderer {
|
||||
self.begin_frame();
|
||||
// View Opacity Mask: the mask's coverage in greyscale instead of the artwork.
|
||||
if let Some(m) = opts.mask_view.and_then(|id| doc.node(id)).and_then(|n| n.extras().mask.as_deref()) {
|
||||
let pixels = self
|
||||
.mask_values(&frame, m, w, h)
|
||||
.unwrap_or_else(|| vec![0; w as usize * h as usize])
|
||||
.into_iter()
|
||||
.flat_map(|v| [v, v, v, 255])
|
||||
.collect();
|
||||
let pixels = P::from_bytes(
|
||||
self.mask_values(&frame, m, w, h)
|
||||
.unwrap_or_else(|| vec![0; w as usize * h as usize])
|
||||
.into_iter()
|
||||
.flat_map(|v| [v, v, v, 255])
|
||||
.collect(),
|
||||
);
|
||||
self.end_frame();
|
||||
self.stats.symbol_art = symbols.art_measured();
|
||||
self.stats.micros = now().saturating_sub(start);
|
||||
@@ -219,23 +245,26 @@ impl Renderer {
|
||||
// proof that preserves the numbers, when one is on: the planes hold the inks as they
|
||||
// are, images included).
|
||||
let planes = if proof::preserving(opts).is_some() { None } else { frame.plates };
|
||||
let cmy = self.draw_frame(&Frame { ink: Ink::Cmy, plates: planes, ..frame }, w, h);
|
||||
let cmy: Vec<u8> = self.draw_frame(&Frame { ink: Ink::Cmy, plates: planes, ..frame }, w, h);
|
||||
let stats = self.stats;
|
||||
let k = self.draw_frame(&Frame { ink: Ink::K, plates: planes, ..frame }, w, h);
|
||||
let k: Vec<u8> = self.draw_frame(&Frame { ink: Ink::K, plates: planes, ..frame }, w, h);
|
||||
self.stats = stats;
|
||||
if inks {
|
||||
let pixels = if inks {
|
||||
ink::amounts(&cmy, &k)
|
||||
} else {
|
||||
let (pixels, composed) = ink::compose(&cmy, &k, opts, threads);
|
||||
self.stats.ink_threads = composed;
|
||||
pixels
|
||||
}
|
||||
};
|
||||
drop((cmy, k));
|
||||
P::from_bytes(pixels)
|
||||
} else {
|
||||
self.draw_frame(&frame, w, h)
|
||||
};
|
||||
self.end_frame();
|
||||
if !inks && !pixels.is_empty() {
|
||||
proof::post(&mut pixels, opts);
|
||||
let bytes = pixels.bytes_mut();
|
||||
if !inks && !bytes.is_empty() {
|
||||
proof::post(bytes, opts);
|
||||
}
|
||||
self.stats.symbol_art = symbols.art_measured();
|
||||
self.stats.micros = now().saturating_sub(start);
|
||||
@@ -325,7 +354,7 @@ impl Renderer {
|
||||
/// Draw frame `f` (`w`×`h` pixels): the artboards and the page's art, then the background
|
||||
/// under them. The art blends only with itself, as it does on the canvas, where the paper is
|
||||
/// drawn apart from it: a Screen glow on the bare page stays visible on a white background (#6125).
|
||||
fn draw_frame(&mut self, f: &Frame, w: u16, h: u16) -> Vec<u8> {
|
||||
fn draw_frame<P: FramePixels>(&mut self, f: &Frame, w: u16, h: u16) -> P {
|
||||
let (threads, opts) = (self.threads, f.opts);
|
||||
let kept = self.contexts.iter().position(|(t, c)| *t == threads && c.width() == w && c.height() == h);
|
||||
let mut ctx = match kept.map(|i| self.contexts.remove(i)) {
|
||||
@@ -366,20 +395,19 @@ impl Renderer {
|
||||
} else {
|
||||
self.draw_page(&mut ctx, f);
|
||||
}
|
||||
let pm = if f.patch_rejected() {
|
||||
let pixels = if f.patch_rejected() {
|
||||
self.picture = None;
|
||||
None
|
||||
} else {
|
||||
Some(self.finish(&mut ctx, self.raster))
|
||||
Some(P::finish(self, &mut ctx))
|
||||
};
|
||||
self.contexts.push((threads, ctx));
|
||||
if self.contexts.len() > 2 {
|
||||
self.contexts.remove(0);
|
||||
}
|
||||
let Some(pm) = pm else { return Vec::new() };
|
||||
let mut pixels = group::into_bytes(pm);
|
||||
let Some(mut pixels) = pixels else { return P::from_bytes(Vec::new()) };
|
||||
if let Some(bg) = opts.background {
|
||||
over_background(&mut pixels, f.ink.fixed8(screen_under_art(f, bg)));
|
||||
over_background(pixels.bytes_mut(), f.ink.fixed8(screen_under_art(f, bg)));
|
||||
}
|
||||
pixels
|
||||
}
|
||||
@@ -413,15 +441,24 @@ impl Renderer {
|
||||
/// Render one artboard (or any document rect) at `scale` pixels per point, transparent or on white,
|
||||
/// as exported: template layers and guides are left out.
|
||||
pub fn render_region(&mut self, doc: &Document, region: Rect, scale: f64, white: bool) -> Rendered {
|
||||
let opts = RenderOptions { background: white.then_some([255, 255, 255, 255]), skip_templates: true, ..Default::default() };
|
||||
self.render_region_with(doc, region, scale, &opts)
|
||||
self.region(doc, region, scale, ®ion_options(white))
|
||||
}
|
||||
|
||||
/// [`Self::render_region`] with the pixels in words of four bytes, as [`Self::render_words`]
|
||||
/// returns them.
|
||||
pub fn render_region_words(&mut self, doc: &Document, region: Rect, scale: f64, white: bool) -> Rendered<Vec<u32>> {
|
||||
self.region(doc, region, scale, ®ion_options(white))
|
||||
}
|
||||
|
||||
/// Render a document rect at `scale` pixels per point with `opts`.
|
||||
pub fn render_region_with(&mut self, doc: &Document, region: Rect, scale: f64, opts: &RenderOptions) -> Rendered {
|
||||
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));
|
||||
self.render(doc, w, h, view, opts)
|
||||
self.render_document(doc, w, h, view, opts, None)
|
||||
}
|
||||
|
||||
/// `region` of `doc` as ink amounts in the working CMYK space, 4 bytes a pixel (0 = no ink):
|
||||
@@ -433,7 +470,7 @@ impl Renderer {
|
||||
let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0));
|
||||
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
|
||||
let _frame = vectorcraft_text::KeptLayoutsFrame::begin();
|
||||
self.render_as(doc, w, h, view, opts, true, 1, None).pixels
|
||||
self.render_as::<Vec<u8>>(doc, w, h, view, opts, true, 1, None).pixels
|
||||
}
|
||||
|
||||
/// Render a single node (thumbnails, previews) fitted into `size`×`size` pixels.
|
||||
@@ -544,6 +581,11 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// The options of [`Renderer::render_region`]: as exported, transparent or on white.
|
||||
fn region_options(white: bool) -> RenderOptions {
|
||||
RenderOptions { background: white.then_some([255, 255, 255, 255]), skip_templates: true, ..Default::default() }
|
||||
}
|
||||
|
||||
/// The rasterizer settings for `opts`: the quality render mode when [`RenderOptions::precise`] is set.
|
||||
fn raster_settings(opts: &RenderOptions) -> vello_cpu::RasterizerSettings {
|
||||
let render_mode = if opts.precise { vello_cpu::RenderMode::OptimizeQuality } else { vello_cpu::RenderMode::OptimizeSpeed };
|
||||
@@ -557,6 +599,58 @@ fn screen_under_art(f: &Frame, rgba: [u8; 4]) -> [u8; 4] {
|
||||
if matches!(f.ink.base(), Ink::Cmy | Ink::K) { rgba } else { proof::under_art(f.opts, rgba) }
|
||||
}
|
||||
|
||||
/// The buffer a frame's premultiplied RGBA pixels are returned in ([`Rendered::pixels`]).
|
||||
pub(crate) trait FramePixels: Sized {
|
||||
/// The pixels `ctx` holds, rendered by [`Renderer::finish`]'s rules.
|
||||
fn finish(r: &mut Renderer, ctx: &mut RenderContext) -> Self;
|
||||
/// The pixels in `bytes` (four a pixel).
|
||||
fn from_bytes(bytes: Vec<u8>) -> Self;
|
||||
/// The pixels as bytes, four a pixel.
|
||||
fn bytes_mut(&mut self) -> &mut [u8];
|
||||
}
|
||||
|
||||
impl FramePixels for Vec<u8> {
|
||||
fn finish(r: &mut Renderer, ctx: &mut RenderContext) -> Self {
|
||||
group::into_bytes(r.finish(ctx, r.raster))
|
||||
}
|
||||
|
||||
fn from_bytes(bytes: Vec<u8>) -> Self {
|
||||
bytes
|
||||
}
|
||||
|
||||
fn bytes_mut(&mut self) -> &mut [u8] {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Each word holds a pixel's four bytes in memory in the order a byte buffer holds them.
|
||||
impl FramePixels for Vec<u32> {
|
||||
/// Over transparency, `ctx` renders straight into the words. Over a picture
|
||||
/// ([`Renderer::finish`]), the rendered pixmap is copied into them.
|
||||
fn finish(r: &mut Renderer, ctx: &mut RenderContext) -> Self {
|
||||
if r.picture.is_none() {
|
||||
ctx.flush();
|
||||
let (w, h) = (ctx.width(), ctx.height());
|
||||
let mut words = vec![0u32; usize::from(w) * usize::from(h)];
|
||||
if let Some(target) = vello_cpu::PixmapMut::new(w, h, bytemuck::cast_slice_mut(&mut words)) {
|
||||
ctx.render_with(target, &mut r.resources, r.raster);
|
||||
#[cfg(test)]
|
||||
group::FINISHED.with(|p| p.set(words.as_ptr() as usize));
|
||||
return words;
|
||||
}
|
||||
}
|
||||
Self::from_bytes(group::into_bytes(r.finish(ctx, r.raster)))
|
||||
}
|
||||
|
||||
fn from_bytes(bytes: Vec<u8>) -> Self {
|
||||
bytes.as_chunks::<4>().0.iter().map(|p| u32::from_ne_bytes(*p)).collect()
|
||||
}
|
||||
|
||||
fn bytes_mut(&mut self) -> &mut [u8] {
|
||||
bytemuck::cast_slice_mut(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Premultiplied RGBA `pixels` drawn over the solid color `background` (`[r, g, b, a]`, straight).
|
||||
pub(crate) fn over_background(pixels: &mut [u8], [r, g, b, a]: [u8; 4]) {
|
||||
let alpha = u32::from(a);
|
||||
|
||||
@@ -41,6 +41,7 @@ mod tileedge;
|
||||
mod typeedges;
|
||||
mod viewraster;
|
||||
mod widthzoom;
|
||||
mod words;
|
||||
|
||||
fn rect_node(d: &mut Document, r: Rect, fill: Paint, stroke: Paint, w: f64) -> Node {
|
||||
let id = d.alloc_id();
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
//! A frame rendered in words ([`Renderer::render_words`]): the bytes [`Renderer::render`] returns,
|
||||
//! rendered straight into the words.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
use vectorcraft_color::{BlendMode as Blend, Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, ColorMode, Node};
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
use crate::group::FINISHED;
|
||||
use crate::*;
|
||||
|
||||
fn rect(d: &mut Document, r: Rect, c: Color) -> Node {
|
||||
Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0))
|
||||
}
|
||||
|
||||
/// A 100 × 100 pt page in `mode` with a page-sized rectangle under the nodes `top` makes.
|
||||
fn page(mode: ColorMode, top: impl FnOnce(&mut Document) -> Vec<Node>) -> Document {
|
||||
let mut d = Document::new_with_mode(100.0, 100.0, mode);
|
||||
let below = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(0.8, 0.6, 0.2));
|
||||
let top = top(&mut d);
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), usize::MAX, below).unwrap();
|
||||
for n in top {
|
||||
d.insert(Some(l), usize::MAX, n).unwrap();
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
fn square(d: &mut Document) -> Node {
|
||||
rect(d, Rect::new(10.0, 20.0, 60.0, 45.0), Color::rgb(0.1, 0.4, 0.9))
|
||||
}
|
||||
|
||||
/// A half-opaque group that blends with the page under it: drawn offscreen over a copy of it.
|
||||
fn blending_group(d: &mut Document) -> Node {
|
||||
let mut child = rect(d, Rect::new(20.0, 20.0, 80.0, 80.0), Color::rgb(0.5, 0.5, 1.0));
|
||||
child.blend = Blend::Multiply;
|
||||
let mut g = Node::group(d.alloc_id(), vec![Arc::new(child)]);
|
||||
g.opacity = 0.5;
|
||||
g
|
||||
}
|
||||
|
||||
fn finished() -> usize {
|
||||
FINISHED.with(Cell::get)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_in_words_holds_the_bytes_of_the_same_frame_in_bytes() {
|
||||
let rgb = |top: fn(&mut Document) -> Node| page(ColorMode::Rgb, |d| vec![top(d)]);
|
||||
let cases = [
|
||||
("a square", rgb(square), RenderOptions::default()),
|
||||
("over no background", rgb(square), RenderOptions { background: None, artboards: false, ..Default::default() }),
|
||||
("a blending group", rgb(blending_group), RenderOptions::default()),
|
||||
("CMYK blending", page(ColorMode::Cmyk, |d| vec![blending_group(d)]), RenderOptions::default()),
|
||||
("supersampled", rgb(square), RenderOptions { supersample: true, ..Default::default() }),
|
||||
("outline", rgb(square), RenderOptions { outline: true, ..Default::default() }),
|
||||
];
|
||||
for (what, d, opts) in cases {
|
||||
for (w, h, view) in [(100, 100, Affine::IDENTITY), (37, 61, Affine::scale(1.7) * Affine::translate((-5.0, -3.0)))] {
|
||||
let bytes = Renderer::new().render(&d, w, h, view, &opts);
|
||||
let words = Renderer::new().render_words(&d, w, h, view, &opts);
|
||||
assert_eq!((words.width, words.height), (bytes.width, bytes.height), "{what}: the frame's size");
|
||||
assert_eq!(words.pixels.len() * 4, bytes.pixels.len(), "{what}: a word a pixel");
|
||||
assert!(bytemuck::cast_slice::<u32, u8>(&words.pixels) == bytes.pixels.as_slice(), "{what} ({w} × {h}): the same bytes");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_in_words_is_returned_in_the_buffer_it_rendered_into() {
|
||||
let d = page(ColorMode::Rgb, |d| vec![square(d)]);
|
||||
let mut r = Renderer::new();
|
||||
for background in [None, Some([255, 255, 255, 255])] {
|
||||
let opts = RenderOptions { background, ..Default::default() };
|
||||
let out = r.render_words(&d, 64, 48, Affine::IDENTITY, &opts);
|
||||
assert_eq!(out.pixels.len(), 64 * 48);
|
||||
assert_eq!(out.pixels.as_ptr() as usize, finished(), "background {background:?}: the words it rendered into are returned");
|
||||
}
|
||||
let patch = r.render_plain_patch_words(&d, 64, 48, Affine::IDENTITY, &RenderOptions::default()).expect("a plain page renders as a patch");
|
||||
assert_eq!(patch.pixels.as_ptr() as usize, finished(), "a patch's words are returned without a copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_region_in_words_holds_the_bytes_of_the_region_in_bytes() {
|
||||
let d = page(ColorMode::Rgb, |d| vec![square(d), blending_group(d)]);
|
||||
let region = Rect::new(5.0, 15.0, 70.0, 90.0);
|
||||
for white in [false, true] {
|
||||
let bytes = Renderer::new().render_region(&d, region, 1.3, white);
|
||||
let mut r = Renderer::new();
|
||||
let words = r.render_region_words(&d, region, 1.3, white);
|
||||
assert_eq!((words.width, words.height), (bytes.width, bytes.height), "white {white}: the region's size");
|
||||
assert!(bytemuck::cast_slice::<u32, u8>(&words.pixels) == bytes.pixels.as_slice(), "white {white}: the same bytes");
|
||||
}
|
||||
let plain = page(ColorMode::Rgb, |d| vec![square(d)]);
|
||||
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");
|
||||
}
|
||||
Reference in new issue
Block a user