Give GPU rasters an empty default

This commit is contained in:
Dennis Kobert authored and Keavon Chambers committed 2026-11-05 13:30:19 -08:00
1 parent 73aeeee4d6
commit 49ecb3e695
10 files changed
+122 -69

No files matched your search

@@ -18,7 +18,7 @@ use graphene_std::raster::{
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
SelectiveColorChoice, TonalRange,
};
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::raster_types::{CPU, GPU, Raster, Storage};
use graphene_std::text::TextAlign;
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
@@ -944,9 +944,15 @@ impl TableItemLayout for Raster<GPU> {
"Raster"
}
fn identifier(&self) -> String {
format!("Raster ({} x {})", self.data().width(), self.data().height())
let size = self.size();
format!("Raster ({} x {})", size.x, size.y)
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
if self.is_empty() {
let widgets = vec![TextLabel::new("Image has no area").widget_instance()];
return vec![LayoutGroup::row(widgets)];
}
let widgets = vec![TextLabel::new("This raster data is a texture on the GPU. It currently cannot be displayed here.").widget_instance()];
vec![LayoutGroup::row(widgets)]
}
+3 -1
View File
@@ -13,7 +13,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, GPU, Image, 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};
@@ -36,6 +36,7 @@ macro_rules! for_each_item_type_default {
$action!(Vector);
$action!(f64);
$action!(Raster<CPU>);
$action!(Raster<GPU>);
$action!(Graphic);
$action!(Color);
$action!(Gradient);
@@ -52,6 +53,7 @@ macro_rules! for_each_list_type_default {
$action!(Graphic);
$action!(Artboard);
$action!(Raster<CPU>);
$action!(Raster<GPU>);
$action!(Vector);
$action!(String);
$action!(Color);
@@ -285,6 +285,7 @@ pub use gpu::{Texture, TextureWeakRef};
mod gpu {
use super::*;
use crate::raster_types::__private::Sealed;
use glam::UVec2;
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq, Eq, Hash, DynAny)]
@@ -349,9 +350,9 @@ mod gpu {
}
}
#[derive(Clone, Debug, PartialEq, Hash)]
#[derive(Clone, Debug, Default, PartialEq, Hash)]
pub struct GPU {
pub texture: Texture,
texture: Option<Texture>,
}
impl core_types::CacheHash for GPU {
@@ -365,17 +366,22 @@ mod gpu {
impl Storage for Raster<GPU> {
fn is_empty(&self) -> bool {
self.texture.width() == 0 || self.texture.height() == 0
let size = self.size();
size.x == 0 || size.y == 0
}
}
impl Raster<GPU> {
pub fn new_gpu(texture: impl Into<Texture>) -> Self {
Self::new(GPU { texture: texture.into() })
Self::new(GPU { texture: Some(texture.into()) })
}
pub fn data(&self) -> &wgpu::Texture {
&self.texture
pub fn texture(&self) -> Option<&Texture> {
self.texture.as_ref()
}
pub fn size(&self) -> UVec2 {
self.texture.as_ref().map_or(UVec2::ZERO, |texture| UVec2::new(texture.width(), texture.height()))
}
}
}
@@ -385,7 +391,7 @@ mod gpu {
use super::*;
use crate::raster_types::__private::Sealed;
#[derive(Clone, Debug, PartialEq, Hash, core_types::CacheHash)]
#[derive(Clone, Debug, Default, PartialEq, Hash, core_types::CacheHash)]
pub struct GPU;
impl Sealed for Raster<GPU> {}
@@ -2570,7 +2570,7 @@ impl Render for List<Raster<GPU>> {
/// Draws one item of GPU raster content into the Vello scene.
fn render_raster_gpu_item_to_vello(item: ItemRef<'_, Raster<GPU>>, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
let Some(raster) = item.element() else { return };
let Some(texture) = item.element().and_then(|raster| raster.texture()) else { return };
let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE);
let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.);
let opacity_fill_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
@@ -2610,12 +2610,12 @@ fn render_raster_gpu_item_to_vello(item: ItemRef<'_, Raster<GPU>>, scene: &mut V
return;
}
let width = raster.data().width();
let height = raster.data().height();
let width = texture.width();
let height = texture.height();
let sampler = peniko::ImageSampler::new().with_extend(peniko::Extend::Pad);
let image_transform = transform * transform_attribute * DAffine2::from_scale(1. / DVec2::new(width as f64, height as f64));
scene.draw_texture(raster.texture.clone(), sampler, kurbo::Affine::new(image_transform.to_cols_array()));
scene.draw_texture(texture.clone(), sampler, kurbo::Affine::new(image_transform.to_cols_array()));
if layer {
scene.pop_layer()
@@ -69,6 +69,7 @@ impl RasterKernelLookup<'_> {
/// With `filtered`, it may also call `input_i_sample(texel)`, sampling the input bilinearly at texel coordinates, whose texel centers lie at +0.5, clamped to its edge,
/// which requires every input to be in a filterable format such as `Rgba16Float` rather than [`crate::RASTER_FORMAT`].
/// It declares the texture of each of the `lookups` itself, the `k`th at binding `2 + inputs + k`.
/// An empty input reads as transparent with a size of zero, and an empty `output_size` gives the empty raster without running the kernel.
/// Every run of the same `kernel` must have the same number of inputs, the same kinds of lookups, and the same `filtered`.
pub struct RasterKernelArgs<'a> {
pub kernel: TypeId,
@@ -94,6 +95,7 @@ pub struct RasterKernelRuntime {
pipelines: Mutex<HashMap<(TypeId, wgpu::TextureFormat), KernelPipeline>>,
lookups: Mutex<VecDeque<(u64, wgpu::Texture)>>,
sampler: wgpu::Sampler,
empty_input: wgpu::Texture,
}
impl RasterKernelRuntime {
@@ -147,14 +149,33 @@ impl WgpuPipeline for RasterKernelRuntime {
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let empty_input = executor.context().device.create_texture(&wgpu::TextureDescriptor {
label: Some("raster_kernel_empty_input"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba16Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
Self {
pipelines: Mutex::default(),
lookups: Mutex::default(),
sampler,
empty_input,
}
}
fn run(&self, executor: &WgpuExecutor, args: &RasterKernelArgs<'_>) -> Raster<GPU> {
if args.output_size.x == 0 || args.output_size.y == 0 {
return Raster::default();
}
let device = &executor.context().device;
let param_slots = slots(args.params.len());
@@ -177,7 +198,7 @@ impl WgpuPipeline for RasterKernelRuntime {
let input_views = args
.inputs
.iter()
.map(|input| input.raster.texture.create_view(&wgpu::TextureViewDescriptor::default()))
.map(|input| input.raster.texture().map_or(&self.empty_input, |texture| texture).create_view(&wgpu::TextureViewDescriptor::default()))
.collect::<Vec<_>>();
let lookup_views = args
.lookups
@@ -328,9 +349,9 @@ fn frame_data(args: &RasterKernelArgs<'_>) -> Vec<f32> {
let mut data = vec![args.output_size.x as f32, args.output_size.y as f32, 0., 0.];
for input in &args.inputs {
let affine = input.output_to_texel;
let texture = &input.raster.texture;
let size = input.raster.size();
data.extend([affine.matrix2.x_axis.x, affine.matrix2.x_axis.y, affine.matrix2.y_axis.x, affine.matrix2.y_axis.y].map(|value| value as f32));
data.extend([affine.translation.x as f32, affine.translation.y as f32, texture.width() as f32, texture.height() as f32]);
data.extend([affine.translation.x as f32, affine.translation.y as f32, size.x as f32, size.y as f32]);
}
data
}
@@ -5,31 +5,17 @@ use core_types::list::{Item, List};
use core_types::ops::{Convert, ConvertAsync};
use core_types::transform::Footprint;
use raster_types::Image;
use raster_types::{CPU, GPU, Raster, Texture};
use raster_types::{CPU, GPU, Raster, Storage};
use wgpu::Extent3d;
/// Uploads CPU image data to a GPU texture
fn upload_to_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, image: &Raster<CPU>) -> Texture {
let texture = executor.request_texture_with_format(glam::UVec2::new(image.width, image.height), crate::RASTER_FORMAT);
if image.width == 0 || image.height == 0 {
queue.write_texture(
texture.as_image_copy(),
bytemuck::bytes_of(&Color::TRANSPARENT),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(16),
rows_per_image: Some(1),
},
Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
);
return texture;
fn upload_to_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, image: &Raster<CPU>) -> Raster<GPU> {
if image.is_empty() {
return Raster::default();
}
let texture = executor.request_texture_with_format(glam::UVec2::new(image.width, image.height), crate::RASTER_FORMAT);
queue.write_texture(
texture.as_image_copy(),
bytemuck::cast_slice(image.data.as_slice()),
@@ -44,7 +30,7 @@ fn upload_to_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, image: &Raste
depth_or_array_layers: 1,
},
);
texture
Raster::new_gpu(texture)
}
/// Converts a Raster<GPU> texture to Raster<CPU> by downloading the underlying texture data.
@@ -63,8 +49,8 @@ struct RasterGpuToRasterCpuConverter {
_source: raster_types::Texture,
}
impl RasterGpuToRasterCpuConverter {
fn new(executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>) -> Self {
let texture = data_gpu.data();
fn new(executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>) -> Option<Self> {
let texture = data_gpu.texture()?;
let width = texture.width();
let height = texture.height();
let format = texture.format();
@@ -103,7 +89,7 @@ impl RasterGpuToRasterCpuConverter {
},
);
Self {
Some(Self {
buffer,
width,
height,
@@ -111,8 +97,8 @@ impl RasterGpuToRasterCpuConverter {
unpadded_bytes_per_row,
padded_bytes_per_row,
// Keep source texture alive
_source: data_gpu.texture.clone(),
}
_source: texture.clone(),
})
}
async fn convert(self, device: &wgpu::Device) -> Result<Raster<CPU>, wgpu::BufferAsyncError> {
@@ -232,9 +218,7 @@ impl Convert<List<Raster<GPU>>, WgpuExecutor> for List<Raster<CPU>> {
.into_iter()
.map(|row| {
let (image, attributes) = row.into_parts();
let texture = upload_to_texture(&executor, &queue, &image);
Item::from_parts(Raster::new_gpu(texture), attributes)
Item::from_parts(upload_to_texture(&executor, &queue, &image), attributes)
})
.collect();
@@ -247,10 +231,10 @@ impl Convert<List<Raster<GPU>>, WgpuExecutor> for List<Raster<CPU>> {
impl Convert<Raster<GPU>, WgpuExecutor> for Raster<CPU> {
fn convert(self, _: Footprint, executor: WgpuExecutor) -> Raster<GPU> {
let queue = executor.context().queue.lock();
let texture = upload_to_texture(&executor, &queue, &self);
let raster = upload_to_texture(&executor, &queue, &self);
queue.submit([]);
Raster::new_gpu(texture)
raster
}
}
@@ -284,7 +268,12 @@ impl ConvertAsync<List<Raster<CPU>>, WgpuExecutor> for List<Raster<GPU>> {
let mut map_futures = Vec::new();
for converter in converters {
map_futures.push(converter.convert(device));
map_futures.push(async move {
match converter {
Some(converter) => converter.convert(device).await,
None => Ok(Raster::default()),
}
});
}
let map_results = futures::future::try_join_all(map_futures)
@@ -317,6 +306,7 @@ impl ConvertAsync<Raster<CPU>, WgpuExecutor> for Raster<GPU> {
queue.submit([encoder.finish()]);
let Some(converter) = converter else { return Raster::default() };
converter.convert(device).await.expect("Failed to download texture data")
}
}
+7 -3
View File
@@ -6,11 +6,11 @@ use core_types::context::Ctx;
use core_types::list::Item;
use core_types::ops::ConvertAsync;
use core_types::transform::Footprint;
use glam::{DAffine2, UVec2};
use glam::DAffine2;
use image::{DynamicImage, GenericImage, GenericImageView, GrayImage, ImageBuffer, Luma, Rgba, RgbaImage};
use ndarray::{Array2, ArrayBase, Dim, OwnedRepr};
use raster_types::Image;
use raster_types::{CPU, GPU, Raster};
use raster_types::{CPU, GPU, Raster, Storage};
use std::cmp::{max, min};
use wgpu_executor::WgpuPipelineCache;
use wgpu_executor::shader_runtime::raster_kernel_runtime::RasterKernelInput;
@@ -75,9 +75,13 @@ impl DehazeRaster for Raster<GPU> {
/// Runs the CPU's algorithm in float without its 8-bit quantization, downloading the dark channel to choose the atmospheric light exactly as the CPU does.
/// The guided filter's intermediates stay in [`wgpu_executor::RASTER_FORMAT`] since its variances lose their precision at half-float.
async fn dehaze(image: Item<Self>, strength: f64, pipeline: &WgpuPipelineCache) -> Result<Item<Self>, NodeError> {
if image.element().is_empty() {
return Ok(image);
}
let executor = pipeline.executor().cloned().ok_or_else(|| NodeError::new("A GPU is required to process a GPU raster"))?;
let (raster, attributes) = image.into_parts();
let size = UVec2::new(raster.texture.width(), raster.texture.height());
let size = raster.size();
let radius = (PATCH_SIZE / 2) as i32;
let eroded = run_raster_kernel(&DehazeErode { radius, vertical: false }, vec![dehaze_input(&raster)], size, pipeline)?;
+9 -5
View File
@@ -6,11 +6,11 @@ use core_types::color::{Alpha, Color, Pixel, RGB};
use core_types::context::Ctx;
use core_types::list::Item;
use core_types::{Interrupt, NodeError};
use glam::{DAffine2, UVec2};
use glam::DAffine2;
use num_enum::IntoPrimitive;
use raster_types::Image;
use raster_types::{Bitmap, BitmapMut};
use raster_types::{CPU, GPU, Raster};
use raster_types::{CPU, GPU, Raster, Storage};
use wgpu_executor::WgpuPipelineCache;
use wgpu_executor::shader_runtime::raster_kernel_runtime::RasterKernelInput;
@@ -174,7 +174,11 @@ impl MedianFilterRaster for Raster<CPU> {
impl MedianFilterRaster for Raster<GPU> {
fn median_filter(image: Self, radius: u32, pipeline: &WgpuPipelineCache) -> Result<Self, NodeError> {
let size = UVec2::new(image.texture.width(), image.texture.height());
if image.is_empty() {
return Ok(image);
}
let size = image.size();
let kernel = MedianWindow {
radius: radius.min(size.max_element()),
};
@@ -389,12 +393,12 @@ impl BlurRaster for Raster<GPU> {
/// Each pass sums premultiplied colors into a [`FILTERABLE_FORMAT`] intermediate, and a kernel reaching past [`MAX_BLUR_REACH`] runs on the image halved
/// until it fits, weighing each halved texel by how much of the image it covers, then is scaled back up bilinearly, approximating the CPU's blur.
fn blur(image: Item<Self>, radius: f64, box_blur: bool, gamma: bool, pipeline: &WgpuPipelineCache) -> Result<Item<Self>, NodeError> {
if radius < 0.1 {
if radius < 0.1 || image.element().is_empty() {
return Ok(image);
}
let (raster, attributes) = image.into_parts();
let space = if gamma { BlurSpace::Gamma } else { BlurSpace::Linear };
let size = UVec2::new(raster.texture.width(), raster.texture.height());
let size = raster.size();
let full_size = size.as_ivec2().to_array();
let mut levels = 0;
+17 -10
View File
@@ -5,7 +5,7 @@ use core_types::ops::ConvertAsync;
use core_types::transform::Footprint;
use core_types::{Ctx, NodeError};
use glam::{DAffine2, DMat2, DVec2, UVec2};
use raster_types::{CPU, GPU, Raster};
use raster_types::{CPU, GPU, Raster, Storage};
use std::any::{TypeId, type_name};
use vector_types::Gradient;
pub use wgpu_executor::shader_runtime::raster_kernel_runtime::RasterKernelLookup;
@@ -455,7 +455,11 @@ impl Adjust for Raster<CPU> {
impl Adjust for Raster<GPU> {
fn adjust<K: MapColor>(self, kernel: &K, pipeline: &WgpuPipelineCache) -> Result<Self, NodeError> {
let size = UVec2::new(self.texture.width(), self.texture.height());
if self.is_empty() {
return Ok(self);
}
let size = self.size();
let input = RasterKernelInput {
raster: &self,
output_to_texel: DAffine2::IDENTITY,
@@ -521,30 +525,29 @@ impl KernelFrame {
/// A raster item's size in pixels and its `ATTR_TRANSFORM`, as [`union_frame`] and [`KernelFrame::new`] take each input.
pub fn raster_placement(raster: &Item<Raster<GPU>>) -> (UVec2, DAffine2) {
let size = UVec2::new(raster.element().texture.width(), raster.element().texture.height());
(size, raster.attribute_cloned_or_default(ATTR_TRANSFORM))
(raster.element().size(), raster.attribute_cloned_or_default(ATTR_TRANSFORM))
}
/// The frame covering the union of `inputs`, each a raster's size and transform, on the finest of their pixel grids.
///
/// The grid's axes follow the first input's, with the smallest pixel step along each that any input has, anchored at the first input's origin.
/// Each side is capped at [`MAX_FRAME_SIDE`] pixels. `None` without inputs or with an empty or non-invertible one.
/// Each side is capped at [`MAX_FRAME_SIDE`] pixels. Empty inputs are ignored. `None` without a non-empty input or with a non-invertible one.
pub fn union_frame(inputs: &[(UVec2, DAffine2)]) -> Option<KernelFrame> {
let placeable = |(size, transform): &(UVec2, DAffine2)| size.x > 0 && size.y > 0 && transform.matrix2.determinant() != 0.;
let first = inputs.first()?.1;
if !inputs.iter().all(placeable) {
let placed = inputs.iter().copied().filter(|(size, _)| size.x > 0 && size.y > 0).collect::<Vec<_>>();
let first = placed.first()?.1;
if placed.iter().any(|(_, transform)| transform.matrix2.determinant() == 0.) {
return None;
}
let axes = DMat2::from_cols(first.matrix2.x_axis.normalize(), first.matrix2.y_axis.normalize());
let to_axes = axes.inverse();
let corners = inputs
let corners = placed
.iter()
.flat_map(|(_, transform)| [DVec2::ZERO, DVec2::X, DVec2::Y, DVec2::ONE].map(|corner| to_axes * transform.transform_point2(corner)));
let (min, max) = corners.fold((DVec2::INFINITY, DVec2::NEG_INFINITY), |(min, max), corner| (min.min(corner), max.max(corner)));
let step = inputs
let step = placed
.iter()
.map(|(size, transform)| {
let to_texels = DMat2::from_diagonal(size.as_dvec2()) * transform.matrix2.inverse() * axes;
@@ -582,6 +585,10 @@ impl ReadPixels for Raster<GPU> {
fn read_pixels(self, pipeline: &WgpuPipelineCache) -> impl Future<Output = Result<Raster<CPU>, NodeError>> + Send {
let executor = pipeline.executor().cloned();
async move {
if self.is_empty() {
return Ok(Raster::default());
}
let executor = executor.ok_or_else(|| NodeError::new("A GPU is required to read a GPU raster"))?;
Ok(self.convert(Footprint::DEFAULT, executor).await)
}
+15 -2
View File
@@ -17,7 +17,7 @@ use graphene_resource::Resource;
use rand::prelude::*;
use rand_chacha::ChaCha8Rng;
use raster_types::{Bitmap, BitmapMut};
use raster_types::{CPU, GPU, Raster};
use raster_types::{CPU, GPU, Raster, Storage};
use raster_types::{Image, ImageError};
use std::fmt::Debug;
use std::hash::Hash;
@@ -263,7 +263,12 @@ impl PlacedRaster for Raster<CPU> {
impl PlacedRaster for Raster<GPU> {
/// Each channel is placed by its transform into their [`union_frame`], which takes the red channel's other attributes, and gives its luminance weighted by its alpha.
/// An empty channel gives zero, or full opacity for the alpha channel.
fn channels_to_image(channels: [Item<Self>; 4], pipeline: &WgpuPipelineCache) -> Result<Item<Self>, NodeError> {
if channels.iter().all(|channel| channel.element().is_empty()) {
return Ok(Item::default());
}
let frame = union_frame(&channels.each_ref().map(raster_placement)).ok_or_else(|| NodeError::new("Every channel must be placed by an invertible transform"))?;
let raster = run_raster_kernel(&CombineChannels {}, frame.kernel_inputs(&channels.each_ref().map(Item::element)), frame.size, pipeline)?;
@@ -275,6 +280,10 @@ impl PlacedRaster for Raster<GPU> {
/// The stencil is sampled bilinearly where each image pixel's center lies, extending its edge pixels beyond it.
fn mask(image: Item<Self>, stencil: Item<Self>, pipeline: &WgpuPipelineCache) -> Result<Item<Self>, NodeError> {
if image.element().is_empty() || stencil.element().is_empty() {
return Ok(image);
}
let (image_size, image_transform) = raster_placement(&image);
let (stencil_size, stencil_transform) = raster_placement(&stencil);
if image_transform.matrix2.determinant() == 0. || stencil_transform.matrix2.determinant() == 0. {
@@ -294,6 +303,10 @@ impl PlacedRaster for Raster<GPU> {
}
fn extend_image_to_bounds(image: Item<Self>, bounds: DAffine2, pipeline: &WgpuPipelineCache) -> Result<Item<Self>, (Item<Self>, NodeError)> {
if image.element().is_empty() {
return Ok(image);
}
let (image_size, image_transform) = raster_placement(&image);
let image_aabb = Bbox::unit().affine_transform(image_transform).to_axis_aligned_bbox();
let bounds_aabb = Bbox::unit().affine_transform(bounds.transform()).to_axis_aligned_bbox();
@@ -338,7 +351,7 @@ impl RasterKernel for CombineChannels {
let red = input_0_at(coord);
let green = input_1_at(coord);
let blue = input_2_at(coord);
let alpha = input_3_at(coord);
let alpha = select(input_3_at(coord), vec4<f32>(1.), any(input_3_size() == vec2<i32>(0)));
return vec4<f32>(luminance_rec_709(red) * red.a, luminance_rec_709(green) * green.a, luminance_rec_709(blue) * blue.a, luminance_rec_709(alpha) * alpha.a);
"#,
)