Compare commits

..
21 changed files with 1459 additions and 54 deletions

No files matched your search

Generated
+2 -2
View File
@@ -2675,7 +2675,6 @@ dependencies = [
"math-nodes",
"node-macro",
"path-bool-nodes",
"raster-kernels",
"raster-nodes",
"rendering",
"repeat-nodes",
@@ -5437,9 +5436,11 @@ dependencies = [
"glam",
"graph-craft",
"graphene-std",
"graphic-types",
"interpreted-executor",
"log",
"node-macro",
"wgpu-executor",
]
[[package]]
@@ -8078,7 +8079,6 @@ dependencies = [
"log",
"node-macro",
"ollev",
"raster-kernels",
"raster-types",
"vector-types",
]
@@ -37,6 +37,7 @@ impl FrontendGraphDataType {
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
// A generator draws pixels like an image, at whatever resolution is needed
"Generator" => Self::Raster,
"Pixels" => Self::Raster,
raster if raster.starts_with("Raster") => Self::Raster,
_ => Self::General,
}
+9 -1
View File
@@ -12,7 +12,7 @@ pub use glam::{DAffine2, DVec2, IVec2, UVec2};
use graphene_animation::AnimationCurve;
use graphene_application_io::resource::ResourceHash;
use graphene_application_io::resource::ResourceId;
use graphic_types::raster_types::{CPU, Image, Raster};
use graphic_types::raster_types::{CPU, Image, Pixels, Raster};
use graphic_types::vector_types::vector::misc::BoxCorners;
use graphic_types::vector_types::vector::style::DashPattern;
use graphic_types::vector_types::vector::style::{Gradient, GradientRamp};
@@ -400,6 +400,11 @@ macro_rules! tagged_value {
Type::Fn(_, output) => TaggedValue::from_type(output),
// Element types with a dedicated variant use it directly (the variant's value is a rank-0 cell); the rest store the structural type
Type::Item(element) => TaggedValue::from_type(element).or_else(|| {
// Pixels are read back from an image, so a `Pixels` input holds the empty image
if **element == concrete!(Pixels) {
return Some(TaggedValue::TypeDefault(item!(Raster<CPU>)));
}
macro_rules! check {
($type_default:ty) => {
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
@@ -416,6 +421,9 @@ macro_rules! tagged_value {
if **element == concrete!(Stroke) {
return Some(TaggedValue::Strokes(Vec::new()));
}
if **element == concrete!(Pixels) {
return Some(TaggedValue::TypeDefault(list!(Raster<CPU>)));
}
macro_rules! check {
($type_default:ty) => {
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
@@ -440,6 +440,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
node_types.extend(ranked_value_types!(cache_chain_nodes));
// The direct counterpart to `Box<VectorModification>`'s promotion adapter above (see that note)
node_types.extend(cache_chain_nodes!(Box<VectorModification>));
// Context nullification can wrap the read-back adapter's output
node_types.extend(cache_chain_nodes!(Pixels));
// A position wire may feed a ranked vector connector, each position becoming a single-anchor vector
node_types.extend(input_adapter_row!(from_element: DVec2, element: Vector));
// A string wire may feed the ranked `Item<DashPattern>` dash connector by parsing each element into a dash pattern
@@ -496,6 +498,20 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// Position and transform wires may feed a ranked `String` connector by formatting each element as text
node_types.extend(convert_adapter_node!(from_element: DVec2, element: String));
node_types.extend(convert_adapter_node!(from_element: DAffine2, element: String));
// An image wire feeds a `Pixels` connector through its GPU readback, an async node taking the executor, runtime, and source ID after the wire.
// These rows have no one-input passthrough siblings, which type resolution would match by their first input alone.
macro_rules! read_back_node {
($node:ty, wire: $wire:ty) => {
async_node!(
identifier: graphene_std::read_back::INPUT_ADAPTER,
$node,
input: Context,
fn_params: [Context => $wire, Context => Item<wgpu_executor::WgpuExecutor>, Context => Item<graphene_std::RuntimeHandle>, Context => Item<graphene_std::SourceId>]
)
};
}
node_types.push(read_back_node!(graphene_std::read_back::ReadBackNode<_, _, _, _>, wire: Item<Raster<CPU>>));
node_types.push(read_back_node!(graphene_std::read_back::ReadBackListNode<_, _, _, _>, wire: List<Raster<CPU>>));
// The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value
macro_rules! attribute_value_node {
(Item<$element:ty>) => {
@@ -312,6 +312,29 @@ mod cpu {
}
}
/// An image's pixels as it's drawn, with its effects and fill carried out on its own pixel grid.
/// A node input of this type has the compiler read them back from the image wired into it, which carries its effects as attributes until then.
#[derive(Clone, Debug, Default, PartialEq, DynAny, core_types::CacheHash)]
pub struct Pixels(Raster<CPU>);
impl Pixels {
pub fn new(raster: Raster<CPU>) -> Self {
Self(raster)
}
pub fn into_raster(self) -> Raster<CPU> {
self.0
}
}
impl Deref for Pixels {
type Target = Image<Color>;
fn deref(&self) -> &Self::Target {
self.0.data()
}
}
pub use gpu::GPU;
#[cfg(feature = "wgpu")]
pub use gpu::{Texture, TextureWeakRef};
@@ -6024,6 +6024,12 @@ pub(crate) fn render_raster_cpu_image_svg(image: &Raster<CPU>, transform: DAffin
}
}
/// The adjustments at the start of the image's effects that its render carries out on its own pixels, ahead of the rest.
pub fn leading_raster_adjustments(item: &Item<Raster<CPU>>) -> Vec<Adjustment> {
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
ItemRef::Item(item).compositing(&RenderParams::default(), transform).leading_adjustments()
}
/// Draws one item of CPU raster content into the Vello scene.
fn render_raster_cpu_item_to_vello(item: ItemRef<'_, Raster<CPU>>, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
let Some(image) = item.element() else { return };
+17 -2
View File
@@ -2,6 +2,7 @@ mod buffer;
mod context;
mod deferred_svg_images;
mod pipeline;
mod raster_readback;
mod texture_cache;
pub mod texture_conversion;
mod vello_adjustments;
@@ -75,6 +76,19 @@ impl WgpuExecutor {
/// Renders the document scene `draw` draws, with its content placed by `view`, into a new texture of `size` with straight alpha.
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
pub fn render_vello(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<Texture> {
Ok(self.render_vello_and_failure(size, view, draw)?.0)
}
/// Like [`Self::render_vello`], but failing rather than leaving transparent a part Vello GPU fails to render, for a render read back as data.
pub fn try_render_vello(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<Texture> {
match self.render_vello_and_failure(size, view, draw)? {
(_, Some(failure)) => anyhow::bail!("Vello GPU failed to render: {failure}"),
(texture, None) => Ok(texture),
}
}
/// The texture [`Self::render_vello`] renders, with the first failure that left part of it transparent.
fn render_vello_and_failure(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<(Texture, Option<String>)> {
let limit = self.context().device.limits().max_texture_dimension_2d;
if size.x > limit || size.y > limit {
anyhow::bail!("Render size {size} exceeds the GPU's texture size limit of {limit}");
@@ -84,11 +98,12 @@ impl WgpuExecutor {
let view = vello_gpu::kurbo::Affine::new(view.to_cols_array());
let mut canvas = self.inner.document_canvas.lock().unwrap_or_else(PoisonError::into_inner);
self.inner
let failure = self
.inner
.vello_renderer
.render(&mut canvas, &self.context().device, &self.context().queue, draw, view, size, &texture)?;
Ok(texture)
Ok((texture, failure))
}
/// Renders a scene drawn beforehand, on a canvas the caller owns, into a new texture of the scene's size with straight alpha.
@@ -0,0 +1,648 @@
use crate::WgpuExecutor;
use crate::texture_conversion::download_row_bytes;
use core_types::blending::BlendMode;
use core_types::list::{ATTR_EFFECTS, Item, List};
use core_types::transform::Footprint;
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
use glam::{DAffine2, DVec2, UVec2};
use graphic_types::Graphic;
use graphic_types::effects::{EffectOperation, Effects};
use raster_kernels::adjustments::preserves_alpha;
use raster_kernels::raster_effects::adjusted_raster;
use raster_types::{CPU, Image, Pixels, Raster};
use rendering::{Render, RenderOutputType, RenderParams, leading_raster_adjustments};
/// The most pixels an image may grow to with the margin its effects paint into, beyond which the margin is cut short.
const MAX_PIXELS_WITH_MARGIN: f64 = (1 << 24) as f64;
/// The GPU's limits that a readback's renders and downloads stay within.
#[derive(Clone, Copy, Debug)]
struct ReadbackLimits {
/// The most pixels across or down a texture may have, which an image larger than it is downscaled to when uploaded whole.
texture_size: u32,
/// The most bytes a download buffer may hold.
buffer_size: u64,
}
impl ReadbackLimits {
fn of(executor: &WgpuExecutor) -> Self {
let limits = executor.context().device.limits();
Self {
texture_size: limits.max_texture_dimension_2d,
buffer_size: limits.max_buffer_size,
}
}
/// The largest tile, at most `max` pixels across and down, that a texture and its download buffer can hold, or `None` if not even one pixel fits.
fn tile_size(&self, max: UVec2) -> Option<UVec2> {
// Each row's bytes are padded to 256, which 64 pixels fill
let widest_row = (self.buffer_size / wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as u64 * 64).min(u32::MAX as u64) as u32;
let width = max.x.min(self.texture_size).min(widest_row);
if width == 0 {
return None;
}
let height = max.y.min(self.texture_size).min((self.buffer_size / download_row_bytes(width) as u64).min(u32::MAX as u64) as u32);
(height > 0).then_some(UVec2::new(width, height))
}
}
impl WgpuExecutor {
/// The image's pixels as it's drawn, with its effects and fill carried out at its own pixel grid, grown by whole pixels to hold what they paint past its edges.
/// The opacity and blend mode stay for whatever draws the result.
pub async fn read_back(&self, item: Item<Raster<CPU>>) -> anyhow::Result<Item<Pixels>> {
self.read_back_within(item, ReadbackLimits::of(self)).await
}
/// Like [`Self::read_back`], within the GPU `limits`.
async fn read_back_within(&self, item: Item<Raster<CPU>>, limits: ReadbackLimits) -> anyhow::Result<Item<Pixels>> {
let effects: Effects = item.attribute_cloned_or_default(ATTR_EFFECTS);
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.);
let size = UVec2::new(item.element().width, item.element().height);
// Nothing to carry out, or nothing to carry it out on
if (effects.change_nothing() && fill >= 1.) || size.cmpeq(UVec2::ZERO).any() || !transform.matrix2.determinant().is_normal() || !transform.is_finite() {
let raster = item.element().clone();
return Ok(carried_out(item, raster));
}
if let Some(adjusted) = adjusted_without_render(&item, &effects, fill) {
return Ok(carried_out(item, adjusted));
}
let reach = effects_reach(&effects, size.as_dvec2());
if !reach.is_finite() {
anyhow::bail!("The effects on a {} by {} image reach too far to render", size.x, size.y);
}
let margin = capped_margin(reach, size.as_dvec2());
let raster = self.render_at_pixel_grid(&item, &effects, transform, margin, reach, limits).await?;
let unit_margin = margin / size.as_dvec2();
let mut item = carried_out(item, raster);
item.set_attribute(
ATTR_TRANSFORM,
transform * DAffine2::from_translation(-unit_margin) * DAffine2::from_scale(DVec2::ONE + 2. * unit_margin),
);
Ok(item)
}
/// Renders the raster `item` placed by `transform` with its `effects`, one pixel of the render per pixel of its image, grown by `margin` pixels along each axis.
/// A render larger than the GPU's `limits` allow is drawn in tiles. When the whole image is too large to upload, each is drawn from a crop holding the pixels the effects `reach` past it.
async fn render_at_pixel_grid(&self, item: &Item<Raster<CPU>>, effects: &Effects, transform: DAffine2, margin: DVec2, reach: DVec2, limits: ReadbackLimits) -> anyhow::Result<Raster<CPU>> {
let image = item.element();
let size = UVec2::new(image.width, image.height);
let grown_size = size + 2 * margin.as_uvec2();
let document_to_pixels = DAffine2::from_translation(margin) * DAffine2::from_scale(size.as_dvec2()) * transform.inverse();
// The content on its own, without the opacity and blend mode that act on its effects' result as a whole
let mut content = item.clone();
content.remove_attribute::<f64>(ATTR_OPACITY);
content.remove_attribute::<BlendMode>(ATTR_BLEND_MODE);
// Each tile draws a crop of an image too large to upload whole, holding the pixels its effects read, unless they depend on the whole image's extent
let too_large_to_upload = size.cmpgt(UVec2::splat(limits.texture_size)).any();
let crops = too_large_to_upload && !effects.any_takes_frame() && !effects.reach_depends_on_size();
if too_large_to_upload && !crops {
log::warn!(
"A {} by {} image is read back at a lower resolution, since it's too large for the GPU and its effects depend on its whole extent",
size.x,
size.y
);
}
// A crop holds what the effects reach on both sides of its tile, which has to leave a texture room for at least a pixel, checked before the reach becomes an integer
let max_tile_size = match crops {
true => {
let room = DVec2::splat(limits.texture_size as f64) - 2. * reach;
if !room.cmpge(DVec2::ONE).all() {
anyhow::bail!("The effects on a {} by {} image reach too far past each pixel to render it in tiles the GPU can hold", size.x, size.y);
}
room.floor().as_uvec2()
}
false => grown_size,
};
let (margin, reach) = (margin.as_uvec2(), reach.as_uvec2());
let Some(tile_size) = limits.tile_size(max_tile_size) else {
anyhow::bail!("The GPU's textures and buffers can't hold a tile of a {} by {} image's render with its effects", size.x, size.y);
};
// The raster's render carries out leading adjustments changing alpha on its image's own pixels, which a crop's group can't, so they're carried out first
if crops {
let leading_adjustments = leading_raster_adjustments(&content);
if leading_adjustments.iter().any(|adjustment| !preserves_alpha(adjustment)) {
let adjusted = adjusted_raster(content.element(), &leading_adjustments);
let (_, attributes) = content.into_parts();
content = Item::from_parts(adjusted, attributes);
content.set_attribute(ATTR_EFFECTS, effects.after(leading_adjustments.len()));
}
}
let whole = List::new_from_item(content.clone());
if !crops && grown_size.cmple(tile_size).all() {
return self.render_tile(&whole, document_to_pixels, grown_size).await;
}
let mut pixels = Image::try_new(grown_size.x, grown_size.y, Color::TRANSPARENT)?;
for tile_y in (0..grown_size.y).step_by(tile_size.y as usize) {
for tile_x in (0..grown_size.x).step_by(tile_size.x as usize) {
let origin = UVec2::new(tile_x, tile_y);
let size_in_tile = (grown_size - origin).min(tile_size);
let tile_to_pixels = DAffine2::from_translation(-origin.as_dvec2()) * document_to_pixels;
let tile = match crops {
// The tile spans the image's pixels from `origin - margin`, and its effects read up to their reach past it
true => {
let start = origin.saturating_sub(margin + reach);
let end = (origin + size_in_tile + reach).saturating_sub(margin).min(size);
self.render_tile(&cropped(&content, start, end), tile_to_pixels, size_in_tile).await?
}
false => self.render_tile(&whole, tile_to_pixels, size_in_tile).await?,
};
for row in 0..size_in_tile.y as usize {
let start = (origin.y as usize + row) * grown_size.x as usize + origin.x as usize;
let tile_row = &tile.data[row * size_in_tile.x as usize..(row + 1) * size_in_tile.x as usize];
pixels.data[start..start + size_in_tile.x as usize].copy_from_slice(tile_row);
}
}
}
Ok(Raster::new_cpu(pixels))
}
/// Renders the `content` into an image of `size` pixels, which `document_to_pixels` places the document in, and reads it back.
async fn render_tile(&self, content: &(impl Render + Sync), document_to_pixels: DAffine2, size: UVec2) -> anyhow::Result<Raster<CPU>> {
let render_params = RenderParams {
render_output_type: RenderOutputType::Vello,
footprint: Footprint {
transform: document_to_pixels,
resolution: size,
..Default::default()
},
for_export: true,
..Default::default()
};
let texture = self.try_render_vello(size, document_to_pixels, &mut |scene| content.render_to_vello(scene, DAffine2::IDENTITY, &render_params))?;
self.try_download(Raster::new_gpu(texture)).await
}
}
/// The `item` with its image replaced by the `raster` its effects and fill are carried out in, without the attributes holding them.
fn carried_out(item: Item<Raster<CPU>>, raster: Raster<CPU>) -> Item<Pixels> {
let (_, attributes) = item.into_parts();
let mut item = Item::from_parts(Pixels::new(raster), attributes);
item.remove_attribute::<Effects>(ATTR_EFFECTS);
item.remove_attribute::<f64>(ATTR_OPACITY_FILL);
item
}
/// The image with its `effects` and `fill` carried out on the CPU if the effects are all adjustments its render carries out on its own pixels, or `None` if any needs a render.
/// The CPU keeps the adjustments' full precision, including values past 0 to 1 and colors beneath zero alpha, which an 8-bit download would lose.
fn adjusted_without_render(item: &Item<Raster<CPU>>, effects: &Effects, fill: f64) -> Option<Raster<CPU>> {
let adjustments = leading_raster_adjustments(item);
if adjustments.len() < effects.operations().count() {
return None;
}
// Under a partial fill, the leading adjustments all keep alpha, so fading after them matches fading before
let mut adjusted = adjusted_raster(item.element(), &adjustments);
if fill < 1. {
adjusted.data_mut().data.iter_mut().for_each(|color| *color = color.with_alpha(color.a() * fill as f32));
}
Some(adjusted)
}
/// The raster `content` drawn from only its image's pixels from `start` up to `end`, at their own resolution where they lie in the whole image.
/// The crop sits within a group taking the content's placement and effects, so the effects measure and place what they draw as for the whole image.
fn cropped(content: &Item<Raster<CPU>>, start: UVec2, end: UVec2) -> List<Graphic> {
let image = content.element();
let (size, crop_size) = (UVec2::new(image.width, image.height), end.saturating_sub(start));
if crop_size.cmpeq(UVec2::ZERO).any() {
return List::new();
}
let data = (start.y..end.y)
.flat_map(|y| {
let row = (y * size.x) as usize;
image.data[row + start.x as usize..row + end.x as usize].iter().copied()
})
.collect();
let crop = Image {
width: crop_size.x,
height: crop_size.y,
data,
};
let placement = DAffine2::from_translation(start.as_dvec2() / size.as_dvec2()) * DAffine2::from_scale(crop_size.as_dvec2() / size.as_dvec2());
let crop = Item::new_from_element(Raster::new_cpu(crop)).with_attribute(ATTR_TRANSFORM, placement);
let (_, attributes) = content.clone().into_parts();
List::new_from_item(Item::from_parts(Graphic::RasterCPU(Box::new(crop)), attributes))
}
/// How far, in whole pixels along each axis of an image of `size` pixels, its `effects` paint and read past each pixel and its edges.
fn effects_reach(effects: &Effects, size: DVec2) -> DVec2 {
// The content's unit square spans the image's pixels
let content_to_pixels = DAffine2::from_scale(size);
let reach = (effects.reach_around(content_to_pixels, [DVec2::ZERO, size], 0.) + effects.read_beyond_painted(content_to_pixels)).ceil();
// A feather fades the content toward its edges, finding them against the pixels past them
match effects.operations().any(|operation| matches!(operation, EffectOperation::Feather { distance } if distance > 0.)) {
true => reach.max(DVec2::ONE),
false => reach,
}
}
/// The margin an image of `size` pixels grows by to hold its effects' `reach`, cut short evenly past [`MAX_PIXELS_WITH_MARGIN`].
fn capped_margin(reach: DVec2, size: DVec2) -> DVec2 {
if (size + 2. * reach).element_product() <= MAX_PIXELS_WITH_MARGIN {
return reach;
}
let margin = (reach * margin_fraction_that_fits(size, reach)).floor();
if margin.max_element() < reach.max_element() {
log::warn!(
"The effects on a {} by {} image end at a hard edge {} pixels past it, short of the {} they reach, since the image can't grow past {MAX_PIXELS_WITH_MARGIN} pixels",
size.x,
size.y,
margin.max_element(),
reach.max_element()
);
}
margin
}
/// The fraction of `margin` that grows an image of `size` to [`MAX_PIXELS_WITH_MARGIN`], or 0 if the image alone already reaches it.
fn margin_fraction_that_fits(size: DVec2, margin: DVec2) -> f64 {
// The positive root of (width + 2 × fraction × margin width) × (height + 2 × fraction × margin height) = the limit
let quadratic = 4. * margin.x * margin.y;
let linear = 2. * (size.x * margin.y + size.y * margin.x);
let constant = size.element_product() - MAX_PIXELS_WITH_MARGIN;
if constant >= 0. || linear <= 0. {
return 0.;
}
let fraction = match quadratic > 0. {
true => (-linear + (linear * linear - 4. * quadratic * constant).sqrt()) / (2. * quadratic),
false => -constant / linear,
};
fraction.clamp(0., 1.)
}
#[cfg(test)]
mod tests {
use super::*;
use core_types::color::SRGBA8;
use core_types::list::ATTR_APPEARANCE;
use futures::executor::block_on;
use graphic_types::vector_types::vector::style::StrokeAlign;
use graphic_types::{Appearance, Coverage, Effect, Graphic, MaskMode, Vector, stamp_effect};
use vello_gpu::kurbo::{Rect, Shape};
/// The executor these tests share, or `None` without a GPU.
fn executor() -> Option<&'static WgpuExecutor> {
static EXECUTOR: std::sync::OnceLock<Option<WgpuExecutor>> = std::sync::OnceLock::new();
EXECUTOR.get_or_init(|| block_on(crate::WgpuContext::for_tests()).and_then(WgpuExecutor::with_context)).as_ref()
}
/// The size in the document of the pixels of an image scaled unevenly, 1 unit wide and 4 tall.
const TALL_PIXEL: DVec2 = DVec2::new(1., 4.);
/// An image of 20 by 20 pixels, each `pixel_size` in the document, colored by `color` at each pixel's column and row, with its corner at (100, 50).
fn image_of_pixels(pixel_size: DVec2, color: impl Fn(u32, u32) -> Color, effects: &[EffectOperation]) -> Item<Raster<CPU>> {
let data = (0..20 * 20).map(|index| color(index % 20, index / 20)).collect();
let transform = DAffine2::from_translation(DVec2::new(100., 50.)) * DAffine2::from_scale(20. * pixel_size);
let mut item = Item::new_from_element(Raster::new_cpu(Image { width: 20, height: 20, data })).with_attribute(ATTR_TRANSFORM, transform);
for effect in effects {
stamp_effect(&mut item, Effect::new(effect));
}
item
}
/// The read-back image's color at a `point` in the document, transparent past its edges.
fn color_at(image: &Item<Pixels>, point: DVec2) -> Color {
let raster = image.element();
let transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
let pixel = (transform.inverse().transform_point2(point) * DVec2::new(raster.width as f64, raster.height as f64)).floor();
let inside = pixel.cmpge(DVec2::ZERO).all() && pixel.x < raster.width as f64 && pixel.y < raster.height as f64;
if !inside {
return Color::TRANSPARENT;
}
raster.data[pixel.y as usize * raster.width as usize + pixel.x as usize]
}
fn is_black(color: Color) -> bool {
color.a() > 0.98 && color.r().max(color.g()).max(color.b()) < 0.02
}
fn is_white(color: Color) -> bool {
color.a() > 0.98 && color.r().min(color.g()).min(color.b()) > 0.98
}
fn is_clear(color: Color) -> bool {
color.a() < 0.02
}
#[test]
fn an_image_without_effects_comes_back_as_it_is() {
let Some(executor) = executor() else { return };
let image = image_of_pixels(TALL_PIXEL, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 0.25), &[]);
let read_back = block_on(executor.read_back(image.clone())).unwrap();
assert_eq!(**read_back.element(), *image.element().data());
assert_eq!(
read_back.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM),
image.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM)
);
}
/// A fill fades the pixels read back the same whether no effects or an empty list of them is stamped, and goes with the effects while the other attributes stay.
#[test]
fn a_fill_fades_the_pixels_with_or_without_effects() {
let Some(executor) = executor() else { return };
let mut without_effects = image_of_pixels(DVec2::ONE, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 1.), &[]);
without_effects.set_attribute(ATTR_OPACITY_FILL, 0.5);
without_effects.set_attribute(ATTR_OPACITY, 0.25);
without_effects.set_attribute(ATTR_BLEND_MODE, BlendMode::Multiply);
without_effects.set_attribute("unrelated", 7.);
let mut with_no_effects = without_effects.clone();
with_no_effects.set_attribute(ATTR_EFFECTS, Effects::default());
for image in [without_effects, with_no_effects] {
let read_back = block_on(executor.read_back(image.clone())).unwrap();
let faded: Vec<_> = image.element().data.iter().map(|color| color.with_alpha(0.5)).collect();
assert_eq!(read_back.element().data, faded);
assert!(read_back.attribute::<Effects>(ATTR_EFFECTS).is_none());
assert!(read_back.attribute::<f64>(ATTR_OPACITY_FILL).is_none());
assert_eq!(read_back.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.), 0.25);
assert_eq!(read_back.attribute_cloned_or_default::<BlendMode>(ATTR_BLEND_MODE), BlendMode::Multiply);
assert_eq!(read_back.attribute_cloned_or::<f64>("unrelated", 0.), 7.);
assert_eq!(
read_back.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM),
image.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM)
);
}
}
/// A Levels adjustment bending each color channel its own way, and alpha by `alpha_midtones`.
fn uneven_levels(alpha_midtones: f64) -> graphic_types::Adjustment {
use graphic_types::adjustment::{LevelsRecord, LevelsSettings};
let record = |midtones, output_maximums| LevelsRecord {
shadows: 0.,
midtones,
highlights: 100.,
output_minimums: 0.,
output_maximums,
};
graphic_types::Adjustment::Levels(Box::new(LevelsSettings {
composite: record(1.4, 100.),
red: record(0.7, 90.),
green: record(1., 100.),
blue: record(1.2, 100.),
alpha: record(alpha_midtones, 100.),
}))
}
#[test]
fn adjustments_carried_out_on_the_cpu_match_their_render() {
let Some((executor, limits)) = executor_and_limits() else { return };
// Opaque, so the render's straight alpha keeps every color
let operations = [uneven_levels(1.), graphic_types::Adjustment::Invert].map(EffectOperation::Adjustment);
let image = image_of_pixels(DVec2::ONE, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 1.), &operations);
let (effects, transform) = (image.attribute::<Effects>(ATTR_EFFECTS).unwrap().clone(), image.attribute_cloned_or_default(ATTR_TRANSFORM));
let on_the_cpu = adjusted_without_render(&image, &effects, 1.).expect("adjustments alone need no render");
let rendered = block_on(executor.render_at_pixel_grid(&image, &effects, transform, DVec2::ZERO, DVec2::ZERO, limits)).unwrap();
// The render carries out leading adjustments on the image's own pixels too, then draws them into an 8-bit texture
assert_alike(&on_the_cpu, &rendered, ADJUSTMENT_TOLERANCE);
}
#[test]
fn adjustments_alone_are_carried_out_on_the_cpu() {
use graphic_types::Adjustment;
let Some(executor) = executor() else { return };
let adjustments = [uneven_levels(2.2), Adjustment::Invert];
let operations: Vec<_> = adjustments.iter().cloned().map(EffectOperation::Adjustment).collect();
// A Levels stack bending alpha, with fine steps 8 bits can't hold
let color = |x: u32, y: u32| Color::from_rgbaf32_unchecked(x as f32 / 1000., y as f32 / 20., 0.5, (x + y) as f32 / 40.);
let image = image_of_pixels(DVec2::ONE, color, &operations);
let expected = adjusted_raster(image.element(), &adjustments);
let read_back = block_on(executor.read_back(image)).unwrap();
assert_eq!(**read_back.element(), *expected.data());
assert!(read_back.attribute::<Effects>(ATTR_EFFECTS).is_none());
// Inverting keeps alpha, so a partial fill fades the inverted colors, which stay beneath zero alpha
let color = |x: u32, y: u32| Color::from_rgbaf32_unchecked(x as f32 / 20., 0.25, 1., if y < 10 { 0. } else { 0.8 });
let mut image = image_of_pixels(DVec2::ONE, color, &[EffectOperation::Adjustment(Adjustment::Invert)]);
image.set_attribute(ATTR_OPACITY_FILL, 0.5);
let inverted = adjusted_raster(image.element(), &[Adjustment::Invert]);
let read_back = block_on(executor.read_back(image)).unwrap();
assert!(read_back.attribute::<f64>(ATTR_OPACITY_FILL).is_none());
for (index, (color, inverted)) in read_back.element().data.iter().zip(&inverted.data().data).enumerate() {
assert_eq!(*color, inverted.with_alpha(inverted.a() * 0.5), "pixel {index}");
assert!(color.r() + color.g() + color.b() > 0., "pixel {index} lost its color");
}
// Effects past adjustments need a render
let outlined = image_of_pixels(DVec2::ONE, |_, _| Color::WHITE, &[outline(2.)]);
let effects = outlined.attribute::<Effects>(ATTR_EFFECTS).unwrap();
assert!(adjusted_without_render(&outlined, effects, 1.).is_none());
}
#[test]
fn the_margin_holds_what_a_median_reads_past_the_image() {
// A median reads its whole radius and the pixel past it, across the image's pixels of one unit each
let image = image_of_pixels(DVec2::ONE, |_, _| Color::WHITE, &[EffectOperation::Median { radius: 2.5 }]);
let effects = image.attribute::<Effects>(ATTR_EFFECTS).unwrap();
assert_eq!(effects_reach(effects, DVec2::splat(20.)), DVec2::splat(3.));
}
#[test]
fn effects_measure_lengths_in_the_document_across_unevenly_scaled_pixels() {
let Some(executor) = executor() else { return };
// An outline 8 units wide spans 8 of the image's pixels across, but only 2 of them down
let outline = EffectOperation::Outline {
paint: Color::BLACK.into(),
blend_mode: BlendMode::Normal,
weight: 8.,
align: StrokeAlign::Outside,
contour_gradient: false,
};
let read_back = block_on(executor.read_back(image_of_pixels(TALL_PIXEL, |_, _| Color::WHITE, &[outline]))).unwrap();
// The content spans from (100, 50) to (120, 130)
assert!(is_white(color_at(&read_back, DVec2::new(110., 90.))), "the content");
assert!(is_black(color_at(&read_back, DVec2::new(94.5, 90.))), "within the outline, 5.5 units left of the content");
assert!(is_clear(color_at(&read_back, DVec2::new(89.5, 90.))), "past the outline, 10.5 units left of the content");
assert!(is_black(color_at(&read_back, DVec2::new(110., 44.))), "within the outline, 6 units above the content");
assert!(is_clear(color_at(&read_back, DVec2::new(110., 40.))), "past the outline, 10 units above the content");
}
#[test]
fn vector_masks_shape_the_pixels_read_back() {
let Some(executor) = executor() else { return };
// A mask lies in the content's own space, where the left half of its unit square covers the image's left half
let mut left_half = Vector::item_from_bezpath(&Rect::new(0., 0., 0.5, 1.).to_path(0.1));
left_half.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(Color::WHITE))));
let mask = EffectOperation::Mask {
mask: Graphic::Vector(Box::new(left_half)),
mode: MaskMode::Alpha,
density: 100.,
feather: 0.,
invert: false,
};
let read_back = block_on(executor.read_back(image_of_pixels(TALL_PIXEL, |_, _| Color::WHITE, &[mask]))).unwrap();
assert!(is_white(color_at(&read_back, DVec2::new(105.5, 90.))), "the left half, which the mask shows");
assert!(is_clear(color_at(&read_back, DVec2::new(114.5, 90.))), "the right half, which the mask hides");
}
/// An outline of `weight` outside the content, in black.
fn outline(weight: f64) -> EffectOperation {
EffectOperation::Outline {
paint: Color::BLACK.into(),
blend_mode: BlendMode::Normal,
weight,
align: StrokeAlign::Outside,
contour_gradient: false,
}
}
/// The limits of the shared GPU, and its executor, or `None` without a GPU.
fn executor_and_limits() -> Option<(&'static WgpuExecutor, ReadbackLimits)> {
let executor = executor()?;
Some((executor, ReadbackLimits::of(executor)))
}
/// How many 8-bit levels the CPU's adjustments and the render of them may part by, which is the render's rounding to its 8-bit texture.
const ADJUSTMENT_TOLERANCE: u8 = 1;
/// Asserts that two images have the same size and 8-bit pixels within `tolerance` levels of each other.
fn assert_alike(actual: &Image<Color>, expected: &Image<Color>, tolerance: u8) {
assert_eq!((actual.width, actual.height), (expected.width, expected.height));
for (index, (actual, expected)) in actual.data.iter().zip(&expected.data).enumerate() {
let (SRGBA8 { red, green, blue, alpha }, wanted) = (SRGBA8::from(*actual), SRGBA8::from(*expected));
let differences = [red.abs_diff(wanted.red), green.abs_diff(wanted.green), blue.abs_diff(wanted.blue), alpha.abs_diff(wanted.alpha)];
assert!(
differences.iter().all(|&difference| difference <= tolerance),
"pixel {index} is {actual:?} but {expected:?} in the other"
);
}
}
#[test]
fn tiles_small_enough_for_the_download_buffer_match_one_render() {
let Some((executor, limits)) = executor_and_limits() else { return };
// Square pixels of the document's size keep the effects' working pixels on the render's, so neither render resamples them.
// A 2048 byte buffer holds 8 rows of up to 64 pixels, each padded to 256 bytes, so this render is drawn in tiles 8 pixels tall.
let image = image_of_pixels(DVec2::ONE, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 1.), &[outline(2.)]);
let small_buffer = ReadbackLimits { buffer_size: 2048, ..limits };
assert_eq!(small_buffer.tile_size(UVec2::splat(100)), Some(UVec2::new(100, 2048 / 512)));
let whole = block_on(executor.read_back_within(image.clone(), limits)).unwrap();
let tiled = block_on(executor.read_back_within(image, small_buffer)).unwrap();
assert_alike(tiled.element(), whole.element(), 1);
}
#[test]
fn an_image_too_large_to_upload_whole_keeps_its_own_pixels_in_crops() {
let Some((executor, limits)) = executor_and_limits() else { return };
// Alternating black and white columns, inverted and outlined, which a downscaled upload would average to gray
let columns = |x: u32, _| if x.is_multiple_of(2) { Color::BLACK } else { Color::WHITE };
let image = image_of_pixels(DVec2::ONE, columns, &[EffectOperation::Adjustment(graphic_types::Adjustment::Invert), outline(2.)]);
let small_textures = ReadbackLimits { texture_size: 16, ..limits };
let whole = block_on(executor.read_back_within(image.clone(), limits)).unwrap();
let cropped = block_on(executor.read_back_within(image, small_textures)).unwrap();
assert_alike(cropped.element(), whole.element(), 1);
for x in 0..20 {
let color = color_at(&cropped, DVec2::new(100.5 + x as f64, 60.5));
let inverted = if x % 2 == 0 { is_white(color) } else { is_black(color) };
assert!(inverted, "column {x} is {color:?}");
}
}
#[test]
fn limits_too_small_for_any_tile_fail_without_panicking() {
let Some((executor, limits)) = executor_and_limits() else { return };
let image = image_of_pixels(DVec2::ONE, |_, _| Color::WHITE, &[outline(2.)]);
let tiny_buffer = ReadbackLimits { buffer_size: 100, ..limits };
assert!(block_on(executor.read_back_within(image, tiny_buffer)).is_err());
}
#[test]
fn a_reach_too_far_for_any_crop_fails_without_overflowing() {
let Some((executor, limits)) = executor_and_limits() else { return };
// A box blur reaching past 2^31 pixels, on an image too wide for the texture limit, at one document unit per pixel
let blur = EffectOperation::Blur {
radius_mask: Graphic::default(),
radius: 2_147_483_647.,
box_blur: true,
gamma: false,
};
let mut image = Item::new_from_element(Raster::new_cpu(Image::new(16_384, 64, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(16_384., 64.)));
stamp_effect(&mut image, Effect::new(&blur));
let small_textures = ReadbackLimits { texture_size: 8192, ..limits };
assert!(block_on(executor.read_back_within(image, small_textures)).is_err());
}
#[test]
fn crops_carry_out_leading_adjustments_on_transparent_pixels_as_the_whole_image_does() {
let Some((executor, limits)) = executor_and_limits() else { return };
// Make Opaque raises the alpha of fully transparent pixels, which only the image's own pixels can carry, and the outline needs a render
let make_opaque = EffectOperation::Adjustment(graphic_types::Adjustment::MakeOpaque { strength: 100. });
let image = image_of_pixels(DVec2::ONE, |_, _| Color::from_rgbaf32_unchecked(1., 0., 0., 0.), &[make_opaque, outline(2.)]);
let small_textures = ReadbackLimits { texture_size: 16, ..limits };
let whole = block_on(executor.read_back_within(image.clone(), limits)).unwrap();
let cropped = block_on(executor.read_back_within(image, small_textures)).unwrap();
assert_alike(cropped.element(), whole.element(), 1);
let pixels = (0..20).flat_map(|y| (0..20).map(move |x| DVec2::new(100.5 + x as f64, 50.5 + y as f64)));
assert!(pixels.map(|point| color_at(&cropped, point)).all(|color| color.a() > 0.99), "the transparent pixels became opaque");
}
#[test]
fn crops_hold_the_pixels_effects_reach_past_a_margin_cut_short() {
let Some((executor, limits)) = executor_and_limits() else { return };
// A margin cut to nothing, as for an image too large to grow, still leaves the blur its neighbors across the tiles.
// The tiles are wide enough next to the blur's reach that its effects group keeps their full resolution.
let blur = EffectOperation::Blur {
radius_mask: Graphic::default(),
radius: 1.,
box_blur: false,
gamma: false,
};
let mut image = Item::new_from_element(Raster::new_cpu(Image::new(64, 64, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(64.)));
stamp_effect(&mut image, Effect::new(&blur));
let (effects, transform) = (image.attribute::<Effects>(ATTR_EFFECTS).unwrap().clone(), image.attribute_cloned_or_default(ATTR_TRANSFORM));
let reach = effects_reach(&effects, DVec2::splat(64.));
assert!(reach.min_element() > 0.);
let small_textures = ReadbackLimits { texture_size: 60, ..limits };
let whole = block_on(executor.render_at_pixel_grid(&image, &effects, transform, DVec2::ZERO, reach, limits)).unwrap();
let cropped = block_on(executor.render_at_pixel_grid(&image, &effects, transform, DVec2::ZERO, reach, small_textures)).unwrap();
assert_alike(&cropped, &whole, 1);
}
}
@@ -22,23 +22,35 @@ struct RasterGpuToRasterCpuConverter {
padded_bytes_per_row: u32,
_source: raster_types::Texture,
}
/// The bytes in each row of a download buffer for an image `width` pixels wide, padded to the alignment copies need.
pub(crate) fn download_row_bytes(width: u32) -> u32 {
let bytes_per_pixel = 4; // RGBA8
(width * bytes_per_pixel).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT
}
/// The buffer a texture of `width` by `height` pixels downloads into.
fn download_buffer(executor: &WgpuExecutor, width: u32, height: u32) -> Buffer {
executor.create_buffer(&wgpu::BufferDescriptor {
label: Some("texture_download_buffer"),
size: download_row_bytes(width) as u64 * height as u64,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
})
}
impl RasterGpuToRasterCpuConverter {
fn new(executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>) -> Self {
let buffer = download_buffer(executor, data_gpu.data().width(), data_gpu.data().height());
Self::with_buffer(encoder, data_gpu, buffer)
}
/// Copies the texture into the `buffer` made for its size, once the `encoder` is submitted.
fn with_buffer(encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>, buffer: Buffer) -> Self {
let texture = data_gpu.data();
let width = texture.width();
let height = texture.height();
let bytes_per_pixel = 4; // RGBA8
let unpadded_bytes_per_row = width * bytes_per_pixel;
let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let padded_bytes_per_row = unpadded_bytes_per_row.div_ceil(align) * align;
let buffer_size = padded_bytes_per_row as u64 * height as u64;
let buffer = executor.create_buffer(&wgpu::BufferDescriptor {
label: Some("texture_download_buffer"),
size: buffer_size,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let unpadded_bytes_per_row = width * 4;
let padded_bytes_per_row = download_row_bytes(width);
encoder.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo {
@@ -73,7 +85,7 @@ impl RasterGpuToRasterCpuConverter {
}
}
async fn convert(self, device: &wgpu::Device) -> Result<Raster<CPU>, wgpu::BufferAsyncError> {
async fn convert(self, device: &wgpu::Device) -> anyhow::Result<Raster<CPU>> {
let buffer_slice = self.buffer.slice(..);
let (sender, receiver) = futures::channel::oneshot::channel();
buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
@@ -104,9 +116,12 @@ impl RasterGpuToRasterCpuConverter {
}
};
map_result.expect("Failed to receive map result")?;
let Ok(map_result) = map_result else {
anyhow::bail!("The download of a {} by {} image was canceled before the GPU mapped its buffer", self.width, self.height);
};
map_result?;
let view = buffer_slice.get_mapped_range().expect("Failed to get mapped range");
let view = buffer_slice.get_mapped_range()?;
let row_stride = self.padded_bytes_per_row as usize;
let row_bytes = self.unpadded_bytes_per_row as usize;
@@ -230,3 +245,33 @@ impl ConvertAsync<Raster<CPU>, WgpuExecutor> for Raster<GPU> {
converter.convert(device).await.expect("Failed to download texture data")
}
}
impl WgpuExecutor {
/// Downloads the GPU raster's pixels, failing rather than panicking when the GPU can't make or map the buffer they're copied into.
pub async fn try_download(&self, raster: Raster<GPU>) -> anyhow::Result<Raster<CPU>> {
let device = &self.context().device;
let (width, height) = (raster.data().width(), raster.data().height());
let buffer_size = download_row_bytes(width) as u64 * height as u64;
let limit = device.limits().max_buffer_size;
if buffer_size > limit {
anyhow::bail!("Downloading a {width} by {height} image takes a {buffer_size} byte buffer, past the GPU's limit of {limit} bytes");
}
// Popped in the reverse order they're pushed, before awaiting either, since the scopes can't be held across an await
let out_of_memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
let buffer = download_buffer(self, width, height);
let (validation, out_of_memory) = (validation.pop(), out_of_memory.pop());
if let Some(error) = validation.await.or(out_of_memory.await) {
anyhow::bail!("The GPU couldn't make the buffer to download a {width} by {height} image: {error}");
}
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("fallible_texture_download_encoder"),
});
let converter = RasterGpuToRasterCpuConverter::with_buffer(&mut encoder, raster, buffer);
self.context().queue.submit([encoder.finish()]);
converter.convert(device).await
}
}
@@ -73,6 +73,8 @@ struct RenderContext<'a> {
canvas: &'a mut VelloCanvas,
device: &'a wgpu::Device,
queue: &'a Queue,
/// The first failure that left part of the render transparent.
failure: Option<String>,
}
impl VelloRenderer {
@@ -120,7 +122,7 @@ impl VelloRenderer {
}
/// Renders the scene `draw` draws on `canvas`, with its content placed by `view`, into `target` (an `Rgba8Unorm` texture of `size` with straight alpha).
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into. Gives the first failure that left a part transparent.
#[expect(clippy::too_many_arguments)]
pub(crate) fn render(
&self,
@@ -131,7 +133,7 @@ impl VelloRenderer {
view: Affine,
size: UVec2,
target: &wgpu::Texture,
) -> anyhow::Result<()> {
) -> anyhow::Result<Option<String>> {
if u16::try_from(size.x).is_err() || u16::try_from(size.y).is_err() {
anyhow::bail!("Render size {size} exceeds Vello GPU's limit");
}
@@ -142,12 +144,14 @@ impl VelloRenderer {
canvas,
device,
queue,
failure: None,
};
context.render_area(draw, view, size, target, TargetAlpha::Straight);
let failure = context.failure;
canvas.images.free_unused();
canvas.effect_textures.finish_render();
Ok(())
Ok(failure)
}
/// Renders a `scene` drawn beforehand on `canvas` into `target` (an `Rgba8Unorm` texture of the scene's size with straight alpha).
@@ -160,6 +164,7 @@ impl VelloRenderer {
canvas,
device,
queue,
failure: None,
};
let (scene, images) = scene.finish();
if let Err(error) = context.submit(&scene, images, max_texture_size, target, TargetAlpha::Straight, true) {
@@ -192,6 +197,7 @@ impl RenderContext<'_> {
if !too_much_to_hold || split_depth > MAX_SPLIT_DEPTH || size.max_element() <= 1 {
// A failed render leaves its area transparent rather than taking down the editor
log::error!("Vello GPU failed to render: {error}");
self.failure.get_or_insert_with(|| error.to_string());
clear(device, queue, target);
return;
}
@@ -230,6 +236,7 @@ impl RenderContext<'_> {
};
if halves.iter().all(|(.., rendered)| stalled(rendered)) {
log::error!("Vello GPU failed to render: {error}");
self.failure.get_or_insert_with(|| error.to_string());
clear(device, queue, target);
return;
}
@@ -491,6 +498,7 @@ impl EffectsRenderer for RenderContext<'_> {
Ok(()) => Some(backdrop),
Err(error) => {
log::error!("Vello GPU failed to render what lies beneath content reading it: {error}");
self.failure.get_or_insert_with(|| error.to_string());
self.canvas.effect_textures.release(backdrop);
None
}
-1
View File
@@ -45,7 +45,6 @@ wgpu-executor = { workspace = true }
core-types = { workspace = true }
vector-types = { workspace = true }
graphic-types = { workspace = true }
raster-kernels = { workspace = true }
svg-convert = { workspace = true }
blending-nodes = { workspace = true }
text-nodes = { workspace = true }
+1
View File
@@ -1,6 +1,7 @@
pub mod any;
pub mod platform_application_io;
pub mod poll_debug;
pub mod read_back;
pub mod render_background;
pub mod render_cache;
pub mod render_node;
@@ -12,7 +12,7 @@ pub use graph_craft::document::value::RenderOutputType;
#[cfg(target_family = "wasm")]
pub use graphene_canvas_utils as canvas_utils;
use graphic_types::Graphic;
use graphic_types::raster_types::{CPU, Raster};
use graphic_types::raster_types::{CPU, Pixels, Raster};
use graphic_types::raster_types::{Image, ImageError};
use rendering::{Render, RenderParams};
use std::sync::Arc;
@@ -172,8 +172,8 @@ fn string_to_bytes(_: impl Ctx, string: Item<String>) -> Item<Resource> {
/// Converts extracted raw RGBA pixel data from an input image. Each pixel becomes 4 sequential bytes. Useful for transmission over HTTP or writing to files.
#[node_macro::node(category("Data: I/O"), icon("NodeImageToBytes"), name("Image to Bytes"))]
fn image_to_bytes(_: impl Ctx, image: Item<Raster<CPU>>) -> Item<Resource> {
let bytes: Vec<u8> = raster_kernels::evaluate_raster_effects(image)
fn image_to_bytes(_: impl Ctx, image: Item<Pixels>) -> Item<Resource> {
let bytes: Vec<u8> = image
.element()
.data
.iter()
+32
View File
@@ -0,0 +1,32 @@
use core_types::list::{Item, List};
use core_types::{Ctx, NodeError, ProtoNodeIdentifier};
use graphic_types::raster_types::{CPU, Pixels, Raster};
/// The input adapter the compiler places ahead of each node input taking `Pixels`, with `read_back` and `read_back_list` as its rows.
pub const INPUT_ADAPTER: ProtoNodeIdentifier = ProtoNodeIdentifier::new("input_adapter<Pixels>");
/// Reads back the pixels of an image as the GPU draws it with its effects and fill, for a node input taking `Pixels`. It stays pending until the download lands, so the reader doesn't run on stand-in pixels.
#[node_macro::node(category("_Adapters"), skip_impl)]
async fn read_back(
_: impl Ctx,
image: Item<Raster<CPU>>,
#[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: Item<wgpu_executor::WgpuExecutor>,
) -> Result<Item<Pixels>, NodeError> {
executor.element().read_back(image).await.map_err(NodeError::new)
}
/// The `List` counterpart of `read_back`, reading back each image in turn.
#[node_macro::node(category("_Adapters"), skip_impl)]
async fn read_back_list(
_: impl Ctx,
images: List<Raster<CPU>>,
#[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: Item<wgpu_executor::WgpuExecutor>,
) -> Result<List<Pixels>, NodeError> {
let executor = executor.element();
let mut read_back = List::new();
for image in images.into_iter() {
read_back.push(executor.read_back(image).await.map_err(NodeError::new)?);
}
Ok(read_back)
}
+4 -4
View File
@@ -2,15 +2,14 @@ use core_types::context::Ctx;
use core_types::list::Item;
use image::{DynamicImage, GenericImage, GenericImageView, GrayImage, ImageBuffer, Luma, Rgba, RgbaImage};
use ndarray::{Array2, ArrayBase, Dim, OwnedRepr};
use raster_kernels::evaluate_raster_effects;
use raster_types::Image;
use raster_types::{CPU, Raster};
use raster_types::{CPU, Pixels, Raster};
use std::cmp::{max, min};
#[node_macro::node(category("Raster: Filter"), icon("NodeDehaze"), memoize)]
fn dehaze(
_: impl Ctx,
image_frame: Item<Raster<CPU>>,
image_frame: Item<Pixels>,
#[unit("%")]
#[range]
#[hard(0..100)]
@@ -18,7 +17,8 @@ fn dehaze(
) -> Item<Raster<CPU>> {
let strength = *strength.element();
let (image, attributes) = evaluate_raster_effects(image_frame).into_parts();
let (pixels, attributes) = image_frame.into_parts();
let image = pixels.into_raster();
let (width, height) = (image.width, image.height);
// Prepare the image data for processing
@@ -2,8 +2,7 @@ use color::{ColorSpace, Oklab};
use core_types::color::Color;
use core_types::context::Ctx;
use core_types::list::{Item, List};
use raster_kernels::evaluate_raster_effects;
use raster_types::{CPU, Raster};
use raster_types::Pixels;
use std::collections::BinaryHeap;
use std::ops::{AddAssign, SubAssign};
@@ -19,14 +18,13 @@ const OKLAB_GAMUT_RANGES: [(f32, f32); 3] = [(0., 1.), (-0.24, 0.28), (-0.32, 0.
fn image_color_palette(
_: impl Ctx,
/// The image to find colors in.
image: Item<Raster<CPU>>,
image: Item<Pixels>,
/// How many colors to find. Raising it adds a color at the end and may adjust one existing color, leaving the rest as they were.
#[default(4)]
#[hard(1..)]
count: Item<i64>,
) -> List<Color> {
let count = *count.element() as usize;
let image = evaluate_raster_effects(image);
// O(n) binning of the image's n pixels into an OkLab histogram, weighted by alpha so transparent pixels are ignored
let mut cumulative = vec![Moments::default(); TABLE_SIDE.pow(3)];
@@ -227,7 +225,7 @@ fn table_index(position: [usize; 3]) -> usize {
#[cfg(test)]
mod test {
use super::*;
use raster_types::Image;
use raster_types::{Image, Raster};
fn palette(runs: &[(Color, usize)], count: i64) -> Vec<Color> {
let data = runs.iter().flat_map(|&(color, length)| std::iter::repeat_n(color, length)).collect::<Vec<_>>();
@@ -237,7 +235,7 @@ mod test {
data,
});
let palette = image_color_palette((), Item::new_from_element(image), Item::new_from_element(count));
let palette = image_color_palette((), Item::new_from_element(Pixels::new(image)), Item::new_from_element(count));
palette.iter_element_values().copied().collect()
}
-1
View File
@@ -19,7 +19,6 @@ workspace = true
core-types = { workspace = true }
vector-types = { workspace = true }
raster-types = { workspace = true }
raster-kernels = { workspace = true }
graphic-types = { workspace = true }
graphene-hash = { workspace = true }
node-macro = { workspace = true }
+11 -14
View File
@@ -9,8 +9,7 @@ use core_types::runtime::Runtime;
use core_types::{ATTR_TRANSFORM, CacheHash, Ctx, Poll, RuntimeHandle, SourceId};
use glam::{DAffine2, DVec2};
use graphic_types::Graphic;
use raster_kernels::evaluate_raster_effects;
use raster_types::{CPU, Raster};
use raster_types::Pixels;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::time::Duration;
@@ -42,7 +41,7 @@ const BROWSER_MAX_MEGABYTES: f64 = 1000.;
fn vectorize(
_: impl Ctx,
/// The image to trace.
image: Item<Raster<CPU>>,
image: Item<Pixels>,
/// How much detail to keep, as a multiple of the default level read from how busy the image is. Higher values spend more segments on smaller features.
#[default(1.)]
#[hard(0.01..)]
@@ -107,7 +106,7 @@ fn vectorize(
}
/// Runs one slice of the trace held in `slot`, starting a new trace if `slot` holds none for these inputs.
fn trace_slice(image: &Item<Raster<CPU>>, detail: f64, tolerance: f64, stages: ollev::Stages, max_pixels: Option<usize>, slot: &TraceSlot, slice: Duration) -> Poll<List<Graphic>> {
fn trace_slice(image: &Item<Pixels>, detail: f64, tolerance: f64, stages: ollev::Stages, max_pixels: Option<usize>, slot: &TraceSlot, slice: Duration) -> Poll<List<Graphic>> {
if image.element().width == 0 || image.element().height == 0 {
slot.clear();
return Poll::Final(List::new());
@@ -118,9 +117,7 @@ fn trace_slice(image: &Item<Raster<CPU>>, detail: f64, tolerance: f64, stages: o
(detail.to_bits(), tolerance.to_bits(), max_pixels).hash(&mut hasher);
[stages.translucency, stages.strokes, stages.primitives, stages.effects, stages.instancing, stages.path_gradients].hash(&mut hasher);
// The image's effects are carried out once for the whole trace, rather than on each slice
let start = || {
let image = evaluate_raster_effects(image.clone());
let raster = image.element();
let (width, height) = (raster.width as usize, raster.height as usize);
let image_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
@@ -154,23 +151,23 @@ mod test {
use super::*;
use core_types::Color;
use core_types::runtime::{AsyncRuntime, Spawn, Task};
use raster_types::Image;
use raster_types::{Image, Raster};
use std::sync::{Arc, Mutex};
use std::task::{Context, Waker};
/// An image of `width` by `height` pixels colored by `color` at each pixel's column and row.
fn raster(width: u32, height: u32, color: impl Fn(u32, u32) -> Color) -> Item<Raster<CPU>> {
fn raster(width: u32, height: u32, color: impl Fn(u32, u32) -> Color) -> Item<Pixels> {
let data = (0..width * height).map(|index| color(index % width, index / width)).collect();
Item::new_from_element(Raster::new_cpu(Image { width, height, data }))
Item::new_from_element(Pixels::new(Raster::new_cpu(Image { width, height, data })))
}
/// One slice of `image` traced at default settings by the node holding `slot`.
fn slice(image: &Item<Raster<CPU>>, slot: &TraceSlot) -> Poll<List<Graphic>> {
fn slice(image: &Item<Pixels>, slot: &TraceSlot) -> Poll<List<Graphic>> {
trace_slice(image, 1., 1., ollev::Stages::ALL, None, slot, SLICE)
}
/// The shapes traced from `image` at `detail` and `tolerance` by a node of its own, slice by slice.
fn trace(image: &Item<Raster<CPU>>, detail: f64, tolerance: f64) -> List<Graphic> {
fn trace(image: &Item<Pixels>, detail: f64, tolerance: f64) -> List<Graphic> {
let slot = TraceSlot::default();
loop {
match trace_slice(image, detail, tolerance, ollev::Stages::ALL, None, &slot, SLICE) {
@@ -184,7 +181,7 @@ mod test {
const DARK: Color = Color::from_rgbaf32_unchecked(0.05, 0.1, 0.4, 1.);
/// A dark ring from `inner` to `inner + width` pixels out from the middle of a light square of `size` pixels.
fn ring(size: u32, inner: f64, width: f64) -> Item<Raster<CPU>> {
fn ring(size: u32, inner: f64, width: f64) -> Item<Pixels> {
let center = size as f64 / 2.;
raster(size, size, |x, y| {
let distance = DVec2::new(x as f64 + 0.5, y as f64 + 0.5).distance(DVec2::splat(center));
@@ -228,7 +225,7 @@ mod test {
}
/// Shapes partly over one another: rings, a disc and a ramp, enough to keep a trace busy for many short slices.
fn busy(size: u32) -> Item<Raster<CPU>> {
fn busy(size: u32) -> Item<Pixels> {
let center = DVec2::splat(size as f64 / 2.);
raster(size, size, |x, y| {
let point = DVec2::new(x as f64 + 0.5, y as f64 + 0.5);
@@ -351,7 +348,7 @@ mod test {
const SOURCE: SourceId = SourceId(7);
/// One evaluation of the node holding `slot` on `image`, with every stage on.
fn evaluate(slot: &TraceSlot, image: &Item<Raster<CPU>>, runtime: &AsyncRuntime) -> Poll<List<Graphic>> {
fn evaluate(slot: &TraceSlot, image: &Item<Pixels>, runtime: &AsyncRuntime) -> Poll<List<Graphic>> {
let one = || Item::new_from_element(1.);
let on = || Item::new_from_element(true);
vectorize(
+2
View File
@@ -31,3 +31,5 @@ futures = { workspace = true }
glam = { workspace = true }
node-macro = { workspace = true }
document-loader = { workspace = true }
graphic-types = { workspace = true }
wgpu-executor = { workspace = true }
+21 -2
View File
@@ -1,6 +1,8 @@
#[macro_use]
extern crate log;
#[cfg(test)]
mod readback_tests;
mod value_types;
use graph_craft::Type;
@@ -195,7 +197,18 @@ impl Preprocessor {
// We pre initialize the node registry here to avoid a deadlock
let into_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
let node_registry = core_types::registry::NODE_REGISTRY.lock().unwrap();
for (id, metadata) in core_types::registry::NODE_METADATA.lock().unwrap().iter() {
let node_metadata = core_types::registry::NODE_METADATA.lock().unwrap();
// The read-back adapter is async, so it takes the executor, runtime, and source ID after the wire
let read_back_environment: Vec<NodeInput> = match node_metadata.get(&read_back::read_back::IDENTIFIER) {
Some(metadata) => node_inputs(&metadata.fields, const { &NodeIOTypes::empty() }).into_iter().skip(1).collect(),
None => {
error!("The read-back adapter's node has no metadata, so it can't be given its executor, runtime, and source ID");
Vec::new()
}
};
for (id, metadata) in node_metadata.iter() {
let id = id.clone();
let NodeMetadata {
@@ -254,8 +267,14 @@ impl Preprocessor {
generated_nodes += 1;
let mut original_location = OriginalLocation::default();
original_location.auto_convert_index = Some(i);
let mut adapter_inputs = vec![NodeInput::import(generic!(X), i)];
if input_adapter_identifier == read_back::INPUT_ADAPTER {
adapter_inputs.extend(read_back_environment.iter().cloned());
}
let document_node = DocumentNode {
inputs: vec![NodeInput::import(generic!(X), i)],
inputs: adapter_inputs,
implementation: DocumentNodeImplementation::ProtoNode(input_adapter_identifier),
visible: true,
compile_metadata: forwarding,
@@ -0,0 +1,588 @@
//! Node inputs taking `Pixels`, which the compiler reads back from the images wired into them.
use super::*;
use core_types::blending::BlendMode;
use core_types::list::{Item, List};
use core_types::runtime::{AsyncRuntime, Spawn, Task};
use core_types::{ATTR_TRANSFORM, Color, Ctx, ExtractIndex, OwnedContextImpl, Poll};
use glam::{DAffine2, DVec2};
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::graphene_compiler::Compiler;
use graphene_std::platform_application_io::Resource;
use graphene_std::raster::{CPU, Image, Pixels, Raster};
use graphene_std::vector::style::StrokeAlign;
use graphic_types::{Adjustment, Effect, EffectOperation, Graphic, stamp_effect};
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
use interpreted_executor::util::wrap_network_in_scope;
use std::sync::{Arc, Mutex};
/// A 2 by 2 black image, inverted by an effect if `inverted`, which reads back as white.
fn black_image(inverted: bool) -> Item<Raster<CPU>> {
let mut image = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::BLACK))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(2.)));
if inverted {
stamp_effect(&mut image, Effect::new(&EffectOperation::Adjustment(Adjustment::Invert)));
}
image
}
/// A black image and one inverted to white by its effect, as a list, like the output of Rasterize.
#[node_macro::node(category(""))]
fn black_and_inverted_images(_: impl Ctx, _primary: ()) -> List<Raster<CPU>> {
[black_image(false), black_image(true)].into_iter().collect()
}
/// A black image inverted to white by its effect.
#[node_macro::node(category(""))]
fn inverted_image(_: impl Ctx, _primary: ()) -> Item<Raster<CPU>> {
black_image(true)
}
/// A 4 by 4 image lighter for a higher index in its context, outlined so it reads back through a render. It lands a task after it's asked for, as a load in the browser does.
#[node_macro::node(category(""))]
async fn indexed_image(ctx: impl Ctx + ExtractIndex, _primary: ()) -> Item<Raster<CPU>> {
YieldOnce(false).await;
let index = ctx.try_index().and_then(|mut indices| indices.next()).unwrap_or_default();
let gray = index as f32 / 4.;
let color = Color::from_rgbaf32_unchecked(gray, gray, gray, 1.);
let mut image = Item::new_from_element(Raster::new_cpu(Image::new(4, 4, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(4.)));
stamp_effect(&mut image, Effect::new(&outline()));
image
}
/// A black outline a unit wide outside the content, which only a render carries out.
fn outline() -> EffectOperation {
EffectOperation::Outline {
paint: Graphic::from(Color::BLACK),
blend_mode: BlendMode::Normal,
weight: 1.,
align: StrokeAlign::Outside,
contour_gradient: false,
}
}
/// The pixels read back from the image wired into it, as a reader for these tests.
#[node_macro::node(category(""))]
fn read_pixels(_: impl Ctx, pixels: Item<Pixels>) -> Item<Raster<CPU>> {
let (pixels, attributes) = pixels.into_parts();
Item::from_parts(pixels.into_raster(), attributes)
}
/// The size of each image `recorded_pixels` was given, which only one test reads.
static RECORDED_SIZES: Mutex<Vec<(u32, u32)>> = Mutex::new(Vec::new());
/// The pixels read back from the image wired into it, as a reader recording the size of each image it's given.
#[node_macro::node(category(""))]
fn recorded_pixels(_: impl Ctx, pixels: Item<Pixels>) -> Item<Raster<CPU>> {
RECORDED_SIZES.lock().unwrap().push((pixels.element().width, pixels.element().height));
let (pixels, attributes) = pixels.into_parts();
Item::from_parts(pixels.into_raster(), attributes)
}
/// The image it's given, passed on as another node of a second output.
#[node_macro::node(category(""))]
fn same_image(_: impl Ctx, image: Item<Raster<CPU>>) -> Item<Raster<CPU>> {
image
}
/// Pending when first polled, as a download in the browser is until a later task of its event loop.
struct YieldOnce(bool);
impl std::future::Future for YieldOnce {
type Output = ();
fn poll(mut self: std::pin::Pin<&mut Self>, context: &mut std::task::Context<'_>) -> std::task::Poll<()> {
if self.0 {
return std::task::Poll::Ready(());
}
self.0 = true;
context.waker().wake_by_ref();
std::task::Poll::Pending
}
}
/// Holds each spawned task until the test runs it, as the browser runs it after the evaluation that spawned it.
#[derive(Default)]
struct QueuedSpawner(Mutex<Vec<Task>>);
impl Spawn for QueuedSpawner {
fn spawn(&self, task: Task) {
self.0.lock().unwrap().push(task);
}
}
impl QueuedSpawner {
/// Runs each queued task to its end, giving how many there were.
fn run_queued(&self) -> usize {
let tasks = std::mem::take(&mut *self.0.lock().unwrap());
let count = tasks.len();
tasks.into_iter().for_each(futures::executor::block_on);
count
}
fn queued(&self) -> usize {
self.0.lock().unwrap().len()
}
}
/// A network compiled with the editor API in scope, and the runtime its async nodes spawn their tasks on.
struct Compiled {
dynamic_executor: DynamicExecutor,
output: OutputHandle,
runtime: AsyncRuntime,
spawner: Arc<QueuedSpawner>,
editor_api: Arc<PlatformEditorApi>,
}
impl Compiled {
/// The `network` preprocessed and compiled with a GPU in scope, or `None` without a GPU.
fn new(network: NodeNetwork) -> Option<Self> {
let gpu = futures::executor::block_on(wgpu_executor::WgpuExecutor::new())?;
let application_io = PlatformApplicationIo::new_with_executor(gpu);
Some(Self::with_application_io(network, application_io))
}
/// The `network` preprocessed and compiled with the `application_io` in scope.
fn with_application_io(network: NodeNetwork, application_io: PlatformApplicationIo) -> Self {
let spawner = Arc::new(QueuedSpawner::default());
let mut compiled = Self {
dynamic_executor: DynamicExecutor::default(),
output: OutputHandle::default(),
runtime: AsyncRuntime::new(spawner.clone()),
spawner,
editor_api: Arc::new(PlatformEditorApi {
application_io: Some(Arc::new(application_io)),
}),
};
compiled.output = compiled.compile(network);
compiled
}
/// The output of the `network`, compiled beside those before it and sharing the nodes they have in common.
fn compile(&mut self, network: NodeNetwork) -> OutputHandle {
let mut network = wrap_network_in_scope(network, self.editor_api.clone(), self.runtime.handle());
Preprocessor::new().preprocess(&mut network, &|_| None).expect("preprocessing should succeed");
let proto_network = Compiler {}.compile_single(network).expect("the network should compile").network;
let (output, _) = self.dynamic_executor.update(proto_network).expect("the network should type check and build");
self.runtime.update_sources(self.dynamic_executor.sources());
output
}
/// One evaluation of the `output` with the `index` in its context if given, reading the generations the landed tasks bumped, as the editor's evaluations do.
fn evaluate_once(&self, output: &OutputHandle, index: Option<usize>) -> Poll<core_types::registry::Any> {
let mut context = OwnedContextImpl::empty().with_generations(self.runtime.snapshot());
if let Some(index) = index {
context = context.with_index(index);
}
self.dynamic_executor.tree().evaluate(output.node(), &context.into_context()).expect("the output should evaluate")
}
/// The output evaluated until it's final, with the `index` in its context if given, running the tasks each evaluation spawns before the next.
/// Gives how many evaluations that took.
fn evaluate(&self, index: Option<usize>) -> (core_types::registry::Any, usize) {
for evaluations in 1..=1000 {
match self.evaluate_once(&self.output, index) {
Poll::Final(value) => return (value, evaluations),
Poll::Pending | Poll::Partial(_) => {
self.spawner.run_queued();
}
Poll::Error(error) => panic!("the output failed: {error}"),
Poll::Fallback(boxed) => panic!("the output failed: {}", boxed.1),
}
}
panic!("the output never became final")
}
}
fn proto_node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
DocumentNode {
inputs,
implementation: DocumentNodeImplementation::ProtoNode(identifier),
..Default::default()
}
}
/// A network of the `node` fed by the `source` node, exporting the node's output `output_index`.
fn network(source: ProtoNodeIdentifier, node: DocumentNode, output_index: usize) -> NodeNetwork {
NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), output_index)],
nodes: [(NodeId(0), proto_node(source, vec![NodeInput::value(TaggedValue::None, false)])), (NodeId(1), node)]
.into_iter()
.collect(),
..Default::default()
}
}
/// The node's inputs as a new one of it gets them.
fn default_inputs(identifier: &ProtoNodeIdentifier) -> Vec<NodeInput> {
let node_registry = core_types::registry::NODE_REGISTRY.lock().unwrap();
let metadata_registry = core_types::registry::NODE_METADATA.lock().unwrap();
let first_node_io = node_registry.get(identifier).and_then(|implementations| implementations.first()).map(|(_, node_io)| node_io);
let metadata = metadata_registry.get(identifier).expect("the node should have registered metadata");
node_inputs(&metadata.fields, first_node_io.unwrap_or(const { &NodeIOTypes::empty() }))
}
fn wire() -> NodeInput {
NodeInput::node(NodeId(0), 0)
}
/// The first pixel of each image, as the gamma-encoded red channel and alpha.
fn first_pixels(images: &List<Raster<CPU>>) -> Vec<(f32, f32)> {
images.iter_element_values().map(|image| (image.data[0].r(), image.data[0].a())).collect()
}
#[test]
fn the_read_back_adapter_takes_the_inputs_of_an_async_node() {
let reader = proto_node(read_pixels::IDENTIFIER, vec![NodeInput::value(TaggedValue::None, false)]);
let mut network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(0), 0)],
nodes: [(NodeId(0), reader)].into_iter().collect(),
..Default::default()
};
let runtime = AsyncRuntime::new(Arc::new(QueuedSpawner::default()));
network = wrap_network_in_scope(network, Arc::default(), runtime.handle());
Preprocessor::new().preprocess(&mut network, &|_| None).expect("preprocessing should succeed");
let adapters: Vec<_> = (network.definitions.values().flat_map(|definition| definition.nodes.values()))
.filter(|node| node.implementation == DocumentNodeImplementation::ProtoNode(graphene_std::read_back::INPUT_ADAPTER))
.collect();
let [adapter] = adapters.as_slice() else {
panic!("the reader's input should have one read-back adapter, but has {}", adapters.len())
};
let environment = [
NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER),
NodeInput::scope("runtime"),
NodeInput::Reflection(DocumentNodeMetadata::SourceId),
];
assert_eq!(adapter.inputs[1..], environment, "the adapter takes the executor, runtime, and source ID after the wire");
}
#[test]
fn an_item_wire_reads_back_the_image_with_its_effects() {
let Some(compiled) = Compiled::new(network(inverted_image::IDENTIFIER, proto_node(read_pixels::IDENTIFIER, vec![wire()]), 0)) else {
return;
};
let (output, _) = compiled.evaluate(None);
let image = output.downcast::<Item<Raster<CPU>>>().expect("the reader should output an image");
assert!(image.element().data.iter().all(|color| *color == Color::WHITE), "the black image reads back inverted to white");
}
#[test]
fn a_list_wire_reads_back_each_image() {
let Some(compiled) = Compiled::new(network(black_and_inverted_images::IDENTIFIER, proto_node(read_pixels::IDENTIFIER, vec![wire()]), 0)) else {
return;
};
let (output, _) = compiled.evaluate(None);
let images = output.downcast::<List<Raster<CPU>>>().expect("the reader should output a list of images");
assert_eq!(first_pixels(&images), [(0., 1.), (1., 1.)]);
}
#[test]
fn an_unwired_input_reads_back_no_pixels() {
let inputs = default_inputs(&read_pixels::IDENTIFIER);
assert_eq!(
inputs[0].as_value(),
Some(&TaggedValue::TypeDefault(core_types::item!(Raster<CPU>))),
"an unwired input holds the empty image"
);
let reader = NodeNetwork {
exports: vec![NodeInput::node(NodeId(0), 0)],
nodes: [(NodeId(0), proto_node(read_pixels::IDENTIFIER, inputs))].into_iter().collect(),
..Default::default()
};
let Some(compiled) = Compiled::new(reader) else { return };
let (output, _) = compiled.evaluate(None);
let image = output.downcast::<Item<Raster<CPU>>>().expect("the reader should output an image");
assert!(image.element().data.is_empty());
}
/// Evaluated under a series of contexts as a Repeat node does, the read-back adapter keeps a result for each, so evaluating them again neither waits nor reads back again.
#[test]
fn the_read_back_finishes_under_each_context_in_turn_and_keeps_its_result() {
let Some(compiled) = Compiled::new(network(indexed_image::IDENTIFIER, proto_node(read_pixels::IDENTIFIER, vec![wire()]), 0)) else {
return;
};
let read_back = |index: usize| {
let (output, evaluations) = compiled.evaluate(Some(index));
let image = output.downcast::<Item<Raster<CPU>>>().expect("the reader should output an image");
let raster = image.element();
let middle = raster.data[(raster.height / 2 * raster.width + raster.width / 2) as usize];
(raster.buffer_id(), middle.r(), evaluations)
};
// The source's task lands one evaluation later, and the readback with it
let first: Vec<_> = (0..3).map(read_back).collect();
for (index, &(_, _, evaluations)) in first.iter().enumerate() {
assert_eq!(evaluations, 2, "index {index} should become final once its source lands");
}
assert!(first[0].1 < first[1].1 && first[1].1 < first[2].1, "each index reads back its own image: {first:?}");
// Each landing bumps the source's generation, which the readback's context holds, so this pass may read back again, but each is final at once
let settled: Vec<_> = (0..3).map(read_back).collect();
assert!(
settled.iter().all(|&(_, _, evaluations)| evaluations == 1),
"a landed source keeps each index final at once: {settled:?}"
);
assert_eq!(compiled.spawner.run_queued(), 0, "nothing waits on a task");
// Once nothing lands, each context's read-back pixels are the ones kept for it, in any order
for index in [2, 0, 1] {
let (buffer_id, middle, evaluations) = read_back(index);
assert_eq!(evaluations, 1);
assert_eq!((buffer_id, middle), (settled[index].0, settled[index].1), "index {index} read back again");
}
assert_eq!(compiled.spawner.run_queued(), 0, "nothing waits on a task");
}
/// Readbacks waiting under three contexts at once, asked for by two outputs held together, all finish once what they wait on lands, sharing their pixels between the outputs.
/// A native download lands when it's asked for, so what's held pending is the image each readback waits on, as a download in the browser would be.
#[test]
fn readbacks_pending_under_several_contexts_for_two_outputs_finish_together() {
let Some(mut compiled) = Compiled::new(network(indexed_image::IDENTIFIER, proto_node(recorded_pixels::IDENTIFIER, vec![wire()]), 0)) else {
return;
};
let first_output = compiled.output.clone();
// The second output passes the reader's pixels through one more node, sharing the reader and its readback with the first
let mut second_network = network(indexed_image::IDENTIFIER, proto_node(recorded_pixels::IDENTIFIER, vec![wire()]), 0);
second_network.nodes.insert(NodeId(2), proto_node(same_image::IDENTIFIER, vec![NodeInput::node(NodeId(1), 0)]));
second_network.exports = vec![NodeInput::node(NodeId(2), 0)];
let second_output = compiled.compile(second_network);
// Each context waits on its image's task, which stays queued, and asking again starts nothing new
let asked_for = [(&first_output, 0), (&second_output, 1), (&first_output, 2)];
for _ in 0..2 {
for (output, index) in asked_for {
assert!(matches!(compiled.evaluate_once(output, Some(index)), Poll::Pending), "index {index} should wait on its image");
}
}
assert_eq!(compiled.spawner.queued(), 3, "one task for each context");
assert!(RECORDED_SIZES.lock().unwrap().is_empty(), "the reader ran while its pixels were unfinished");
// Once the images land, both outputs get each context's read-back pixels at once, the same ones
assert_eq!(compiled.spawner.run_queued(), 3);
let buffer_ids = |output: &OutputHandle| -> Vec<u64> {
(0..3)
.map(|index| match compiled.evaluate_once(output, Some(index)) {
Poll::Final(value) => value.downcast::<Item<Raster<CPU>>>().expect("the reader should output an image").element().buffer_id(),
_ => panic!("index {index} should be final once its image landed"),
})
.collect()
};
let first = buffer_ids(&first_output);
assert_eq!(buffer_ids(&second_output), first, "both outputs share each context's pixels");
assert_eq!(buffer_ids(&first_output), first, "evaluating again reuses each context's pixels");
assert_eq!(compiled.spawner.queued(), 0, "nothing was read back again");
// The reader only ever ran on read-back pixels, grown past the 4 by 4 image by its outline
assert!(RECORDED_SIZES.lock().unwrap().iter().all(|&size| size == (8, 8)), "{:?}", RECORDED_SIZES.lock().unwrap());
}
/// Without a GPU, a reader's input is an error.
#[test]
fn a_reader_without_a_gpu_fails() {
let compiled = Compiled::with_application_io(
network(inverted_image::IDENTIFIER, proto_node(read_pixels::IDENTIFIER, vec![wire()]), 0),
PlatformApplicationIo::default(),
);
let Poll::Error(error) = compiled.evaluate_once(&compiled.output, None) else {
panic!("the reader should fail without a GPU")
};
assert!(error.error().is::<wgpu_executor::NoGpuError>(), "the reader failed with {error}");
}
/// An image of 32 by 32 pixels with a dark disc and a red band on a light ground, enough for every reader to find shapes and colors in, inverted by an effect if `inverted`.
fn varied_image(inverted: bool) -> Item<Raster<CPU>> {
let data = (0..32 * 32)
.map(|index| {
let (x, y) = ((index % 32) as f64, (index / 32) as f64);
if DVec2::new(x - 12., y - 12.).length() < 8. {
Color::from_rgbaf32_unchecked(0.05, 0.1, 0.3, 1.)
} else if y >= 24. {
Color::from_rgbaf32_unchecked(0.8, 0.1, 0.1, 1.)
} else {
Color::from_rgbaf32_unchecked(0.9, 0.85, 0.7, 1.)
}
})
.collect();
let mut image = Item::new_from_element(Raster::new_cpu(Image { width: 32, height: 32, data })).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(32.)));
if inverted {
stamp_effect(&mut image, Effect::new(&EffectOperation::Adjustment(Adjustment::Invert)));
}
image
}
/// The varied image as it is.
#[node_macro::node(category(""))]
fn plain_varied_image(_: impl Ctx, _primary: ()) -> Item<Raster<CPU>> {
varied_image(false)
}
/// The varied image inverted by its effect.
#[node_macro::node(category(""))]
fn inverted_varied_image(_: impl Ctx, _primary: ()) -> Item<Raster<CPU>> {
varied_image(true)
}
/// Whether two outputs of a reader are equal, as tagged values where they convert or else as one of the types the readers output.
/// `None` for outputs of a type this can't compare.
fn outputs_equal(a: &core_types::registry::Any, b: &core_types::registry::Any) -> Option<bool> {
if let (Ok(a), Ok(b)) = (TaggedValue::try_from_std_any_ref(&**a), TaggedValue::try_from_std_any_ref(&**b)) {
return Some(a == b);
}
macro_rules! compare_as {
($($ty:ty),*) => {$(
if let (Some(a), Some(b)) = (a.downcast_ref::<$ty>(), b.downcast_ref::<$ty>()) {
return Some(a == b);
}
)*};
}
compare_as!(Item<Raster<CPU>>, List<Raster<CPU>>, List<Color>, List<Graphic>);
// Resources compare by their bytes
if let (Some(a), Some(b)) = (a.downcast_ref::<Item<Resource>>(), b.downcast_ref::<Item<Resource>>()) {
return Some(a.element().as_ref() == b.element().as_ref());
}
None
}
/// Every node input taking `Pixels`, by its node's identifier and its index, besides this module's own readers.
fn pixel_reading_inputs() -> Vec<(ProtoNodeIdentifier, usize)> {
let node_registry = core_types::registry::NODE_REGISTRY.lock().unwrap();
let metadata_registry = core_types::registry::NODE_METADATA.lock().unwrap();
let takes_pixels = |ty: &Type| matches!(ty.clone().normalize_rank().nested_type(), Type::Item(element) | Type::List(element) if **element == concrete!(Pixels));
let mut inputs: Vec<_> = (node_registry.iter())
.filter(|(identifier, _)| metadata_registry.contains_key(*identifier) && ![read_pixels::IDENTIFIER, recorded_pixels::IDENTIFIER].contains(*identifier))
.flat_map(|(identifier, implementations)| {
let indices: HashSet<usize> = (implementations.iter())
.flat_map(|(_, node_io)| node_io.inputs.iter().enumerate().filter(|(_, ty)| takes_pixels(ty)).map(|(index, _)| index))
.collect();
indices.into_iter().map(|index| (identifier.clone(), index))
})
.collect();
inputs.sort_by(|a, b| (a.0.as_str(), a.1).cmp(&(b.0.as_str(), b.1)));
inputs
}
/// Every node input taking `Pixels` reads the pixels as drawn, so an image under an effect gives a different output than the image alone.
/// A node gaining such an input has to be added to the list below on purpose.
#[test]
fn every_pixel_reading_input_reads_the_image_with_its_effects() {
let inputs = pixel_reading_inputs();
let identifiers: Vec<&str> = inputs.iter().map(|(identifier, _)| identifier.as_str()).collect();
let mut readers = [
graphene_std::platform_application_io::image_to_bytes::IDENTIFIER,
graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER,
graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER,
graphene_std::vectorize_nodes::vectorize::IDENTIFIER,
];
readers.sort_by(|a, b| a.as_str().cmp(b.as_str()));
assert_eq!(identifiers, readers.iter().map(ProtoNodeIdentifier::as_str).collect::<Vec<_>>(), "the nodes reading pixels");
for (identifier, index) in inputs {
let mut node_inputs = default_inputs(&identifier);
node_inputs[index] = wire();
let output = |source: ProtoNodeIdentifier| {
let compiled = Compiled::new(network(source, proto_node(identifier.clone(), node_inputs.clone()), 0))?;
Some(compiled.evaluate(None).0)
};
let (Some(plain), Some(inverted)) = (output(plain_varied_image::IDENTIFIER), output(inverted_varied_image::IDENTIFIER)) else {
return;
};
let equal = outputs_equal(&plain, &inverted).unwrap_or_else(|| panic!("{} gives an output this test can't compare", identifier.as_str()));
assert!(!equal, "{} gives the same output for an image whether or not it's inverted by an effect", identifier.as_str());
}
}
/// A 96 by 96 image of gray noise, outlined so it reads back through a render, which Vectorize traces over several evaluations.
#[node_macro::node(category(""))]
fn outlined_noise(_: impl Ctx, _primary: ()) -> Item<Raster<CPU>> {
// Pseudo-random grays from an xorshift sequence, so the trace finds many small regions
let mut state = 0x2545_f491_u32;
let data = (0..96 * 96)
.map(|_| {
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
let gray = (state % 256) as f32 / 255.;
Color::from_rgbaf32_unchecked(gray, gray, gray, 1.)
})
.collect();
let mut image = Item::new_from_element(Raster::new_cpu(Image { width: 96, height: 96, data })).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(96.)));
stamp_effect(&mut image, Effect::new(&outline()));
image
}
/// Each slice of a trace bumps the generation of Vectorize's source, which mustn't read the image back again and so restart the trace.
#[test]
fn a_trace_of_read_back_pixels_runs_to_its_end() {
let mut inputs = default_inputs(&graphene_std::vectorize_nodes::vectorize::IDENTIFIER);
inputs[0] = wire();
let Some(compiled) = Compiled::new(network(outlined_noise::IDENTIFIER, proto_node(graphene_std::vectorize_nodes::vectorize::IDENTIFIER, inputs), 0)) else {
return;
};
let (output, evaluations) = compiled.evaluate(None);
let traced = output.downcast::<List<Graphic>>().expect("Vectorize should output graphics");
assert!(evaluations > 1, "the trace should take several slices");
assert!(!traced.is_empty());
}
/// The node `identifier` with these `inputs`, its input fed a list of a black image and one inverted to white by an effect, giving its output.
fn evaluate_on_two_images<T: 'static>(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> Option<T> {
let compiled = Compiled::new(network(black_and_inverted_images::IDENTIFIER, proto_node(identifier.clone(), inputs), 0))?;
let (output, _) = compiled.evaluate(None);
Some(*output.downcast::<T>().unwrap_or_else(|_| panic!("{} should output a list of each image's result", identifier.as_str())))
}
#[test]
fn dehaze_reads_back_each_image_of_a_list() {
let inputs = vec![wire(), NodeInput::value(TaggedValue::Number(0.), false)];
let Some(images) = evaluate_on_two_images::<List<Raster<CPU>>>(graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER, inputs) else {
return;
};
let sizes: Vec<_> = images.iter_element_values().map(|image| (image.width, image.height)).collect();
assert_eq!(sizes, [(2, 2), (2, 2)]);
// Without any strength, the haze removal keeps each image's own read-back colors
let colors: Vec<_> = images
.iter_element_values()
.flat_map(|image| image.data.iter().map(|color| (color.r().round(), color.a().round())))
.collect();
assert_eq!(colors, [[(0., 1.); 4], [(1., 1.); 4]].concat(), "the black image stays black and the inverted one white");
}
#[test]
fn image_color_palette_finds_each_image_of_a_list_its_own_colors() {
let inputs = vec![wire(), NodeInput::value(TaggedValue::Integer(1), false)];
let Some(colors) = evaluate_on_two_images::<List<Color>>(graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER, inputs) else {
return;
};
let colors: Vec<_> = colors.iter_element_values().map(|color| (color.r().round(), color.a())).collect();
assert_eq!(colors, [(0., 1.), (1., 1.)], "one color for each image, in order");
}
#[test]
fn image_to_bytes_reads_back_each_image_of_a_list() {
let Some(resources) = evaluate_on_two_images::<List<Resource>>(graphene_std::platform_application_io::image_to_bytes::IDENTIFIER, vec![wire()]) else {
return;
};
let bytes: Vec<Vec<u8>> = resources.iter_element_values().map(|resource| resource.as_ref().to_vec()).collect();
assert_eq!(bytes, [[0, 0, 0, 255].repeat(4), [255, 255, 255, 255].repeat(4)]);
}