Fall back to half-float rasters where the GPU can't render full floats

This commit is contained in:
Dennis Kobert authored and Keavon Chambers committed 2026-11-05 13:30:20 -08:00
1 parent 2e57be5aa1
commit 181c8e461c
10 files changed
+72 -23

No files matched your search

Generated
+1
View File
@@ -8737,6 +8737,7 @@ dependencies = [
"futures",
"glam",
"graphene-application-io",
"half",
"log",
"node-macro",
"raster-types",
@@ -33,3 +33,4 @@ web-sys = { workspace = true }
vello_gpu = { workspace = true }
bytemuck = { workspace = true }
thiserror = { workspace = true }
half = { workspace = true }
+24 -1
View File
@@ -37,8 +37,10 @@ const TEXTURE_CACHE_SIZE: u64 = 1024 * 1024 * 1024; // 1GB
#[cfg(target_family = "wasm")]
const TEXTURE_CACHE_SIZE: u64 = 512 * 1024 * 1024; // 512MB
/// The format of every raster texture, holding linear-light straight-alpha values.
/// The preferred format of raster textures, holding linear-light straight-alpha values.
pub const RASTER_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float;
/// The raster texture format on adapters that can't render to [`RASTER_FORMAT`], or when `GRAPHITE_RASTER_FORMAT=f16` forces it.
pub const FALLBACK_RASTER_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
#[derive(dyn_any::DynAny, Clone)]
pub struct WgpuExecutor {
@@ -49,12 +51,18 @@ impl WgpuExecutor {
pub fn context(&self) -> &WgpuContext {
&self.inner.context
}
/// The format of every raster texture this executor creates, either [`RASTER_FORMAT`] or [`FALLBACK_RASTER_FORMAT`].
pub fn raster_format(&self) -> wgpu::TextureFormat {
self.inner.raster_format
}
}
#[derive(dyn_any::DynAny)]
pub struct WgpuExecutorInner {
context: WgpuContext,
texture_cache: std::sync::Mutex<TextureCache>,
raster_format: wgpu::TextureFormat,
vello_renderer: VelloRenderer,
/// The canvas the node graph renders documents on.
document_canvas: Mutex<VelloCanvas>,
@@ -182,6 +190,7 @@ impl WgpuExecutor {
}
pub fn with_context(context: WgpuContext) -> Option<Self> {
let raster_format = choose_raster_format(&context.adapter);
let vello_renderer = VelloRenderer::new(&context.device);
let texture_cache = TextureCache::new(TEXTURE_CACHE_SIZE);
@@ -190,6 +199,7 @@ impl WgpuExecutor {
inner: Arc::new(WgpuExecutorInner {
context,
texture_cache: texture_cache.into(),
raster_format,
vello_renderer,
document_canvas: Mutex::default(),
}),
@@ -200,3 +210,16 @@ impl WgpuExecutor {
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("No GPU is available")]
pub struct NoGpuError;
fn choose_raster_format(adapter: &wgpu::Adapter) -> wgpu::TextureFormat {
if std::env::var("GRAPHITE_RASTER_FORMAT").is_ok_and(|format| format == "f16") {
return FALLBACK_RASTER_FORMAT;
}
if adapter.get_texture_format_features(RASTER_FORMAT).allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT) {
RASTER_FORMAT
} else {
log::warn!("The GPU can't render to {RASTER_FORMAT:?}, so rasters fall back to {FALLBACK_RASTER_FORMAT:?}");
FALLBACK_RASTER_FORMAT
}
}
@@ -4,6 +4,7 @@ use core_types::color::SRGBA8;
use core_types::list::{Item, List};
use core_types::ops::{Convert, ConvertAsync};
use core_types::transform::Footprint;
use half::f16;
use raster_types::Image;
use raster_types::{CPU, GPU, Raster, Storage};
use wgpu::Extent3d;
@@ -14,14 +15,21 @@ fn upload_to_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, image: &Raste
return Raster::default();
}
let texture = executor.request_texture_with_format(glam::UVec2::new(image.width, image.height), crate::RASTER_FORMAT);
let format = executor.raster_format();
let texture = executor.request_texture_with_format(glam::UVec2::new(image.width, image.height), format);
let half_floats: Vec<[f16; 4]>;
let (bytes, bytes_per_pixel) = if format == crate::FALLBACK_RASTER_FORMAT {
half_floats = image.data.iter().map(|color| color.to_vec4().to_array().map(f16::from_f32)).collect();
(bytemuck::cast_slice(half_floats.as_slice()), 8)
} else {
(bytemuck::cast_slice(image.data.as_slice()), 16)
};
queue.write_texture(
texture.as_image_copy(),
bytemuck::cast_slice(image.data.as_slice()),
bytes,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(16 * image.width),
bytes_per_row: Some(bytes_per_pixel * image.width),
rows_per_image: Some(image.height),
},
Extent3d {
@@ -37,7 +45,7 @@ fn upload_to_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, image: &Raste
///
/// Assumptions:
/// - 2D texture, mip level 0
/// - 4 bytes-per-pixel RGBA8, or `RASTER_FORMAT`
/// - 4 bytes-per-pixel RGBA8, or `RASTER_FORMAT` or `FALLBACK_RASTER_FORMAT`
/// - Texture has COPY_SRC usage
struct RasterGpuToRasterCpuConverter {
buffer: Buffer,
@@ -54,7 +62,11 @@ impl RasterGpuToRasterCpuConverter {
let width = texture.width();
let height = texture.height();
let format = texture.format();
let bytes_per_pixel = if format == crate::RASTER_FORMAT { 16 } else { 4 };
let bytes_per_pixel = match format {
crate::RASTER_FORMAT => 16,
crate::FALLBACK_RASTER_FORMAT => 8,
_ => 4,
};
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;
@@ -142,11 +154,19 @@ impl RasterGpuToRasterCpuConverter {
for row in 0..self.height as usize {
let start = row * row_stride;
let row_slice = &view[start..start + row_bytes];
if self.format == crate::RASTER_FORMAT {
cpu_data.extend(bytemuck::pod_collect_to_vec::<u8, Color>(row_slice));
} else {
for &[red, green, blue, alpha] in row_slice.as_chunks::<4>().0 {
cpu_data.push(SRGBA8::new(red, green, blue, alpha).into());
match self.format {
crate::RASTER_FORMAT => cpu_data.extend(bytemuck::pod_collect_to_vec::<u8, Color>(row_slice)),
crate::FALLBACK_RASTER_FORMAT => {
let pixels = bytemuck::pod_collect_to_vec::<u8, [f16; 4]>(row_slice);
cpu_data.extend(pixels.iter().map(|pixel| {
let [red, green, blue, alpha] = pixel.map(f16::to_f32);
Color::from_rgbaf32_unchecked(red, green, blue, alpha)
}));
}
_ => {
for &[red, green, blue, alpha] in row_slice.as_chunks::<4>().0 {
cpu_data.push(SRGBA8::new(red, green, blue, alpha).into());
}
}
}
}
@@ -361,7 +361,7 @@ impl ImageTextures {
if let SceneImage::Texture(source) = image {
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
let loads_linear_light = source.format().is_srgb() || source.format() == crate::RASTER_FORMAT;
let loads_linear_light = source.format().is_srgb() || matches!(source.format(), crate::RASTER_FORMAT | crate::FALLBACK_RASTER_FORMAT);
alpha_conversion.premultiply(device, encoder, &source_view, loads_linear_light, &view);
}
@@ -4,7 +4,7 @@ pub(super) struct Convert {
}
impl Convert {
pub(super) fn new(device: &wgpu::Device) -> Self {
pub(super) fn new(device: &wgpu::Device, raster_format: wgpu::TextureFormat) -> Self {
let shader = device.create_shader_module(wgpu::include_wgsl!("convert.wgsl"));
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("basic_brush_convert_bind_group_layout"),
@@ -37,7 +37,7 @@ impl Convert {
module: &shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu_executor::RASTER_FORMAT.into())],
targets: &[Some(raster_format.into())],
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
@@ -80,7 +80,7 @@ impl WgpuPipeline for BasicBrushPipeline {
Self {
scatter: Scatter::new(device),
resolve: Resolve::new(device),
convert: Convert::new(device),
convert: Convert::new(device, executor.raster_format()),
kernels: KernelCache::default(),
}
}
@@ -183,7 +183,7 @@ pub(super) fn render(pipeline: &BasicBrushPipeline, executor: &WgpuExecutor, fra
let updated = (!missing.is_empty()).then(|| executor.request_texture_with_format(crop.size, COMPOSITE_FORMAT));
let composite = executor.request_texture_with_format(crop.size, COMPOSITE_FORMAT);
let scratch = Field::request(executor, region.size);
let output = executor.request_texture_with_format(crop.size, wgpu_executor::RASTER_FORMAT);
let output = executor.request_texture_with_format(crop.size, executor.raster_format());
let mut recorder = Recorder::new(pipeline, executor, &region);
if let Some(updated) = &updated {
+1 -1
View File
@@ -73,7 +73,7 @@ fn dehaze_input(raster: &Raster<GPU>) -> RasterKernelInput<'_> {
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.
/// The guided filter's intermediates stay in the executor's raster format rather than `FILTERABLE_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);
+9 -5
View File
@@ -411,12 +411,16 @@ fn run<K: ToGpuParams + 'static>(
.ok_or_else(|| NodeError::new("A GPU is required to process a GPU raster"))
}
/// Runs `kernel` on its inputs, each placed by the affine from output pixel coordinates to its texel coordinates, into a raster of `output_size`.
pub fn run_raster_kernel<K: RasterKernel>(kernel: &K, inputs: Vec<RasterKernelInput<'_>>, output_size: UVec2, pipeline: &WgpuPipelineCache) -> Result<Raster<GPU>, NodeError> {
run_raster_kernel_with_format(kernel, inputs, output_size, RASTER_FORMAT, pipeline)
fn raster_format(pipeline: &WgpuPipelineCache) -> WgpuTextureFormat {
pipeline.executor().map_or(RASTER_FORMAT, WgpuExecutor::raster_format)
}
/// Runs `kernel` like [`run_raster_kernel`] into a texture of `output_format` instead of [`RASTER_FORMAT`], such as a [`FILTERABLE_FORMAT`] intermediate a [`RasterKernel::FILTERED`] kernel can read.
/// Runs `kernel` on its inputs, each placed by the affine from output pixel coordinates to its texel coordinates, into a raster of `output_size`.
pub fn run_raster_kernel<K: RasterKernel>(kernel: &K, inputs: Vec<RasterKernelInput<'_>>, output_size: UVec2, pipeline: &WgpuPipelineCache) -> Result<Raster<GPU>, NodeError> {
run_raster_kernel_with_format(kernel, inputs, output_size, raster_format(pipeline), pipeline)
}
/// Runs `kernel` like [`run_raster_kernel`] into a texture of `output_format` instead of the executor's raster format, such as a [`FILTERABLE_FORMAT`] intermediate a [`RasterKernel::FILTERED`] kernel can read.
pub fn run_raster_kernel_with_format<K: RasterKernel>(
kernel: &K,
inputs: Vec<RasterKernelInput<'_>>,
@@ -464,7 +468,7 @@ impl Adjust for Raster<GPU> {
raster: &self,
output_to_texel: DAffine2::IDENTITY,
};
run(kernel, map_color_module::<K>, false, vec![input], size, RASTER_FORMAT, pipeline)
run(kernel, map_color_module::<K>, false, vec![input], size, raster_format(pipeline), pipeline)
}
}