From 3898cb4a1e9a01c727912e0c8140ab2e5dbd52ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?charlotte=20=F0=9F=8C=B8?= Date: Mon, 16 Nov 2026 12:59:51 -0800 Subject: [PATCH 1/4] 3D strokes, vertex baking and draw pooling. --- crates/processing_core/src/constants.rs | 3 + crates/processing_ffi/src/lib.rs | 19 +- crates/processing_node/src/lib.rs | 9 +- crates/processing_pyo3/src/constants.rs | 1 + crates/processing_pyo3/src/graphics.rs | 52 +- crates/processing_pyo3/src/lib.rs | 25 +- crates/processing_render/src/gltf.rs | 1 + crates/processing_render/src/graphics.rs | 5 +- crates/processing_render/src/lib.rs | 21 +- crates/processing_render/src/material/mod.rs | 17 +- .../src/material/processing.wgsl | 132 ++++ .../src/particles/material.rs | 24 +- .../processing_render/src/particles/pack.rs | 8 +- .../src/particles/point_render.rs | 9 +- .../processing_render/src/render/command.rs | 11 +- crates/processing_render/src/render/line.rs | 83 ++- .../processing_render/src/render/material.rs | 97 ++- crates/processing_render/src/render/mod.rs | 648 ++++++++++++------ crates/processing_render/src/render/pool.rs | 247 +++++++ .../src/render/primitive/arc.rs | 7 +- .../src/render/primitive/curves.rs | 12 +- .../src/render/primitive/ellipse.rs | 6 +- .../src/render/primitive/line.rs | 7 +- .../src/render/primitive/mod.rs | 111 ++- .../src/render/primitive/quad.rs | 10 +- .../src/render/primitive/rect.rs | 11 +- .../src/render/primitive/triangle.rs | 10 +- crates/processing_wasm/src/lib.rs | 9 +- examples/curves.rs | 7 +- tests/visual/cases.toml | 27 + 30 files changed, 1316 insertions(+), 313 deletions(-) create mode 100644 crates/processing_render/src/material/processing.wgsl create mode 100644 crates/processing_render/src/render/pool.rs diff --git a/crates/processing_core/src/constants.rs b/crates/processing_core/src/constants.rs index 28a4ba04..a2479c3e 100644 --- a/crates/processing_core/src/constants.rs +++ b/crates/processing_core/src/constants.rs @@ -38,6 +38,9 @@ pub const ITALIC: &str = "italic"; pub const BOLD: &str = "bold"; pub const BOLD_ITALIC: &str = "bold_italic"; +pub const ENABLE_STROKE_PERSPECTIVE: &str = "enable_stroke_perspective"; // hint +pub const DISABLE_STROKE_PERSPECTIVE: &str = "disable_stroke_perspective"; + pub const WORD: &str = "word"; // text wrap mode pub const CHAR: &str = "char"; diff --git a/crates/processing_ffi/src/lib.rs b/crates/processing_ffi/src/lib.rs index b0b153ef..6c3797e9 100644 --- a/crates/processing_ffi/src/lib.rs +++ b/crates/processing_ffi/src/lib.rs @@ -714,7 +714,15 @@ pub extern "C" fn processing_circle(graphics_id: u64, cx: f32, cy: f32, d: f32) pub extern "C" fn processing_line(graphics_id: u64, x1: f32, y1: f32, x2: f32, y2: f32) { error::clear_error(); let graphics_entity = Entity::from_bits(graphics_id); - error::check(|| graphics_record_command(graphics_entity, DrawCommand::Line { x1, y1, x2, y2 })); + error::check(|| { + graphics_record_command( + graphics_entity, + DrawCommand::Line { + from: Vec3::new(x1, y1, 0.0), + to: Vec3::new(x2, y2, 0.0), + }, + ) + }); } /// Draw a triangle. @@ -782,7 +790,14 @@ pub extern "C" fn processing_quad( pub extern "C" fn processing_point(graphics_id: u64, x: f32, y: f32) { error::clear_error(); let graphics_entity = Entity::from_bits(graphics_id); - error::check(|| graphics_record_command(graphics_entity, DrawCommand::Point { x, y })); + error::check(|| { + graphics_record_command( + graphics_entity, + DrawCommand::Point { + at: Vec3::new(x, y, 0.0), + }, + ) + }); } /// Draw a square. diff --git a/crates/processing_node/src/lib.rs b/crates/processing_node/src/lib.rs index 34d9b2f9..a11e97db 100644 --- a/crates/processing_node/src/lib.rs +++ b/crates/processing_node/src/lib.rs @@ -564,10 +564,8 @@ pub fn js_line(graphics_id: BigInt, x1: f64, y1: f64, x2: f64, y2: f64) -> Resul record( graphics_id, DrawCommand::Line { - x1: x1 as f32, - y1: y1 as f32, - x2: x2 as f32, - y2: y2 as f32, + from: vec3(x1, y1, 0.0), + to: vec3(x2, y2, 0.0), }, ) } @@ -627,8 +625,7 @@ pub fn js_point(graphics_id: BigInt, x: f64, y: f64) -> Result<()> { record( graphics_id, DrawCommand::Point { - x: x as f32, - y: y as f32, + at: vec3(x, y, 0.0), }, ) } diff --git a/crates/processing_pyo3/src/constants.rs b/crates/processing_pyo3/src/constants.rs index 5d6ae744..81a19100 100644 --- a/crates/processing_pyo3/src/constants.rs +++ b/crates/processing_pyo3/src/constants.rs @@ -42,6 +42,7 @@ pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> { add!(m, TOP, BOTTOM, BASELINE); add!(m, NORMAL, ITALIC, BOLD, BOLD_ITALIC); add!(m, IMAGE); + add!(m, ENABLE_STROKE_PERSPECTIVE, DISABLE_STROKE_PERSPECTIVE); add!(m, WORD, CHAR); add!(m, NEAREST, CLAMP, REPEAT, MIRROR); add!(m, SRGB, LINEAR, HSL, HSV, HWB, OKLAB, OKLCH, LAB, LCH, XYZ); diff --git a/crates/processing_pyo3/src/graphics.rs b/crates/processing_pyo3/src/graphics.rs index 2202aa29..28f24fb6 100644 --- a/crates/processing_pyo3/src/graphics.rs +++ b/crates/processing_pyo3/src/graphics.rs @@ -1522,8 +1522,28 @@ impl Graphics { .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } - pub fn line(&self, x1: f32, y1: f32, x2: f32, y2: f32) -> PyResult<()> { - graphics_record_command(self.entity, DrawCommand::Line { x1, y1, x2, y2 }) + /// `line(x1, y1, x2, y2)`, or in 3D `line(x1, y1, z1, x2, y2, z2)`. + #[pyo3(signature = (x1, y1, x2, y2, *args))] + pub fn line( + &self, + x1: f32, + y1: f32, + x2: f32, + y2: f32, + args: &Bound<'_, PyTuple>, + ) -> PyResult<()> { + let rest: Vec = args.extract()?; + let (from, to) = match rest[..] { + [] => (Vec3::new(x1, y1, 0.0), Vec3::new(x2, y2, 0.0)), + // six numbers read as two points + [a, b] => (Vec3::new(x1, y1, x2), Vec3::new(y2, a, b)), + _ => { + return Err(pyo3::exceptions::PyTypeError::new_err( + "line() takes 4 numbers, or 6 in 3D", + )); + } + }; + graphics_record_command(self.entity, DrawCommand::Line { from, to }) .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } @@ -1569,9 +1589,15 @@ impl Graphics { .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } - pub fn point(&self, x: f32, y: f32) -> PyResult<()> { - graphics_record_command(self.entity, DrawCommand::Point { x, y }) - .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + #[pyo3(signature = (x, y, z=0.0))] + pub fn point(&self, x: f32, y: f32, z: f32) -> PyResult<()> { + graphics_record_command( + self.entity, + DrawCommand::Point { + at: Vec3::new(x, y, z), + }, + ) + .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn square(&self, x: f32, y: f32, s: f32) -> PyResult<()> { @@ -1710,6 +1736,22 @@ impl Graphics { .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } + /// Changes a renderer setting (Processing `hint`). + pub fn hint(&self, which: &str) -> PyResult<()> { + use processing::prelude::constants as consts; + let perspective = match () { + _ if which.eq_ignore_ascii_case(consts::ENABLE_STROKE_PERSPECTIVE) => true, + _ if which.eq_ignore_ascii_case(consts::DISABLE_STROKE_PERSPECTIVE) => false, + _ => { + return Err(PyValueError::new_err(format!( + "unsupported hint: {which:?}" + ))); + } + }; + graphics_record_command(self.entity, DrawCommand::StrokePerspective(perspective)) + .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + } + /// `IMAGE` reads `vertex()` texture coordinates in pixels of the texture, `NORMAL` from 0 to 1. pub fn texture_mode(&self, mode: &str) -> PyResult<()> { let mode = processing::prelude::TextureMode::parse(mode) diff --git a/crates/processing_pyo3/src/lib.rs b/crates/processing_pyo3/src/lib.rs index 2af14b2f..28cd9ef0 100644 --- a/crates/processing_pyo3/src/lib.rs +++ b/crates/processing_pyo3/src/lib.rs @@ -2498,9 +2498,16 @@ pub mod processing_py { } #[pyfunction] - #[pyo3(pass_module)] - fn line(module: &Bound<'_, PyModule>, x1: f32, y1: f32, x2: f32, y2: f32) -> PyResult<()> { - graphics!(module).line(x1, y1, x2, y2) + #[pyo3(pass_module, signature = (x1, y1, x2, y2, *args))] + fn line( + module: &Bound<'_, PyModule>, + x1: f32, + y1: f32, + x2: f32, + y2: f32, + args: &Bound<'_, PyTuple>, + ) -> PyResult<()> { + graphics!(module).line(x1, y1, x2, y2, args) } #[pyfunction] @@ -2534,9 +2541,9 @@ pub mod processing_py { } #[pyfunction] - #[pyo3(pass_module)] - fn point(module: &Bound<'_, PyModule>, x: f32, y: f32) -> PyResult<()> { - graphics!(module).point(x, y) + #[pyo3(pass_module, signature = (x, y, z=0.0))] + fn point(module: &Bound<'_, PyModule>, x: f32, y: f32, z: f32) -> PyResult<()> { + graphics!(module).point(x, y, z) } #[pyfunction] @@ -2621,6 +2628,12 @@ pub mod processing_py { graphics!(module).normal(args) } + #[pyfunction] + #[pyo3(pass_module)] + fn hint(module: &Bound<'_, PyModule>, which: &str) -> PyResult<()> { + graphics!(module).hint(which) + } + #[pyfunction] #[pyo3(pass_module)] fn texture_mode(module: &Bound<'_, PyModule>, mode: &str) -> PyResult<()> { diff --git a/crates/processing_render/src/gltf.rs b/crates/processing_render/src/gltf.rs index add89361..3ca6e1c7 100644 --- a/crates/processing_render/src/gltf.rs +++ b/crates/processing_render/src/gltf.rs @@ -334,6 +334,7 @@ pub fn material( extension: ProcessingMaterial { blend_state: None, depth_write: None, + instance_fill: false, }, }); let entity = world.spawn(UntypedMaterial(handle.untyped())).id(); diff --git a/crates/processing_render/src/graphics.rs b/crates/processing_render/src/graphics.rs index c8eab929..fb27d8be 100644 --- a/crates/processing_render/src/graphics.rs +++ b/crates/processing_render/src/graphics.rs @@ -339,7 +339,10 @@ pub fn create( CommandBuffer::new(), RenderState::default(), crate::image::BackgroundBlit::default(), - crate::color::ColorMode::default(), + ( + crate::color::ColorMode::default(), + crate::render::pool::DrawPool::default(), + ), SurfaceSize(width, height), Graphics { readback_buffer, diff --git a/crates/processing_render/src/lib.rs b/crates/processing_render/src/lib.rs index 7d706a27..c0590bbd 100644 --- a/crates/processing_render/src/lib.rs +++ b/crates/processing_render/src/lib.rs @@ -69,6 +69,20 @@ use crate::render::command::DrawCommand; #[derive(Component)] pub struct Flush; +/// Registers one of the renderer's own shaders under `$handle` while the app is built. +macro_rules! internal_shader { + ($app:expr, $handle:expr, $path:literal) => {{ + let _ = $app + .world_mut() + .resource_mut::>() + .insert( + $handle.id(), + bevy::shader::Shader::from_wgsl(include_str!($path), concat!(file!(), "/", $path)), + ); + }}; +} +pub(crate) use internal_shader; + pub struct ProcessingRenderPlugin; impl Plugin for ProcessingRenderPlugin { @@ -756,10 +770,13 @@ pub fn graphics_get_color_mode(graphics_entity: Entity) -> error::Result error::Result<()> { + // no system dispatch: called once per draw command app_mut(|app| { app.world_mut() - .run_system_cached_with(graphics::record_command, (graphics_entity, cmd)) - .unwrap() + .get_mut::(graphics_entity) + .ok_or(error::ProcessingError::GraphicsNotFound)? + .push(cmd); + Ok(()) }) } diff --git a/crates/processing_render/src/material/mod.rs b/crates/processing_render/src/material/mod.rs index aeabbaa8..4fa24e20 100644 --- a/crates/processing_render/src/material/mod.rs +++ b/crates/processing_render/src/material/mod.rs @@ -16,10 +16,15 @@ use bevy::shader::ShaderRef; use bevy_naga_reflect::reflect::ParameterCategory; use processing_core::error::{self, ProcessingError}; +/// The StandardMaterial fragment shader with the per-instance fill. +const PROCESSING_SHADER: Handle = + bevy::asset::uuid_handle!("6f1f3c1e-2b7a-4d0e-9a53-8c2f4be7a901"); + pub struct ProcessingMaterialPlugin; impl Plugin for ProcessingMaterialPlugin { fn build(&self, app: &mut App) { + crate::internal_shader!(app, PROCESSING_SHADER, "processing.wgsl"); app.add_plugins(bevy::pbr::MaterialPlugin::< ExtendedMaterial, >::default()); @@ -54,6 +59,7 @@ pub fn create_pbr( extension: ProcessingMaterial { blend_state: None, depth_write: None, + instance_fill: false, }, }); commands.spawn(UntypedMaterial(handle.untyped())).id() @@ -387,6 +393,8 @@ pub fn destroy( pub struct ProcessingMaterial { pub blend_state: Option, pub depth_write: Option, + /// the fill is the sRGB8 RGBA color packed in each instance's `MeshTag` + pub instance_fill: bool, } #[repr(C)] @@ -394,6 +402,7 @@ pub struct ProcessingMaterial { pub struct ProcessingMaterialKey { blend_state: Option, depth_write: Option, + instance_fill: bool, } impl From<&ProcessingMaterial> for ProcessingMaterialKey { @@ -401,6 +410,7 @@ impl From<&ProcessingMaterial> for ProcessingMaterialKey { ProcessingMaterialKey { blend_state: mat.blend_state, depth_write: mat.depth_write, + instance_fill: mat.instance_fill, } } } @@ -411,7 +421,7 @@ impl MaterialExtension for ProcessingMaterial { } fn fragment_shader() -> ShaderRef { - ::fragment_shader() + PROCESSING_SHADER.into() } fn specialize( @@ -425,6 +435,11 @@ impl MaterialExtension for ProcessingMaterial { key.bind_group_data.blend_state, key.bind_group_data.depth_write, ); + if key.bind_group_data.instance_fill + && let Some(fragment) = &mut descriptor.fragment + { + fragment.shader_defs.push("INSTANCE_FILL".into()); + } Ok(()) } } diff --git a/crates/processing_render/src/material/processing.wgsl b/crates/processing_render/src/material/processing.wgsl new file mode 100644 index 00000000..681a4fff --- /dev/null +++ b/crates/processing_render/src/material/processing.wgsl @@ -0,0 +1,132 @@ +// The StandardMaterial fragment shader plus a per-instance fill packed in the mesh tag. + +#import bevy_pbr::{ + pbr_types, + pbr_functions::alpha_discard, + pbr_fragment::pbr_input_from_standard_material, + decal::clustered::apply_decals, +} + +#ifdef PREPASS_PIPELINE +#import bevy_pbr::{ + prepass_io::{VertexOutput, FragmentOutput}, + pbr_deferred_functions::deferred_output, +} +#else +#import bevy_pbr::{ + forward_io::{VertexOutput, FragmentOutput}, + pbr_functions::{apply_pbr_lighting, main_pass_post_lighting_processing}, + pbr_types::STANDARD_MATERIAL_FLAGS_UNLIT_BIT, +} +#endif + +#ifdef VISIBILITY_RANGE_DITHER +#import bevy_pbr::pbr_functions::visibility_range_dither; +#endif + +#ifdef MESHLET_MESH_MATERIAL_PASS +#import bevy_pbr::meshlet_visibility_buffer_resolve::resolve_vertex_output +#endif + +#ifdef OIT_ENABLED +#import bevy_core_pipeline::oit::oit_draw +#endif // OIT_ENABLED + +#ifdef FORWARD_DECAL +#import bevy_pbr::decal::forward::get_forward_decal_info +#endif + +#ifdef INSTANCE_FILL +#import bevy_pbr::mesh_functions::get_tag + +// r in the low byte, as `instance_fill` packs it +fn unpack_instance_fill(tag: u32) -> vec4 { + let srgb = vec4( + f32(tag & 0xffu), + f32((tag >> 8u) & 0xffu), + f32((tag >> 16u) & 0xffu), + f32(tag >> 24u), + ) / 255.0; + let linear = select( + pow((srgb.rgb + 0.055) / 1.055, vec3(2.4)), + srgb.rgb / 12.92, + srgb.rgb <= vec3(0.04045), + ); + return vec4(linear, srgb.a); +} +#endif + +@fragment +fn fragment( +#ifdef MESHLET_MESH_MATERIAL_PASS + @builtin(position) frag_coord: vec4, +#else + vertex_output: VertexOutput, + @builtin(front_facing) is_front: bool, +#endif +) -> FragmentOutput { +#ifdef MESHLET_MESH_MATERIAL_PASS + let vertex_output = resolve_vertex_output(frag_coord); + let is_front = true; +#endif + + var in = vertex_output; + + // If we're in the crossfade section of a visibility range, conditionally + // discard the fragment according to the visibility pattern. +#ifdef VISIBILITY_RANGE_DITHER + visibility_range_dither(in.position, in.visibility_range_dither); +#endif + +#ifdef FORWARD_DECAL + let forward_decal_info = get_forward_decal_info(in); + in.world_position = forward_decal_info.world_position; + in.uv = forward_decal_info.uv; +#endif + + // generate a PbrInput struct from the StandardMaterial bindings + var pbr_input = pbr_input_from_standard_material(in, is_front); + +#ifdef INSTANCE_FILL + pbr_input.material.base_color *= unpack_instance_fill(get_tag(in.instance_index)); +#endif + + // alpha discard + pbr_input.material.base_color = alpha_discard(pbr_input.material, pbr_input.material.base_color); + + // clustered decals + apply_decals(&pbr_input); + +#ifdef PREPASS_PIPELINE + // write the gbuffer, lighting pass id, and optionally normal and motion_vector textures + let out = deferred_output(in, pbr_input); +#else + // in forward mode, we calculate the lit color immediately, and then apply some post-lighting effects here. + // in deferred mode the lit color and these effects will be calculated in the deferred lighting shader + var out: FragmentOutput; + if (pbr_input.material.flags & STANDARD_MATERIAL_FLAGS_UNLIT_BIT) == 0u { + out.color = apply_pbr_lighting(pbr_input); + } else { + out.color = pbr_input.material.base_color; + } + + // apply in-shader post processing (fog, alpha-premultiply, and also tonemapping, debanding if the camera is non-hdr) + // note this does not include fullscreen postprocessing effects like bloom. + out.color = main_pass_post_lighting_processing(pbr_input, out.color); +#endif + +#ifdef OIT_ENABLED + let alpha_mode = pbr_input.material.flags & pbr_types::STANDARD_MATERIAL_FLAGS_ALPHA_MODE_RESERVED_BITS; + if alpha_mode != pbr_types::STANDARD_MATERIAL_FLAGS_ALPHA_MODE_OPAQUE { + // The fragments will only be drawn during the oit resolve pass. + oit_draw(in.position, out.color); + discard; + } +#endif // OIT_ENABLED + +#ifdef FORWARD_DECAL + out.color.a = min(forward_decal_info.alpha, out.color.a); +#endif + + return out; +} diff --git a/crates/processing_render/src/particles/material.rs b/crates/processing_render/src/particles/material.rs index 273880c0..ca8d0f4e 100644 --- a/crates/processing_render/src/particles/material.rs +++ b/crates/processing_render/src/particles/material.rs @@ -1,6 +1,5 @@ use std::ops::Deref; -use bevy::asset::embedded_asset; use bevy::material::specialize::SpecializedMeshPipelineError; use bevy::pbr::{ ExtendedMaterial, MaterialExtension, MaterialExtensionKey, MaterialExtensionPipeline, @@ -16,11 +15,13 @@ use bevy::shader::ShaderRef; use crate::render::material::UntypedMaterial; +const SHADER: Handle = bevy::asset::uuid_handle!("3d9e5a17-64c2-4b8f-a0d1-7e5c93f2b684"); + pub struct ParticlesMaterialPlugin; impl Plugin for ParticlesMaterialPlugin { fn build(&self, app: &mut App) { - embedded_asset!(app, "particles.wgsl"); + crate::internal_shader!(app, SHADER, "particles.wgsl"); app.add_plugins(MaterialPlugin::::default()); } } @@ -53,11 +54,11 @@ pub struct ParticlesExtension { impl MaterialExtension for ParticlesExtension { fn fragment_shader() -> ShaderRef { - "embedded://processing_render/particles/particles.wgsl".into() + SHADER.into() } fn deferred_fragment_shader() -> ShaderRef { - "embedded://processing_render/particles/particles.wgsl".into() + SHADER.into() } fn specialize( @@ -79,13 +80,16 @@ impl MaterialExtension for ParticlesExtension { } } -pub fn add_particles_materials(mut commands: Commands, meshes: Query<(Entity, &UntypedMaterial)>) { +pub fn add_particles_materials( + mut commands: Commands, + meshes: Query<(Entity, &UntypedMaterial), Changed>, +) { for (entity, handle) in meshes.iter() { let handle = handle.deref().clone(); - if let Ok(handle) = handle.try_typed::() { - commands - .entity(entity) - .insert(MeshMaterial3d::(handle)); - } + let mut entity = commands.entity(entity); + match handle.try_typed::() { + Ok(handle) => entity.insert(MeshMaterial3d::(handle)), + Err(_) => entity.remove::>(), + }; } } diff --git a/crates/processing_render/src/particles/pack.rs b/crates/processing_render/src/particles/pack.rs index 0d844113..2c77313e 100644 --- a/crates/processing_render/src/particles/pack.rs +++ b/crates/processing_render/src/particles/pack.rs @@ -171,7 +171,7 @@ fn shader_defs_for(key: PackPipelineKey) -> Vec { fn get_or_create_pipeline( pipelines: &mut ParticlesPackPipelines, - pipeline_cache: &PipelineCache, + pipeline_cache: &mut PipelineCache, shader: &Handle, key: PackPipelineKey, ) -> CachedComputePipelineId { @@ -206,6 +206,8 @@ fn get_or_create_pipeline( pipeline, }, ); + // compile before the first draw, or that frame skips these particles + pipeline_cache.process_queue(); pipelines.by_key.get(&key).unwrap().pipeline } @@ -261,7 +263,7 @@ fn extract_particles_draws( fn prepare_pack_bind_groups( shader: Res, mut pipelines: ResMut, - pipeline_cache: Res, + mut pipeline_cache: ResMut, extracted: Res, reservations: Res, batched_instance_buffers: Res>, @@ -305,7 +307,7 @@ fn prepare_pack_bind_groups( } let pipeline_id = - get_or_create_pipeline(&mut pipelines, &pipeline_cache, &shader.0, data.key); + get_or_create_pipeline(&mut pipelines, &mut pipeline_cache, &shader.0, data.key); if !matches!( pipeline_cache.get_compute_pipeline_state(pipeline_id), CachedPipelineState::Ok(_) diff --git a/crates/processing_render/src/particles/point_render.rs b/crates/processing_render/src/particles/point_render.rs index b5483e8d..79f10bd2 100644 --- a/crates/processing_render/src/particles/point_render.rs +++ b/crates/processing_render/src/particles/point_render.rs @@ -1,4 +1,3 @@ -use bevy::asset::embedded_asset; use bevy::camera::visibility::{self, VisibilityClass}; use bevy::core_pipeline::core_3d::{ CORE_3D_DEPTH_FORMAT, Opaque3d, Opaque3dBatchSetKey, Opaque3dBinKey, Transparent3d, @@ -42,11 +41,13 @@ use crate::geometry::Topology; const SURFACE_FORMAT: TextureFormat = TextureFormat::Rgba16Float; +const SHADER: Handle = bevy::asset::uuid_handle!("e27c1f90-5ab3-4d6e-b148-9f03c6d7a251"); + pub struct ParticlesPointRenderPlugin; impl Plugin for ParticlesPointRenderPlugin { fn build(&self, app: &mut App) { - embedded_asset!(app, "point.wgsl"); + crate::internal_shader!(app, SHADER, "point.wgsl"); app.add_plugins(ExtractComponentPlugin::::default()); let Some(render_app) = app.get_sub_app_mut(RenderApp) else { @@ -154,9 +155,7 @@ impl Specializer for RasterSpecializer { impl FromWorld for ParticleRasterPipeline { fn from_world(world: &mut World) -> Self { let render_device = world.resource::().clone(); - let asset_server = world.resource::(); - let shader: Handle = - asset_server.load("embedded://processing_render/particles/point.wgsl"); + let shader = SHADER; let view_entries: Vec<_> = BindGroupLayoutEntries::single( ShaderStages::VERTEX, diff --git a/crates/processing_render/src/render/command.rs b/crates/processing_render/src/render/command.rs index 054b5677..4dee737f 100644 --- a/crates/processing_render/src/render/command.rs +++ b/crates/processing_render/src/render/command.rs @@ -603,10 +603,8 @@ pub enum DrawCommand { h: f32, }, Line { - x1: f32, - y1: f32, - x2: f32, - y2: f32, + from: Vec3, + to: Vec3, }, Triangle { x1: f32, @@ -627,8 +625,7 @@ pub enum DrawCommand { y4: f32, }, Point { - x: f32, - y: f32, + at: Vec3, }, Arc { cx: f32, @@ -684,6 +681,8 @@ pub enum DrawCommand { }, /// The normal of the vertices that follow in this shape. ShapeNormal(Vec3), + /// Whether stroke weight is in world units and shrinks with distance. + StrokePerspective(bool), TextureMode(TextureMode), BeginContour, EndContour, diff --git a/crates/processing_render/src/render/line.rs b/crates/processing_render/src/render/line.rs index 7fc4d137..c1612c36 100644 --- a/crates/processing_render/src/render/line.rs +++ b/crates/processing_render/src/render/line.rs @@ -1,9 +1,9 @@ //! Strokes in 3D: line segments drawn as camera-facing capsules by one material. use bevy::asset::RenderAssetUsages; -use bevy::asset::embedded_asset; use bevy::material::descriptor::RenderPipelineDescriptor; use bevy::material::specialize::SpecializedMeshPipelineError; +use bevy::math::Affine3A; use bevy::mesh::{Indices, MeshVertexAttribute, MeshVertexBufferLayoutRef, PrimitiveTopology}; use bevy::pbr::{Material, MaterialPipeline, MaterialPipelineKey, MaterialPlugin}; use bevy::prelude::*; @@ -22,30 +22,44 @@ pub const ATTRIBUTE_LINE_PARAMS: MeshVertexAttribute = pub const ATTRIBUTE_OTHER_COLOR: MeshVertexAttribute = MeshVertexAttribute::new("Line_OtherColor", 742_915_303, VertexFormat::Float32x4); -const SHADER: &str = "embedded://processing_render/render/line.wgsl"; +const SHADER: Handle = bevy::asset::uuid_handle!("b0a4c6d2-7e19-4f38-8d65-1c9e2a7f5b43"); pub struct LineMaterialPlugin; impl Plugin for LineMaterialPlugin { fn build(&self, app: &mut App) { - embedded_asset!(app, "line.wgsl"); + crate::internal_shader!(app, SHADER, "line.wgsl"); app.add_plugins(MaterialPlugin::::default()); let mut materials = app.world_mut().resource_mut::>(); + let mut add = + |blended, perspective| materials.add(LineMaterial::new(blended, None, perspective)); let handles = LineMaterials { - opaque: materials.add(LineMaterial::new(false, None)), - blended: materials.add(LineMaterial::new(true, None)), + screen: [add(false, false), add(true, false)], + perspective: [add(false, true), add(true, true)], }; app.insert_resource(handles); } } -/// The materials strokes share when no blend mode is set. +/// The materials strokes share, as (opaque, translucent) pairs. #[derive(Resource)] pub struct LineMaterials { - pub opaque: Handle, - /// for strokes with a translucent color - pub blended: Handle, + /// weight in pixels + screen: [Handle; 2], + /// weight in world units, shrinking with distance + perspective: [Handle; 2], +} + +impl LineMaterials { + pub fn get(&self, blended: bool, perspective: bool) -> Handle { + let pair = if perspective { + &self.perspective + } else { + &self.screen + }; + pair[blended as usize].clone() + } } #[derive(Clone, Copy, Debug, ShaderType)] @@ -82,10 +96,10 @@ impl From<&LineMaterial> for LineMaterialKey { } impl LineMaterial { - pub fn new(blended: bool, blend_state: Option) -> Self { + pub fn new(blended: bool, blend_state: Option, perspective: bool) -> Self { Self { uniform: LineUniform { - perspective: 0, + perspective: perspective as u32, depth_bias: 1e-3, }, blended, @@ -225,17 +239,48 @@ impl Segments { pub struct LineMesh { opaque: Segments, blended: Segments, - /// physical pixels per unit of stroke weight + /// physical pixels per logical pixel of the graphics + pixel_density: f32, + /// weights are in world units instead of pixels + perspective: bool, + /// the matrix baked into segments as they are added + transform: Affine3A, + /// stroke weight multiplier, set by `set_transform` weight_scale: f32, + /// rough physical pixels per local unit, for flattening curves + pixels_per_unit: f32, } impl LineMesh { - pub fn new(weight_scale: f32) -> Self { - Self { + /// Strokes for a graphics of `pixel_density`. + pub fn new(pixel_density: f32, perspective: bool) -> Self { + let mut mesh = Self { opaque: Segments::default(), blended: Segments::default(), - weight_scale, - } + pixel_density, + perspective, + transform: Affine3A::IDENTITY, + weight_scale: 1.0, + pixels_per_unit: 1.0, + }; + mesh.set_transform(Affine3A::IDENTITY, 1.0); + mesh + } + + /// Sets the matrix for the segments that follow. + pub fn set_transform(&mut self, transform: Affine3A, matrix_scale: f32) { + self.transform = transform; + self.weight_scale = if self.perspective { + matrix_scale + } else { + matrix_scale * self.pixel_density + }; + self.pixels_per_unit = matrix_scale * self.pixel_density; + } + + /// How far a flattened curve may stray from the true one: a quarter of a physical pixel. + pub fn flatten_tolerance(&self) -> f32 { + (0.25 / self.pixels_per_unit).clamp(1e-4, 10.0) } pub fn is_empty(&self) -> bool { @@ -261,7 +306,11 @@ impl LineMesh { } else { &mut self.opaque }; - segments.push(start, finish, self.weight_scale); + let place = |end: LineEnd| LineEnd { + position: self.transform.transform_point3(end.position), + ..end + }; + segments.push(place(start), place(finish), self.weight_scale); } /// A dot as wide as its weight. diff --git a/crates/processing_render/src/render/material.rs b/crates/processing_render/src/render/material.rs index 45809290..bf4d615c 100644 --- a/crates/processing_render/src/render/material.rs +++ b/crates/processing_render/src/render/material.rs @@ -2,6 +2,7 @@ use bevy::math::Affine2; use bevy::pbr::ExtendedMaterial; use bevy::prelude::*; use bevy::render::render_resource::BlendState; +use std::hash::{Hash, Hasher}; use std::ops::Deref; use crate::material::ProcessingMaterial; @@ -39,6 +40,56 @@ pub enum MaterialKey { }, } +// float fields: a NaN or -0.0 key only misses the cache +impl Eq for MaterialKey {} + +impl Hash for MaterialKey { + fn hash(&self, state: &mut H) { + std::mem::discriminant(self).hash(state); + match self { + MaterialKey::Color { + transparent, + background_image, + uv_transform, + blend_state, + } => { + transparent.hash(state); + background_image.hash(state); + uv_transform.to_cols_array().map(f32::to_bits).hash(state); + blend_state.hash(state); + } + MaterialKey::Pbr { + albedo, + roughness, + metallic, + emissive, + base_color_texture, + uv_transform, + blend_state, + transparent, + two_sided, + } => { + albedo.hash(state); + roughness.hash(state); + metallic.hash(state); + emissive.hash(state); + base_color_texture.hash(state); + uv_transform.to_cols_array().map(f32::to_bits).hash(state); + blend_state.hash(state); + transparent.hash(state); + two_sided.hash(state); + } + MaterialKey::Custom { + entity, + blend_state, + } => { + entity.hash(state); + blend_state.hash(state); + } + } + } +} + pub struct PbrFields { pub albedo: [u8; 4], pub roughness: u8, @@ -197,6 +248,24 @@ impl MaterialKey { } } + /// Whether the material is drawn in the blended phase. + pub fn is_blended(&self) -> bool { + match self { + MaterialKey::Color { + transparent, + blend_state, + .. + } => *transparent || blend_state.is_some(), + MaterialKey::Pbr { + albedo, + transparent, + blend_state, + .. + } => *transparent || albedo[3] < 255 || blend_state.is_some(), + MaterialKey::Custom { blend_state, .. } => blend_state.is_some(), + } + } + pub fn blend_state(&self) -> Option { match self { MaterialKey::Color { blend_state, .. } => *blend_state, @@ -282,26 +351,38 @@ impl MaterialKey { extension: ProcessingMaterial { blend_state, depth_write: None, + instance_fill: false, }, }; materials.add(extended).untyped() } } -pub fn add_processing_materials(mut commands: Commands, meshes: Query<(Entity, &UntypedMaterial)>) { +/// Syncs an entity's typed material component with its `UntypedMaterial`. +pub fn add_processing_materials( + mut commands: Commands, + meshes: Query<(Entity, &UntypedMaterial), Changed>, +) { for (entity, handle) in meshes.iter() { let handle = handle.deref().clone(); - if let Ok(handle) = handle.try_typed::() { - commands.entity(entity).insert(MeshMaterial3d(handle)); - } + let mut entity = commands.entity(entity); + match handle.try_typed::() { + Ok(handle) => entity.insert(MeshMaterial3d(handle)), + Err(_) => entity.remove::>(), + }; } } -pub fn add_custom_materials(mut commands: Commands, meshes: Query<(Entity, &UntypedMaterial)>) { +pub fn add_custom_materials( + mut commands: Commands, + meshes: Query<(Entity, &UntypedMaterial), Changed>, +) { for (entity, handle) in meshes.iter() { let handle = handle.deref().clone(); - if let Ok(handle) = handle.try_typed::() { - commands.entity(entity).insert(CustomMaterial3d(handle)); - } + let mut entity = commands.entity(entity); + match handle.try_typed::() { + Ok(handle) => entity.insert(CustomMaterial3d(handle)), + Err(_) => entity.remove::(), + }; } } diff --git a/crates/processing_render/src/render/mod.rs b/crates/processing_render/src/render/mod.rs index 249874d8..d1b15766 100644 --- a/crates/processing_render/src/render/mod.rs +++ b/crates/processing_render/src/render/mod.rs @@ -3,6 +3,7 @@ pub mod filter; pub mod line; pub mod material; pub mod mesh_builder; +pub mod pool; pub mod primitive; pub mod style; pub mod transform; @@ -18,19 +19,20 @@ use bevy::{ math::{Affine2, Affine3A, Vec3A}, mesh::PrimitiveTopology, pbr::gpu_instance_batch::GpuBatchedMesh3d, - pbr::wireframe::{Wireframe, WireframeColor, WireframeLineWidth, WireframeTopology}, + pbr::wireframe::{WireframeMaterial, WireframeTopology}, prelude::*, render::render_resource::BlendState, window::WindowRef, }; use command::{CommandBuffer, DrawCommand, ShapeMode, TextureMode}; -use line::{LineMaterial, LineMaterials, LineMesh}; +use line::{LineEnd, LineMaterial, LineMaterials, LineMesh}; use material::{MaterialKey, ProcessingExtendedMaterial}; +use pool::{DrawCaches, DrawPool, MaterialDesc, PooledDraw, ShapeKey, WireframeKey}; use primitive::{ - ShapeBuilder, TessellationMode, VertexStyle, VertexType, arc_fill, arc_stroke, bezier, - box_mesh, build_shape_fill, build_shape_lines, build_shape_stroke, capsule_mesh, cone_mesh, - conical_frustum_mesh, curve, cylinder_mesh, ellipse, empty_mesh, line, plane_mesh, quad, - sphere_mesh, tetrahedron_mesh, torus_mesh, triangle, + PathSink, ShapeBuilder, TessellationMode, VertexStyle, VertexType, arc_fill, arc_stroke, + bake_transform, bezier, box_mesh, build_shape_fill, build_shape_lines, build_shape_stroke, + capsule_mesh, cone_mesh, conical_frustum_mesh, curve, cylinder_mesh, ellipse, empty_mesh, line, + plane_mesh, quad, sphere_mesh, tetrahedron_mesh, torus_mesh, triangle, }; use style::{Fill, StyleStack}; use transform::TransformStack; @@ -76,6 +78,7 @@ pub struct RenderResources<'w, 's> { custom_materials: ResMut<'w, Assets>, line_materials: Res<'w, LineMaterials>, line_material_assets: ResMut<'w, Assets>, + wireframe_materials: ResMut<'w, Assets>, canvas_sizes: Query< 'w, 's, @@ -92,17 +95,16 @@ struct BatchState { current_mesh: Option, lines: Option, material_key: Option, - transform: Affine3A, draw_index: u32, render_layers: RenderLayers, graphics_entity: Entity, } -/// Camera-facing strokes that share a transform and a blend mode. +/// Camera-facing strokes that share a blend mode and stroke perspective. struct LineBatch { mesh: LineMesh, - transform: Affine3A, blend_state: Option, + perspective: bool, } impl BatchState { @@ -111,7 +113,6 @@ impl BatchState { current_mesh: None, lines: None, material_key: None, - transform: Affine3A::IDENTITY, draw_index: 0, render_layers, graphics_entity, @@ -182,6 +183,8 @@ pub struct RenderState { pub shape_normal: Option, /// outside the style stack, like P3D pub texture_mode: TextureMode, + /// stroke weight is in world units instead of pixels + pub stroke_perspective: bool, } impl RenderState { @@ -194,6 +197,7 @@ impl RenderState { three_d: false, shape_normal: None, texture_mode: TextureMode::default(), + stroke_perspective: false, } } @@ -204,6 +208,7 @@ impl RenderState { self.three_d = false; self.shape_normal = None; self.texture_mode = TextureMode::default(); + self.stroke_perspective = false; } pub fn begin_frame(&mut self) { @@ -248,9 +253,12 @@ pub fn flush_draw_commands( &mut crate::image::BackgroundBlit, Has, Option<&RenderTarget>, + &mut DrawPool, + &crate::color::ColorMode, ), With, >, + mut caches: Local, p_windows: Query<&Window>, p_images: Query<&Image>, p_geometries: Query<(&Geometry, Option<&GltfNodeTransform>)>, @@ -279,8 +287,17 @@ pub fn flush_draw_commands( mut background_blit, presents, target, + mut pool, + color_mode, ) in graphics.iter_mut() { + pool.begin(&mut res.commands, render_layers); + let mut draws = MeshDraws { + pool: &mut pool, + caches: &mut caches, + // in LINEAR color mode an inexact fill stays in the material + quantize_fill: !matches!(color_mode.space, crate::color::ColorSpace::Linear), + }; // an opaque window ignores background alpha let opaque_window = matches!( target, @@ -304,9 +321,9 @@ pub fn flush_draw_commands( } } - let draw_commands = std::mem::take(&mut cmd_buffer.commands); + let mut draw_commands = std::mem::take(&mut cmd_buffer.commands); let mut batch = BatchState::new(graphics_entity, render_layers.clone()); - let mut pending = draw_commands.into_iter(); + let mut pending = draw_commands.drain(..); let mut drained = true; while let Some(cmd) = pending.next() { @@ -396,6 +413,9 @@ pub fn flush_draw_commands( DrawCommand::TextureMode(mode) => { state.texture_mode = mode; } + DrawCommand::StrokePerspective(perspective) => { + state.stroke_perspective = perspective; + } DrawCommand::NoTexture => { state.style.texture_size = None; match &mut state.style.material_key { @@ -523,17 +543,38 @@ pub fn flush_draw_commands( &p_material_handles, ); } - DrawCommand::Line { x1, y1, x2, y2 } => { - let stroke_config = state.style.stroke_config; - add_stroke( - &mut res, - &mut batch, - &state, - |mesh, color, weight| { - line(mesh, x1, y1, x2, y2, color, weight, &stroke_config) - }, - &p_material_handles, - ); + DrawCommand::Line { from, to } => { + if state.three_d || from.z != 0.0 || to.z != 0.0 { + // a line in space faces the camera + if let Some((color, weight)) = state.style.stroke() { + let end = |position| LineEnd { + position, + color, + weight, + }; + line_batch(&mut res, &mut batch, &state).segment(end(from), end(to)); + } + } else { + let stroke_config = state.style.stroke_config; + add_stroke( + &mut res, + &mut batch, + &state, + |sink, color, weight| { + line( + sink, + from.x, + from.y, + to.x, + to.y, + color, + weight, + &stroke_config, + ) + }, + &p_material_handles, + ); + } } DrawCommand::Triangle { x1, @@ -643,33 +684,39 @@ pub fn flush_draw_commands( &p_material_handles, ); } - DrawCommand::Point { x, y } => { - if let Some((color, d)) = state.style.stroke() - && let Some(material_key) = material_key_with_colors(&state, &[color]) - { - if needs_batch(&batch, &state, &material_key) { - start_batch( - &mut res, - &mut batch, - &state, - material_key, - &p_material_handles, - ); - } - - if let Some(ref mut mesh) = batch.current_mesh { - let stroke_config = state.style.stroke_config; - ellipse( - mesh, - x, - y, - d, - d, + DrawCommand::Point { at } => { + if state.three_d || at.z != 0.0 { + // a point in space is a dot that faces the camera + if let Some((color, weight)) = state.style.stroke() { + line_batch(&mut res, &mut batch, &state).point(LineEnd { + position: at, color, - TessellationMode::Fill, - &stroke_config, - ); + weight, + }); } + } else if let Some((color, d)) = state.style.stroke() + && let Some(material_key) = material_key_with_colors(&state, &[color]) + { + let stroke_config = state.style.stroke_config; + batch_write( + &mut res, + &mut batch, + &state, + material_key, + &p_material_handles, + |mesh| { + ellipse( + mesh, + at.x, + at.y, + d, + d, + color, + TessellationMode::Fill, + &stroke_config, + ) + }, + ); } } DrawCommand::Arc { @@ -839,12 +886,14 @@ pub fn flush_draw_commands( { // a lit shape in space is lit on both faces let key = if in_space { key.two_sided() } else { key }; - if needs_batch(&batch, &state, &key) { - start_batch(&mut res, &mut batch, &state, key, &p_material_handles); - } - if let Some(ref mut mesh) = batch.current_mesh { - build_shape_fill(mesh, &sb, close, in_space, matrix_scale); - } + batch_write( + &mut res, + &mut batch, + &state, + key, + &p_material_handles, + |mesh| build_shape_fill(mesh, &sb, close, in_space, matrix_scale), + ); } if state.style.stroke_color.is_some() && in_space { @@ -858,12 +907,14 @@ pub fn flush_draw_commands( } else if state.style.stroke_color.is_some() && let Some(key) = material_key_with_colors(&state, &sb.stroke_colors()) { - if needs_batch(&batch, &state, &key) { - start_batch(&mut res, &mut batch, &state, key, &p_material_handles); - } - if let Some(ref mut mesh) = batch.current_mesh { - build_shape_stroke(mesh, &sb, close, &stroke_config); - } + batch_write( + &mut res, + &mut batch, + &state, + key, + &p_material_handles, + |mesh| build_shape_stroke(mesh, &sb, close, &stroke_config), + ); } } } @@ -919,33 +970,32 @@ pub fn flush_draw_commands( let stroke_config = state.style.stroke_config; flush_batch(&mut res, &mut batch, &p_material_handles); - start_batch( + batch_write( &mut res, &mut batch, &state, material_key, &p_material_handles, + |mesh| { + rect( + mesh, + x, + y, + w, + h, + [0.0; 4], + tint, + TessellationMode::Fill, + &stroke_config, + ) + }, ); - - if let Some(ref mut mesh) = batch.current_mesh { - rect( - mesh, - x, - y, - w, - h, - [0.0; 4], - tint, - TessellationMode::Fill, - &stroke_config, - ); - } - flush_batch(&mut res, &mut batch, &p_material_handles); } DrawCommand::BackgroundColor(color) => { if !opens_pass(&batch) { - cmd_buffer.commands = std::iter::once(cmd).chain(pending).collect(); + cmd_buffer.commands = + std::iter::once(cmd).chain(pending.by_ref()).collect(); drained = false; break; } @@ -963,7 +1013,8 @@ pub fn flush_draw_commands( continue; }; if !opens_pass(&batch) { - cmd_buffer.commands = std::iter::once(cmd).chain(pending).collect(); + cmd_buffer.commands = + std::iter::once(cmd).chain(pending.by_ref()).collect(); drained = false; break; } @@ -1012,6 +1063,7 @@ pub fn flush_draw_commands( &mut res, &mut batch, &state, + &mut draws, Mesh3dDraw { mesh: geometry.handle.clone(), translucent: geometry.translucent, @@ -1221,7 +1273,16 @@ pub fn flush_draw_commands( &mut res, &mut batch, &state, - box_mesh(width, height, depth), + &mut draws, + ShapeKey::Box, + Vec3::new(width, height, depth), + |unit| { + if unit { + box_mesh(1.0, 1.0, 1.0) + } else { + box_mesh(width, height, depth) + } + }, &p_material_handles, ); } @@ -1234,7 +1295,16 @@ pub fn flush_draw_commands( &mut res, &mut batch, &state, - sphere_mesh(radius, sectors, stacks), + &mut draws, + ShapeKey::Sphere { sectors, stacks }, + Vec3::splat(radius), + |unit| { + if unit { + sphere_mesh(1.0, sectors, stacks) + } else { + sphere_mesh(radius, sectors, stacks) + } + }, &p_material_handles, ); } @@ -1247,7 +1317,16 @@ pub fn flush_draw_commands( &mut res, &mut batch, &state, - cylinder_mesh(radius, height, detail), + &mut draws, + ShapeKey::Cylinder { detail }, + Vec3::new(radius, height, radius), + |unit| { + if unit { + cylinder_mesh(1.0, 1.0, detail) + } else { + cylinder_mesh(radius, height, detail) + } + }, &p_material_handles, ); } @@ -1260,7 +1339,16 @@ pub fn flush_draw_commands( &mut res, &mut batch, &state, - cone_mesh(radius, height, detail), + &mut draws, + ShapeKey::Cone { detail }, + Vec3::new(radius, height, radius), + |unit| { + if unit { + cone_mesh(1.0, 1.0, detail) + } else { + cone_mesh(radius, height, detail) + } + }, &p_material_handles, ); } @@ -1270,11 +1358,26 @@ pub fn flush_draw_commands( major_segments, minor_segments, } => { + // the tube's share of the radius shapes the mesh; the radius scales it + let tube = tube_radius / radius; add_shape3d( &mut res, &mut batch, &state, - torus_mesh(radius, tube_radius, major_segments, minor_segments), + &mut draws, + ShapeKey::Torus { + tube: tube.to_bits(), + major: major_segments, + minor: minor_segments, + }, + Vec3::splat(radius), + |unit| { + if unit { + torus_mesh(1.0, tube, major_segments, minor_segments) + } else { + torus_mesh(radius, tube_radius, major_segments, minor_segments) + } + }, &p_material_handles, ); } @@ -1283,7 +1386,16 @@ pub fn flush_draw_commands( &mut res, &mut batch, &state, - plane_mesh(width, height), + &mut draws, + ShapeKey::Plane, + Vec3::new(width, 1.0, height), + |unit| { + if unit { + plane_mesh(1.0, 1.0) + } else { + plane_mesh(width, height) + } + }, &p_material_handles, ); } @@ -1292,11 +1404,24 @@ pub fn flush_draw_commands( length, detail, } => { + let unit_length = length / radius; add_shape3d( &mut res, &mut batch, &state, - capsule_mesh(radius, length, detail), + &mut draws, + ShapeKey::Capsule { + length: unit_length.to_bits(), + detail, + }, + Vec3::splat(radius), + |unit| { + if unit { + capsule_mesh(1.0, unit_length, detail) + } else { + capsule_mesh(radius, length, detail) + } + }, &p_material_handles, ); } @@ -1306,11 +1431,24 @@ pub fn flush_draw_commands( height, detail, } => { + let top = radius_top / radius_bottom; add_shape3d( &mut res, &mut batch, &state, - conical_frustum_mesh(radius_top, radius_bottom, height, detail), + &mut draws, + ShapeKey::ConicalFrustum { + top: top.to_bits(), + detail, + }, + Vec3::new(radius_bottom, height, radius_bottom), + |unit| { + if unit { + conical_frustum_mesh(top, 1.0, 1.0, detail) + } else { + conical_frustum_mesh(radius_top, radius_bottom, height, detail) + } + }, &p_material_handles, ); } @@ -1319,7 +1457,16 @@ pub fn flush_draw_commands( &mut res, &mut batch, &state, - tetrahedron_mesh(radius), + &mut draws, + ShapeKey::Tetrahedron, + Vec3::splat(radius), + |unit| { + if unit { + tetrahedron_mesh(1.0) + } else { + tetrahedron_mesh(radius) + } + }, &p_material_handles, ); } @@ -1414,8 +1561,15 @@ pub fn flush_draw_commands( } } + drop(pending); + if drained { + // keep the allocation for the next frame + cmd_buffer.commands = draw_commands; + } + flush_batch(&mut res, &mut batch, &p_material_handles); flush_lines(&mut res, &mut batch); + draws.pool.end(&mut res.commands); // a pass cut short by a mid-frame `background()` is wiped by the next one, so it // must not reach the window @@ -1428,6 +1582,7 @@ pub fn flush_draw_commands( CameraOutputMode::Skip }; } + caches.end_flush(); } pub fn activate_cameras(mut cameras: Query<(&mut Camera, Option<&Flush>)>) { @@ -1461,12 +1616,8 @@ fn spawn_mesh( let mesh_handle = res.meshes.add(mesh); - let (scale, rotation, translation) = batch.transform.to_scale_rotation_translation(); - let transform = Transform { - translation: translation + Vec3::new(0.0, 0.0, z_offset), - rotation, - scale, - }; + // the matrix is baked into the vertices + let transform = Transform::from_xyz(0.0, 0.0, z_offset); let material_handle = match key { MaterialKey::Custom { @@ -1493,24 +1644,42 @@ fn spawn_mesh( fn needs_batch(batch: &BatchState, state: &RenderState, material_key: &MaterialKey) -> bool { let material_changed = batch.material_key.as_ref() != Some(material_key); - let transform_changed = batch.transform != state.transform.current(); let requires_separate_draws = state.style.blend_state.is_some(); - material_changed || transform_changed || requires_separate_draws + material_changed || requires_separate_draws } fn start_batch( res: &mut RenderResources, batch: &mut BatchState, - state: &RenderState, material_key: MaterialKey, material_handles: &Query<&UntypedMaterial>, ) { flush_batch(res, batch, material_handles); batch.material_key = Some(material_key); - batch.transform = state.transform.current(); batch.current_mesh = Some(empty_mesh()); } +/// Appends geometry to the batch mesh for `material_key`, baking in the current matrix. +fn batch_write( + res: &mut RenderResources, + batch: &mut BatchState, + state: &RenderState, + material_key: MaterialKey, + material_handles: &Query<&UntypedMaterial>, + write: impl FnOnce(&mut Mesh), +) { + if needs_batch(batch, state, &material_key) { + start_batch(res, batch, material_key, material_handles); + } + let Some(mesh) = batch.current_mesh.as_mut() else { + return; + }; + let first_vertex = mesh.count_vertices(); + let first_index = mesh.indices().map_or(0, |indices| indices.len()); + write(mesh); + bake_transform(mesh, first_vertex, first_index, state.transform.current()); +} + fn apply_shape_mode(mode: ShapeMode, a: f32, b: f32, c: f32, d: f32) -> (f32, f32, f32, f32) { match mode { ShapeMode::Corner => (a, b, c, d), @@ -1666,24 +1835,34 @@ fn add_fill( return; }; - if needs_batch(batch, state, &material_key) { - start_batch(res, batch, state, material_key, material_handles); - } - - if let Some(ref mut mesh) = batch.current_mesh { - tessellate(mesh, color); - } + batch_write(res, batch, state, material_key, material_handles, |mesh| { + tessellate(mesh, color) + }); } +/// Strokes a primitive: a ribbon in its plane in 2D mode, camera-facing segments in 3D mode. fn add_stroke( res: &mut RenderResources, batch: &mut BatchState, state: &RenderState, - tessellate: impl FnOnce(&mut Mesh, Color, f32), + tessellate: impl FnOnce(&mut dyn PathSink, Color, f32), material_handles: &Query<&UntypedMaterial>, ) { + if state.three_d { + if let Some((color, weight)) = state.style.stroke() { + tessellate(line_batch(res, batch, state), color, weight); + } + return; + } let weight = state.style.stroke_weight; - add_stroke_weighted(res, batch, state, weight, tessellate, material_handles); + add_stroke_weighted( + res, + batch, + state, + weight, + |mesh, color, weight| tessellate(mesh, color, weight), + material_handles, + ); } /// A stroke in the current stroke color at `stroke_weight`; a weight of zero draws nothing. @@ -1706,13 +1885,9 @@ fn add_stroke_weighted( return; }; - if needs_batch(batch, state, &material_key) { - start_batch(res, batch, state, material_key, material_handles); - } - - if let Some(ref mut mesh) = batch.current_mesh { - tessellate(mesh, color, stroke_weight); - } + batch_write(res, batch, state, material_key, material_handles, |mesh| { + tessellate(mesh, color, stroke_weight) + }); } /// How much a matrix scales lengths: the cube root of its volume scale. @@ -1720,7 +1895,7 @@ fn matrix_scale(transform: Affine3A) -> f32 { transform.matrix3.determinant().abs().cbrt() } -/// The line mesh strokes are appended to. +/// The line mesh strokes are appended to under the current matrix. fn line_batch<'a>( res: &mut RenderResources, batch: &'a mut BatchState, @@ -1728,10 +1903,11 @@ fn line_batch<'a>( ) -> &'a mut LineMesh { let transform = state.transform.current(); let blend_state = state.style.blend_state; + let perspective = state.stroke_perspective; if batch .lines .as_ref() - .is_some_and(|lines| lines.transform != transform || lines.blend_state != blend_state) + .is_some_and(|lines| lines.blend_state != blend_state || lines.perspective != perspective) { flush_lines(res, batch); } @@ -1743,15 +1919,13 @@ fn line_batch<'a>( logical.map(|size| graphics.size.width as f32 / size.0.max(1) as f32) }) .unwrap_or(1.0); - let transform_scale = matrix_scale(transform); - &mut batch - .lines - .get_or_insert_with(|| LineBatch { - mesh: LineMesh::new(pixel_density * transform_scale), - transform, - blend_state, - }) - .mesh + let lines = batch.lines.get_or_insert_with(|| LineBatch { + mesh: LineMesh::new(pixel_density, perspective), + blend_state, + perspective, + }); + lines.mesh.set_transform(transform, matrix_scale(transform)); + &mut lines.mesh } /// Spawns the accumulated strokes. @@ -1763,25 +1937,22 @@ fn flush_lines(res: &mut RenderResources, batch: &mut BatchState) { return; } // layered at flush, above the fills batched so far - let (scale, rotation, translation) = lines.transform.to_scale_rotation_translation(); - let transform = Transform { - translation: translation + Vec3::new(0.0, 0.0, layer_z(batch.draw_index)), - rotation, - scale, - }; + let transform = Transform::from_xyz(0.0, 0.0, layer_z(batch.draw_index)); batch.draw_index += 1; let (opaque, blended) = lines.mesh.build(); let materials = match lines.blend_state { None => [ - res.line_materials.opaque.clone(), - res.line_materials.blended.clone(), + res.line_materials.get(false, lines.perspective), + res.line_materials.get(true, lines.perspective), ], // a blend mode applies to every segment Some(blend_state) => { - let material = res - .line_material_assets - .add(LineMaterial::new(true, Some(blend_state))); + let material = res.line_material_assets.add(LineMaterial::new( + true, + Some(blend_state), + lines.perspective, + )); [material.clone(), material] } }; @@ -1822,22 +1993,46 @@ fn flush_batch( batch.material_key = None; } +/// The pool and caches mesh draws go through. +struct MeshDraws<'a> { + pool: &'a mut DrawPool, + caches: &'a mut DrawCaches, + /// whether a fill may be rounded to 8-bit sRGB to ride in the instance + quantize_fill: bool, +} + +/// Draws a primitive as a shared unit mesh scaled to `size`. +#[allow(clippy::too_many_arguments)] fn add_shape3d( res: &mut RenderResources, batch: &mut BatchState, state: &RenderState, - mesh: Mesh, + draws: &mut MeshDraws, + key: ShapeKey, + size: Vec3, + build: impl FnOnce(bool) -> Mesh, material_handles: &Query<&UntypedMaterial>, ) { - let mesh = res.meshes.add(mesh); + // a zero or non-finite size cannot scale a unit mesh + let scalable = size.is_finite() && size.cmpne(Vec3::ZERO).all(); + let (mesh, local) = if scalable { + let mesh = draws + .caches + .shapes + .get_or_insert_with(key, || res.meshes.add(build(true))); + (mesh, Some(Transform::from_scale(size))) + } else { + (res.meshes.add(build(false)), None) + }; draw_mesh3d( res, batch, state, + draws, Mesh3dDraw { mesh, translucent: false, - local: None, + local, paint: MeshPaint::Surface { edges: Some(WireframeTopology::Quads), }, @@ -1866,11 +2061,41 @@ enum MeshPaint { Lines, } +/// The key and mesh tag for a fill carried per instance as 8-bit sRGB, if it can be. +fn instance_fill(key: MaterialKey, fill: Color, quantize: bool) -> (MaterialKey, Option) { + let srgba = fill.to_srgba(); + let components = srgba.to_f32_array(); + if components.iter().any(|c| !(0.0..=1.0).contains(c)) { + return (key, None); + } + let bytes = srgba.to_u8_array(); + let exact = components + .iter() + .zip(bytes) + .all(|(c, b)| (c - b as f32 / 255.0).abs() < 1e-4); + if !exact && !quantize { + return (key, None); + } + let tag = u32::from_le_bytes(bytes); + match key { + MaterialKey::Color { .. } => (key, Some(tag)), + MaterialKey::Pbr { .. } => { + let mut pbr = key.as_pbr(); + // the tag carries the alpha that chose the phase + pbr.transparent |= pbr.albedo[3] < 255; + pbr.albedo = [255; 4]; + (pbr.into(), Some(tag)) + } + MaterialKey::Custom { .. } => (key, None), + } +} + /// Draws a mesh colored by the current fill and stroke. fn draw_mesh3d( res: &mut RenderResources, batch: &mut BatchState, state: &RenderState, + draws: &mut MeshDraws, draw: Mesh3dDraw, material_handles: &Query<&UntypedMaterial>, ) { @@ -1895,91 +2120,108 @@ fn draw_mesh3d( return; } - let material_handle = match color { - None => None, - Some(color) => Some(match &state.style.material_key { + let (material, tag) = match color { + None => (None, None), + Some(color) => match &state.style.material_key { MaterialKey::Custom { entity, .. } => { let Some(untyped) = material_handles.get(*entity).ok() else { warn!("Custom material entity {:?} not found", entity); return; }; - clone_custom_material_with_blend( + let material = clone_custom_material_with_blend( &mut res.custom_materials, &untyped.0, state.style.blend_state, - ) - } - // TODO: in 2d, we use vertex colors. `to_material` becomes complicated if we also encode - // a base color in the material, so for simplicity we just create a new material here - // that is unlit and uses the fill color as the base color - MaterialKey::Color { - transparent, - background_image, - uv_transform, - .. - } => { - let blended = state.style.blend_state.is_some() - || color.alpha() < 1.0 - || draw.translucent - || *transparent; - let base = StandardMaterial { - base_color: color, - base_color_texture: background_image.clone(), - uv_transform: *uv_transform, - unlit: true, - cull_mode: None, - alpha_mode: if blended { - AlphaMode::Blend - } else { - AlphaMode::Opaque - }, - depth_bias: sort_bias(batch.draw_index), - ..default() - }; - let extended = ProcessingExtendedMaterial { - base, - extension: ProcessingMaterial { - blend_state: state.style.blend_state, - depth_write: None, - }, - }; - res.materials.add(extended).untyped() + ); + (Some(material), None) } - key @ MaterialKey::Pbr { .. } => { - let mut key = material_key_with_color(key, color, state.style.blend_state); - if draw.translucent { + style_key => { + let textured_translucent = matches!( + style_key, + MaterialKey::Color { + transparent: true, + .. + } + ); + let mut key = material_key_with_color(style_key, color, state.style.blend_state); + if draw.translucent || textured_translucent { key = key.transparent(); } - key.to_material(&mut res.materials, sort_bias(batch.draw_index)) + let (key, tag) = instance_fill(key, color, draws.quantize_fill); + // an unlit fill the tag cannot carry goes in the material + let base_color = match (&key, tag) { + (MaterialKey::Color { .. }, None) => Some(color), + _ => None, + }; + // only blended draws need a sort bias + let depth_bias = if key.is_blended() { + sort_bias(batch.draw_index) + } else { + 0.0 + }; + let desc = MaterialDesc { + key: key.clone(), + base_color: base_color.map(|c| c.to_linear().to_f32_array().map(f32::to_bits)), + instance_fill: tag.is_some(), + depth_bias: depth_bias.to_bits(), + }; + let materials = &mut res.materials; + let material = draws.caches.materials.get_or_insert_with(desc, || { + let mut base = key.to_standard_material(); + if let Some(base_color) = base_color { + base.base_color = base_color; + } + base.depth_bias = depth_bias; + materials + .add(ProcessingExtendedMaterial { + base, + extension: ProcessingMaterial { + blend_state: key.blend_state(), + depth_write: None, + instance_fill: tag.is_some(), + }, + }) + .untyped() + }); + (Some(material), tag) } - }), + }, }; + let wireframe = stroke.map(|(topology, (color, weight))| { + let line_width = if draw.hairline { 1.0 } else { weight }; + let key = WireframeKey { + color: color.to_linear().to_f32_array().map(f32::to_bits), + width: line_width.to_bits(), + topology, + }; + let materials = &mut res.wireframe_materials; + draws.caches.wireframes.get_or_insert_with(key, || { + materials.add(WireframeMaterial { + color, + line_width, + topology, + }) + }) + }); + let mut transform = state.transform.to_bevy_transform(); if let Some(local) = draw.local { transform = Transform::from_matrix(transform.to_matrix() * local.to_matrix()); } transform.translation.z += layer_z(batch.draw_index); - let mut entity = res.commands.spawn(( - Mesh3d(draw.mesh), - FlushTransient(batch.graphics_entity), - transform, - batch.render_layers.clone(), - )); - if let Some(material_handle) = material_handle { - entity.insert(UntypedMaterial(material_handle)); - } - if let Some((edges, (color, weight))) = stroke { - entity.insert(( - Wireframe, - WireframeColor { color }, - WireframeLineWidth { - width: if draw.hairline { 1.0 } else { weight }, - }, - edges, - )); - } + draws.pool.draw( + &mut res.commands, + batch.graphics_entity, + PooledDraw { + mesh: draw.mesh, + material, + tag, + wireframe, + transform, + }, + ); batch.draw_index += 1; } diff --git a/crates/processing_render/src/render/pool.rs b/crates/processing_render/src/render/pool.rs new file mode 100644 index 00000000..8e29eb50 --- /dev/null +++ b/crates/processing_render/src/render/pool.rs @@ -0,0 +1,247 @@ +//! Draw entities kept from flush to flush, and the meshes and materials they share. + +use std::hash::Hash; + +use bevy::{ + asset::UntypedAssetId, + camera::visibility::RenderLayers, + mesh::MeshTag, + pbr::wireframe::{Mesh3dWireframe, Wireframe, WireframeMaterial, WireframeTopology}, + platform::collections::HashMap, + prelude::*, +}; + +use super::material::{MaterialKey, UntypedMaterial}; +use crate::material::custom::CustomMaterial3d; +use crate::particles::material::ParticlesMaterial; +use crate::render::material::ProcessingExtendedMaterial; + +/// The graphics that owns a pooled draw entity. +#[derive(Component)] +#[relationship(relationship_target = PooledDraws)] +pub struct PooledDrawOf(pub Entity); + +#[derive(Component, Default)] +#[relationship_target(relationship = PooledDrawOf, linked_spawn)] +pub struct PooledDraws(Vec); + +/// One mesh draw. +pub struct PooledDraw { + pub mesh: Handle, + /// `None` draws no surface, only the wireframe + pub material: Option, + /// the instance's fill, for a material that reads it from the mesh tag + pub tag: Option, + pub wireframe: Option>, + pub transform: Transform, +} + +struct Slot { + entity: Entity, + mesh: AssetId, + material: Option, + tag: Option, + wireframe: Option>, + visible: bool, +} + +/// Idle slots kept beyond twice what the last flush used. +const POOL_SLACK: usize = 64; + +/// The mesh draw entities of one graphics; slot `i` is the `i`th mesh draw of a flush. +#[derive(Component, Default)] +pub struct DrawPool { + slots: Vec, + live: usize, + prev_live: usize, + layers: Option, +} + +impl DrawPool { + /// Starts a flush: every slot is up for reuse. + pub fn begin(&mut self, commands: &mut Commands, layers: &RenderLayers) { + self.prev_live = self.live; + self.live = 0; + if self.layers.as_ref() != Some(layers) { + for slot in &self.slots { + commands.entity(slot.entity).insert(layers.clone()); + } + self.layers = Some(layers.clone()); + } + } + + /// Draws into the next slot, rewriting the transform and whatever else changed. + pub fn draw(&mut self, commands: &mut Commands, graphics: Entity, draw: PooledDraw) { + let index = self.live; + self.live += 1; + let mesh = draw.mesh.id(); + let material = draw.material.as_ref().map(|material| material.id()); + let wireframe = draw.wireframe.as_ref().map(|wireframe| wireframe.id()); + + let Some(slot) = self.slots.get_mut(index) else { + let mut entity = commands.spawn(( + Mesh3d(draw.mesh), + PooledDrawOf(graphics), + draw.transform, + Visibility::Inherited, + self.layers.clone().unwrap_or_default(), + )); + if let Some(material) = draw.material { + entity.insert(UntypedMaterial(material)); + } + if let Some(tag) = draw.tag { + entity.insert(MeshTag(tag)); + } + if let Some(wireframe) = draw.wireframe { + entity.insert((Wireframe, Mesh3dWireframe(wireframe))); + } + self.slots.push(Slot { + entity: entity.id(), + mesh, + material, + tag: draw.tag, + wireframe, + visible: true, + }); + return; + }; + + let mut entity = commands.entity(slot.entity); + entity.insert(draw.transform); + if slot.mesh != mesh { + slot.mesh = mesh; + entity.insert(Mesh3d(draw.mesh)); + } + if slot.material != material { + slot.material = material; + match draw.material { + Some(material) => entity.insert(UntypedMaterial(material)), + // the sync systems only see a changed `UntypedMaterial`, not a removed one + None => entity.remove::<( + UntypedMaterial, + MeshMaterial3d, + MeshMaterial3d, + CustomMaterial3d, + )>(), + }; + } + if slot.tag != draw.tag { + slot.tag = draw.tag; + match draw.tag { + Some(tag) => entity.insert(MeshTag(tag)), + None => entity.remove::(), + }; + } + if slot.wireframe != wireframe { + slot.wireframe = wireframe; + match draw.wireframe { + Some(wireframe) => entity.insert((Wireframe, Mesh3dWireframe(wireframe))), + None => entity.remove::<(Wireframe, Mesh3dWireframe)>(), + }; + } + if !slot.visible { + slot.visible = true; + entity.insert(Visibility::Inherited); + } + } + + /// Ends a flush: hides the slots it did not reach and frees those past the slack. + pub fn end(&mut self, commands: &mut Commands) { + let keep = self.live * 2 + POOL_SLACK; + if self.slots.len() > keep { + for slot in self.slots.drain(keep..) { + commands.entity(slot.entity).despawn(); + } + } + let hide_to = self.prev_live.min(self.slots.len()); + if self.live < hide_to { + for slot in &mut self.slots[self.live..hide_to] { + if slot.visible { + slot.visible = false; + commands.entity(slot.entity).insert(Visibility::Hidden); + } + } + } + } +} + +/// How many flushes a cached asset survives without being asked for. +const KEEP_FLUSHES: u64 = 8; + +/// One value per distinct key, dropped after `KEEP_FLUSHES` flushes unused. +pub struct Cache { + tick: u64, + map: HashMap, +} + +impl Default for Cache { + fn default() -> Self { + Self { + tick: 0, + map: HashMap::default(), + } + } +} + +impl Cache { + pub fn get_or_insert_with(&mut self, key: K, make: impl FnOnce() -> V) -> V { + let tick = self.tick; + let entry = self.map.entry(key).or_insert_with(|| (make(), tick)); + entry.1 = tick; + entry.0.clone() + } + + fn end_flush(&mut self) { + self.tick += 1; + let tick = self.tick; + self.map.retain(|_, (_, used)| *used + KEEP_FLUSHES >= tick); + } +} + +/// Cache key of a mesh draw's material. +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct MaterialDesc { + pub key: MaterialKey, + /// the fill, when it has to live in the material + pub base_color: Option<[u32; 4]>, + /// the fill comes from each instance's mesh tag + pub instance_fill: bool, + pub depth_bias: u32, +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct WireframeKey { + pub color: [u32; 4], + pub width: u32, + pub topology: WireframeTopology, +} + +/// A unit primitive mesh, keyed by what scaling cannot change. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub enum ShapeKey { + Box, + Sphere { sectors: u32, stacks: u32 }, + Cylinder { detail: u32 }, + Cone { detail: u32 }, + Plane, + Tetrahedron, + Torus { tube: u32, major: u32, minor: u32 }, + Capsule { length: u32, detail: u32 }, + ConicalFrustum { top: u32, detail: u32 }, +} + +/// The assets mesh draws share, across graphics and frames. +#[derive(Default)] +pub struct DrawCaches { + pub materials: Cache, + pub wireframes: Cache>, + pub shapes: Cache>, +} + +impl DrawCaches { + pub fn end_flush(&mut self) { + self.materials.end_flush(); + self.wireframes.end_flush(); + self.shapes.end_flush(); + } +} diff --git a/crates/processing_render/src/render/primitive/arc.rs b/crates/processing_render/src/render/primitive/arc.rs index e91a901a..91d289f6 100644 --- a/crates/processing_render/src/render/primitive/arc.rs +++ b/crates/processing_render/src/render/primitive/arc.rs @@ -2,7 +2,7 @@ use bevy::prelude::*; use lyon::{geom::Point, path::Path}; use crate::render::command::ArcMode; -use crate::render::primitive::{StrokeConfig, TessellationMode, tessellate_path}; +use crate::render::primitive::{PathSink, StrokeConfig, TessellationMode, tessellate_path}; fn arc_path( cx: f32, @@ -71,7 +71,7 @@ pub fn arc_fill( } pub fn arc_stroke( - mesh: &mut Mesh, + sink: &mut dyn PathSink, cx: f32, cy: f32, w: f32, @@ -84,8 +84,7 @@ pub fn arc_stroke( stroke_config: &StrokeConfig, ) { let path = arc_path(cx, cy, w, h, start, stop, mode, false); - tessellate_path( - mesh, + sink.path( &path, color, TessellationMode::Stroke(weight), diff --git a/crates/processing_render/src/render/primitive/curves.rs b/crates/processing_render/src/render/primitive/curves.rs index 2be38131..1fc38f84 100644 --- a/crates/processing_render/src/render/primitive/curves.rs +++ b/crates/processing_render/src/render/primitive/curves.rs @@ -1,11 +1,11 @@ use bevy::prelude::*; use lyon::{geom::Point, path::Path}; -use crate::render::primitive::{StrokeConfig, TessellationMode, tessellate_path}; +use crate::render::primitive::{PathSink, StrokeConfig, TessellationMode}; /// Draw a standalone cubic bezier curve. pub fn bezier( - mesh: &mut Mesh, + sink: &mut dyn PathSink, x1: f32, y1: f32, x2: f32, @@ -23,8 +23,7 @@ pub fn bezier( builder.cubic_bezier_to(Point::new(x2, y2), Point::new(x3, y3), Point::new(x4, y4)); builder.end(false); let path = builder.build(); - tessellate_path( - mesh, + sink.path( &path, color, TessellationMode::Stroke(weight), @@ -34,7 +33,7 @@ pub fn bezier( /// Draw a standalone Catmull-Rom curve segment. pub fn curve( - mesh: &mut Mesh, + sink: &mut dyn PathSink, x1: f32, y1: f32, x2: f32, @@ -62,8 +61,7 @@ pub fn curve( ); builder.end(false); let path = builder.build(); - tessellate_path( - mesh, + sink.path( &path, color, TessellationMode::Stroke(weight), diff --git a/crates/processing_render/src/render/primitive/ellipse.rs b/crates/processing_render/src/render/primitive/ellipse.rs index 300ecddc..45eefc1a 100644 --- a/crates/processing_render/src/render/primitive/ellipse.rs +++ b/crates/processing_render/src/render/primitive/ellipse.rs @@ -1,7 +1,7 @@ use bevy::prelude::*; use lyon::{geom::Point, path::Path}; -use crate::render::primitive::{StrokeConfig, TessellationMode, tessellate_path}; +use crate::render::primitive::{PathSink, StrokeConfig, TessellationMode}; // magic number for cubic bezier approximation of a quarter circle. // kappa = 4 * (sqrt(2) - 1) / 3 @@ -47,7 +47,7 @@ fn ellipse_path(cx: f32, cy: f32, w: f32, h: f32) -> Path { } pub fn ellipse( - mesh: &mut Mesh, + sink: &mut dyn PathSink, cx: f32, cy: f32, w: f32, @@ -57,5 +57,5 @@ pub fn ellipse( stroke_config: &StrokeConfig, ) { let path = ellipse_path(cx, cy, w, h); - tessellate_path(mesh, &path, color, mode, stroke_config); + sink.path(&path, color, mode, stroke_config); } diff --git a/crates/processing_render/src/render/primitive/line.rs b/crates/processing_render/src/render/primitive/line.rs index a1a1a3da..0a390c47 100644 --- a/crates/processing_render/src/render/primitive/line.rs +++ b/crates/processing_render/src/render/primitive/line.rs @@ -1,10 +1,10 @@ use bevy::prelude::*; use lyon::{geom::Point, path::Path}; -use crate::render::primitive::{StrokeConfig, TessellationMode, tessellate_path}; +use crate::render::primitive::{PathSink, StrokeConfig, TessellationMode}; pub fn line( - mesh: &mut Mesh, + sink: &mut dyn PathSink, x1: f32, y1: f32, x2: f32, @@ -18,8 +18,7 @@ pub fn line( builder.line_to(Point::new(x2, y2)); builder.end(false); let path = builder.build(); - tessellate_path( - mesh, + sink.path( &path, color, TessellationMode::Stroke(weight), diff --git a/crates/processing_render/src/render/primitive/mod.rs b/crates/processing_render/src/render/primitive/mod.rs index e7b61f26..33e69905 100644 --- a/crates/processing_render/src/render/primitive/mod.rs +++ b/crates/processing_render/src/render/primitive/mod.rs @@ -12,14 +12,15 @@ mod triangle; pub use arc::{arc_fill, arc_stroke}; use bevy::{ asset::RenderAssetUsages, - mesh::{Indices, PrimitiveTopology}, + math::{Affine3A, Vec3A}, + mesh::{Indices, PrimitiveTopology, VertexAttributeValues}, prelude::*, }; pub use curves::{bezier, curve}; pub use ellipse::ellipse; pub use line::line; use lyon::{ - path::Path, + path::{Path, PathEvent}, tessellation::{ FillOptions, FillRule, FillTessellator, LineCap, LineJoin, StrokeOptions, StrokeTessellator, }, @@ -36,6 +37,7 @@ pub use shape3d::{ pub use triangle::triangle; use super::command::{StrokeCapMode, StrokeJoinMode}; +use super::line::{LineEnd, LineMesh}; use super::mesh_builder::{MeshBuilder, MeshVertex}; pub enum TessellationMode { @@ -81,6 +83,70 @@ impl StrokeJoinMode { } } +/// Where a primitive's path is drawn: a batch mesh or a line mesh. +pub trait PathSink { + fn path( + &mut self, + path: &Path, + color: Color, + mode: TessellationMode, + stroke_config: &StrokeConfig, + ); + + /// The batch mesh, for a primitive that writes a simple fill directly. + fn mesh(&mut self) -> Option<&mut Mesh> { + None + } +} + +impl PathSink for Mesh { + fn path( + &mut self, + path: &Path, + color: Color, + mode: TessellationMode, + stroke_config: &StrokeConfig, + ) { + tessellate_path(self, path, color, mode, stroke_config); + } + + fn mesh(&mut self) -> Option<&mut Mesh> { + Some(self) + } +} + +impl PathSink for LineMesh { + /// Strokes only: segments along the flattened path. + fn path( + &mut self, + path: &Path, + color: Color, + mode: TessellationMode, + _stroke_config: &StrokeConfig, + ) { + let TessellationMode::Stroke(weight) = mode else { + return; + }; + let end = |point: lyon::math::Point| LineEnd { + position: Vec3::new(point.x, point.y, 0.0), + color, + weight, + }; + use lyon::path::iterator::PathIterator; + for event in path.iter().flattened(self.flatten_tolerance()) { + match event { + PathEvent::Line { from, to } => self.segment(end(from), end(to)), + PathEvent::End { + last, + first, + close: true, + } => self.segment(end(last), end(first)), + _ => {} + } + } + } +} + pub fn tessellate_path( mesh: &mut Mesh, path: &Path, @@ -154,6 +220,47 @@ pub fn tessellate_colored_stroke( .unwrap_or_else(|error| debug!("shape not tessellated: {error:?}")); } +/// Applies `transform` to the geometry from `first_vertex` and `first_index` on. +pub fn bake_transform( + mesh: &mut Mesh, + first_vertex: usize, + first_index: usize, + transform: Affine3A, +) { + if transform == Affine3A::IDENTITY { + return; + } + if let Some(VertexAttributeValues::Float32x3(positions)) = + mesh.attribute_mut(Mesh::ATTRIBUTE_POSITION) + { + for position in positions.iter_mut().skip(first_vertex) { + *position = transform.transform_point3(Vec3::from(*position)).to_array(); + } + } + let determinant = transform.matrix3.determinant(); + // normals follow the inverse transpose; a matrix that flattens space has none + if determinant != 0.0 + && let Some(VertexAttributeValues::Float32x3(normals)) = + mesh.attribute_mut(Mesh::ATTRIBUTE_NORMAL) + { + let normal_matrix = transform.matrix3.inverse().transpose(); + for normal in normals.iter_mut().skip(first_vertex) { + *normal = (normal_matrix * Vec3A::from(*normal)) + .normalize_or_zero() + .to_array(); + } + } + // a mirroring matrix turns triangles inside out + if determinant < 0.0 + && let Some(Indices::U32(indices)) = mesh.indices_mut() + { + let first_index = first_index.min(indices.len()); + for triangle in indices[first_index..].chunks_exact_mut(3) { + triangle.swap(1, 2); + } + } +} + pub fn empty_mesh() -> Mesh { let mut mesh = Mesh::new( PrimitiveTopology::TriangleList, diff --git a/crates/processing_render/src/render/primitive/quad.rs b/crates/processing_render/src/render/primitive/quad.rs index 6550d049..0b88a05a 100644 --- a/crates/processing_render/src/render/primitive/quad.rs +++ b/crates/processing_render/src/render/primitive/quad.rs @@ -4,7 +4,7 @@ use bevy::{ }; use lyon::{geom::Point, path::Path}; -use crate::render::primitive::{StrokeConfig, TessellationMode, tessellate_path}; +use crate::render::primitive::{PathSink, StrokeConfig, TessellationMode}; fn quad_path(x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32, x4: f32, y4: f32) -> Path { let mut b = Path::builder(); @@ -17,7 +17,7 @@ fn quad_path(x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32, x4: f32, y4: } pub fn quad( - mesh: &mut Mesh, + sink: &mut dyn PathSink, x1: f32, y1: f32, x2: f32, @@ -30,11 +30,13 @@ pub fn quad( mode: TessellationMode, stroke_config: &StrokeConfig, ) { - if matches!(mode, TessellationMode::Fill) { + if matches!(mode, TessellationMode::Fill) + && let Some(mesh) = sink.mesh() + { simple_quad(mesh, x1, y1, x2, y2, x3, y3, x4, y4, color); } else { let path = quad_path(x1, y1, x2, y2, x3, y3, x4, y4); - tessellate_path(mesh, &path, color, mode, stroke_config); + sink.path(&path, color, mode, stroke_config); } } diff --git a/crates/processing_render/src/render/primitive/rect.rs b/crates/processing_render/src/render/primitive/rect.rs index d989612b..7f6fd33a 100644 --- a/crates/processing_render/src/render/primitive/rect.rs +++ b/crates/processing_render/src/render/primitive/rect.rs @@ -4,7 +4,7 @@ use bevy::{ }; use lyon::{geom::Point, path::Path}; -use crate::render::primitive::{StrokeConfig, TessellationMode, tessellate_path}; +use crate::render::primitive::{PathSink, StrokeConfig, TessellationMode}; fn rect_path(x: f32, y: f32, w: f32, h: f32, radii: [f32; 4]) -> Path { let mut path_builder = Path::builder(); @@ -48,7 +48,7 @@ fn rect_path(x: f32, y: f32, w: f32, h: f32, radii: [f32; 4]) -> Path { } pub fn rect( - mesh: &mut Mesh, + sink: &mut dyn PathSink, x: f32, y: f32, w: f32, @@ -58,11 +58,14 @@ pub fn rect( mode: TessellationMode, stroke_config: &StrokeConfig, ) { - if radii == [0.0; 4] && matches!(mode, TessellationMode::Fill) { + if radii == [0.0; 4] + && matches!(mode, TessellationMode::Fill) + && let Some(mesh) = sink.mesh() + { simple_rect(mesh, x, y, w, h, color); } else { let path = rect_path(x, y, w, h, radii); - tessellate_path(mesh, &path, color, mode, stroke_config); + sink.path(&path, color, mode, stroke_config); } } diff --git a/crates/processing_render/src/render/primitive/triangle.rs b/crates/processing_render/src/render/primitive/triangle.rs index 5b66b479..0679e6c2 100644 --- a/crates/processing_render/src/render/primitive/triangle.rs +++ b/crates/processing_render/src/render/primitive/triangle.rs @@ -4,7 +4,7 @@ use bevy::{ }; use lyon::{geom::Point, path::Path}; -use crate::render::primitive::{StrokeConfig, TessellationMode, tessellate_path}; +use crate::render::primitive::{PathSink, StrokeConfig, TessellationMode}; fn triangle_path(x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32) -> Path { let mut b = Path::builder(); @@ -16,7 +16,7 @@ fn triangle_path(x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32) -> Path { } pub fn triangle( - mesh: &mut Mesh, + sink: &mut dyn PathSink, x1: f32, y1: f32, x2: f32, @@ -27,11 +27,13 @@ pub fn triangle( mode: TessellationMode, stroke_config: &StrokeConfig, ) { - if matches!(mode, TessellationMode::Fill) { + if matches!(mode, TessellationMode::Fill) + && let Some(mesh) = sink.mesh() + { simple_triangle(mesh, x1, y1, x2, y2, x3, y3, color); } else { let path = triangle_path(x1, y1, x2, y2, x3, y3); - tessellate_path(mesh, &path, color, mode, stroke_config); + sink.path(&path, color, mode, stroke_config); } } diff --git a/crates/processing_wasm/src/lib.rs b/crates/processing_wasm/src/lib.rs index 897e8409..f929fb9e 100644 --- a/crates/processing_wasm/src/lib.rs +++ b/crates/processing_wasm/src/lib.rs @@ -433,7 +433,10 @@ pub fn js_line(graphics_id: u64, x1: f32, y1: f32, x2: f32, y2: f32) -> Result<( let graphics_entity = Entity::from_bits(graphics_id); check(graphics_record_command( graphics_entity, - DrawCommand::Line { x1, y1, x2, y2 }, + DrawCommand::Line { + from: Vec3::new(x1, y1, 0.0), + to: Vec3::new(x2, y2, 0.0), + }, )) } @@ -494,7 +497,9 @@ pub fn js_point(graphics_id: u64, x: f32, y: f32) -> Result<(), JsValue> { let graphics_entity = Entity::from_bits(graphics_id); check(graphics_record_command( graphics_entity, - DrawCommand::Point { x, y }, + DrawCommand::Point { + at: Vec3::new(x, y, 0.0), + }, )) } diff --git a/examples/curves.rs b/examples/curves.rs index b15ccdff..4744855d 100644 --- a/examples/curves.rs +++ b/examples/curves.rs @@ -1,5 +1,6 @@ use processing_glfw::GlfwContext; +use bevy::math::Vec3; use processing::prelude::*; use processing_render::render::command::DrawCommand; @@ -89,10 +90,8 @@ fn sketch() -> error::Result<()> { graphics_record_command( graphics, DrawCommand::Line { - x1: 0.0, - y1: y, - x2: 800.0, - y2: y, + from: Vec3::new(0.0, y, 0.0), + to: Vec3::new(800.0, y, 0.0), }, )?; } diff --git a/tests/visual/cases.toml b/tests/visual/cases.toml index c370852a..843b0229 100644 --- a/tests/visual/cases.toml +++ b/tests/visual/cases.toml @@ -177,3 +177,30 @@ python = "text.py" [[case]] name = "py_window_controls" python = "window_controls.py" + +# first-frame captures: an unready shader or pipeline drops its draws + +[[case]] +name = "py_first_frame_shapes" +python = "shapes.py" +frame = 1 + +[[case]] +name = "py_first_frame_primitives_3d" +python = "primitives_3d.py" +frame = 1 + +[[case]] +name = "py_first_frame_text" +python = "text.py" +frame = 1 + +[[case]] +name = "py_first_frame_custom_material" +python = "custom_material.py" +frame = 1 + +[[case]] +name = "py_first_frame_particles_points" +python = "particles_points.py" +frame = 1 From bc24983a1a29af027d22778e232525c1003d4e5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?charlotte=20=F0=9F=8C=B8?= Date: Mon, 30 Nov 2026 14:08:07 -0800 Subject: [PATCH 2/4] Fill as vertex color and custom vertex shaders. --- assets/shaders/custom_vertex.wesl | 20 + .../processing_pyo3/examples/custom_vertex.py | 36 ++ .../shaders/processing/mesh.wesl | 94 ++++ .../processing_render/src/material/custom.rs | 502 +++++++++++++++--- .../src/material/fragment.wgsl | 5 + crates/processing_render/src/material/mod.rs | 51 +- .../src/material/processing.wgsl | 132 ----- .../src/material/vertex.wgsl | 176 ++++++ crates/processing_render/src/render/mod.rs | 136 +++-- tests/visual/cases.toml | 4 + 10 files changed, 913 insertions(+), 243 deletions(-) create mode 100644 assets/shaders/custom_vertex.wesl create mode 100644 crates/processing_pyo3/examples/custom_vertex.py create mode 100644 crates/processing_render/shaders/processing/mesh.wesl create mode 100644 crates/processing_render/src/material/fragment.wgsl delete mode 100644 crates/processing_render/src/material/processing.wgsl create mode 100644 crates/processing_render/src/material/vertex.wgsl diff --git a/assets/shaders/custom_vertex.wesl b/assets/shaders/custom_vertex.wesl new file mode 100644 index 00000000..7f332a3e --- /dev/null +++ b/assets/shaders/custom_vertex.wesl @@ -0,0 +1,20 @@ +import { processing::VertexOutput }; +import { processing::mesh::{Vertex, vertex_output} }; + +@group(3) @binding(0) var bulge: f32; + +@vertex +fn vertex(vertex_in: Vertex) -> VertexOutput { + var vertex = vertex_in; + // `sphere()` draws a unit sphere scaled by its transform + vertex.position += vertex.normal * bulge * sin(vertex.position.y * 12.0); + return vertex_output(vertex); +} + +@fragment +fn fragment(mesh: VertexOutput) -> @location(0) vec4 { + let light_dir = normalize(vec3(0.4, -0.6, 0.7)); + let diffuse = max(dot(normalize(mesh.world_normal), light_dir), 0.2); + // the fill arrives as the vertex color + return vec4(mesh.color.rgb * diffuse, mesh.color.a); +} diff --git a/crates/processing_pyo3/examples/custom_vertex.py b/crates/processing_pyo3/examples/custom_vertex.py new file mode 100644 index 00000000..38beda4a --- /dev/null +++ b/crates/processing_pyo3/examples/custom_vertex.py @@ -0,0 +1,36 @@ +from processing_py import * + +mat = None + +def setup(): + global mat + size(800, 600) + mode_3d() + + shader = load_shader("shaders/custom_vertex.wesl") + mat = create_material(shader, bulge=0.15) + +def draw(): + camera_position(0.0, 0.0, 500.0) + camera_look_at(0.0, 0.0, 0.0) + background(12, 12, 18) + + no_stroke() + material(mat) + + fill(255, 80, 40) + push_matrix() + translate(-200, 0, 0) + sphere(70) + pop_matrix() + + fill(40, 200, 120) + sphere(70) + + fill(60, 120, 255) + push_matrix() + translate(200, 0, 0) + sphere(70) + pop_matrix() + +run() diff --git a/crates/processing_render/shaders/processing/mesh.wesl b/crates/processing_render/shaders/processing/mesh.wesl new file mode 100644 index 00000000..72bf2275 --- /dev/null +++ b/crates/processing_render/shaders/processing/mesh.wesl @@ -0,0 +1,94 @@ +// what a custom vertex stage needs from the mesh; the layouts mirror bevy_pbr's +import package::VertexOutput; + +struct Vertex { + @builtin(instance_index) instance_index: u32, + @location(0) position: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, + @location(5) color: vec4, +} + +// the leading field of bevy_render::view::View +struct View { + clip_from_world: mat4x4, +} + +@group(0) @binding(0) var view: View; + +// bevy_pbr::mesh_types::Mesh +struct Mesh { + world_from_local: mat3x4, + previous_world_from_local: mat3x4, + local_from_world_transpose_a: mat2x4, + local_from_world_transpose_b: f32, + flags: u32, + lightmap_uv_rect: vec2, + first_vertex_index: u32, + current_skin_index: u32, + material_and_lightmap_bind_group_slot: u32, + tag: u32, + morph_descriptor_index: u32, +} + +@group(2) @binding(0) var mesh: array; + +fn world_from_local(instance_index: u32) -> mat4x4 { + let m = transpose(mesh[instance_index].world_from_local); + return mat4x4(vec4(m[0], 0.0), vec4(m[1], 0.0), vec4(m[2], 0.0), vec4(m[3], 1.0)); +} + +fn world_normal(normal: vec3, instance_index: u32) -> vec3 { + let a = mesh[instance_index].local_from_world_transpose_a; + let b = mesh[instance_index].local_from_world_transpose_b; + let m = mat3x3(a[0].xyz, vec3(a[0].w, a[1].xy), vec3(a[1].zw, b)); + // a zero normal stays zero instead of becoming NaN + if all(normal == vec3(0.0)) { + return normal; + } + return normalize(m * normal); +} + +fn clip_from_world(world_position: vec3) -> vec4 { + return view.clip_from_world * vec4(world_position, 1.0); +} + +// the fill of this instance, linear rgba +@if(tag_is_fill) +fn instance_fill(instance_index: u32) -> vec4 { + let tag = mesh[instance_index].tag; + let srgb = vec4( + f32(tag & 0xffu), + f32((tag >> 8u) & 0xffu), + f32((tag >> 16u) & 0xffu), + f32(tag >> 24u), + ) / 255.0; + let linear = select( + pow((srgb.rgb + 0.055) / 1.055, vec3(2.4)), + srgb.rgb / 12.92, + srgb.rgb <= vec3(0.04045), + ); + return vec4(linear, srgb.a); +} + +// a particle's tag is its index, not a fill +@if(!tag_is_fill) +fn instance_fill(instance_index: u32) -> vec4 { + return vec4(1.0); +} + +// the color a vertex is drawn in: its own color times the fill +fn fill_color(vertex: Vertex) -> vec4 { + return vertex.color * instance_fill(vertex.instance_index); +} + +// the `VertexOutput` of an untouched `vertex` +fn vertex_output(vertex: Vertex) -> VertexOutput { + var out: VertexOutput; + out.world_position = world_from_local(vertex.instance_index) * vec4(vertex.position, 1.0); + out.position = clip_from_world(out.world_position.xyz); + out.world_normal = world_normal(vertex.normal, vertex.instance_index); + out.uv = vertex.uv; + out.color = fill_color(vertex); + return out; +} diff --git a/crates/processing_render/src/material/custom.rs b/crates/processing_render/src/material/custom.rs index e6d4bd21..52db2ea8 100644 --- a/crates/processing_render/src/material/custom.rs +++ b/crates/processing_render/src/material/custom.rs @@ -1,5 +1,6 @@ use std::any::{Any, TypeId}; use std::borrow::Cow; +use std::collections::HashMap; use std::sync::Arc; use bevy::platform::collections::hash_map::Entry; @@ -11,23 +12,24 @@ wesl::wesl_pkg!(lygia); use bevy::{ asset::{AsAssetId, AssetEventSystems}, - core_pipeline::core_3d::Opaque3d, + core_pipeline::core_3d::{AlphaMask3d, Opaque3d, Transparent3d}, ecs::system::{ SystemParamItem, lifetimeless::{SRes, SResMut}, }, material::{ - MaterialProperties, + MaterialProperties, RenderPhaseType, descriptor::RenderPipelineDescriptor, key::{ErasedMaterialKey, ErasedMaterialPipelineKey, ErasedMeshPipelineKey}, specialize::SpecializedMeshPipelineError, }, - mesh::MeshVertexBufferLayoutRef, + mesh::{MeshVertexAttribute, MeshVertexBufferLayoutRef}, pbr::{ - DrawMaterial, EntitiesNeedingSpecialization, MainPassOpaqueDrawFunction, - MainPassTransparentDrawFunction, MaterialBindGroupAllocator, MaterialBindGroupAllocators, - MaterialFragmentShader, MaterialVertexShader, MeshPipelineKey, PreparedMaterial, - RenderMaterialBindings, RenderMaterialInstance, RenderMaterialInstances, base_specialize, + DrawMaterial, EntitiesNeedingSpecialization, MainPassAlphaMaskDrawFunction, + MainPassOpaqueDrawFunction, MainPassTransparentDrawFunction, MaterialBindGroupAllocator, + MaterialBindGroupAllocators, MaterialFragmentShader, MaterialVertexShader, MeshPipelineKey, + PreparedMaterial, RenderMaterialBindings, RenderMaterialInstance, RenderMaterialInstances, + base_specialize, }, prelude::*, reflect::{PartialReflect, ReflectMut, ReflectRef, structs::Struct}, @@ -62,12 +64,28 @@ struct CustomMaterialKey { blend_state: Option, double_sided: Option, depth_write: Option, + instance_fill: bool, + vertex_inputs: u32, +} + +/// The mesh attribute bevy binds at each vertex input location. +fn vertex_attributes() -> [MeshVertexAttribute; 8] { + [ + Mesh::ATTRIBUTE_POSITION, + Mesh::ATTRIBUTE_NORMAL, + Mesh::ATTRIBUTE_UV_0, + Mesh::ATTRIBUTE_UV_1, + Mesh::ATTRIBUTE_TANGENT, + Mesh::ATTRIBUTE_COLOR, + Mesh::ATTRIBUTE_JOINT_INDEX, + Mesh::ATTRIBUTE_JOINT_WEIGHT, + ] } fn specialize( _pipeline: &dyn Any, descriptor: &mut RenderPipelineDescriptor, - _layout: &MeshVertexBufferLayoutRef, + layout: &MeshVertexBufferLayoutRef, pipeline_key: ErasedMaterialPipelineKey, ) -> std::result::Result<(), SpecializedMeshPipelineError> { // the first argument is bevy's `MaterialPipeline`; the material key rides in the pipeline key @@ -78,6 +96,27 @@ fn specialize( Some(false) => Some(Face::Back), _ => None, }; + if crate::material::uses_processing_vertex(descriptor) { + if key.instance_fill { + descriptor.vertex.shader_defs.push("INSTANCE_FILL".into()); + } + // a fragment stage reads a uv and a color whether or not the mesh has them + if !layout.0.contains(Mesh::ATTRIBUTE_COLOR) { + crate::material::output_missing_colors(descriptor); + } + if !layout.0.contains(Mesh::ATTRIBUTE_UV_0) { + crate::material::output_missing_uvs(descriptor); + } + } else { + // the mesh must have every attribute the vertex stage reads + let read: Vec<_> = vertex_attributes() + .into_iter() + .enumerate() + .filter(|(location, _)| key.vertex_inputs & (1 << location) != 0) + .map(|(location, attribute)| attribute.at_shader_location(location as u32)) + .collect(); + layout.0.get_layout(&read)?; + } Ok(()) } @@ -85,18 +124,108 @@ fn specialize( pub struct CustomMaterial { pub shader: DynamicShader, pub shader_handle: Handle, + /// the shader that reads the mesh tag as a particle index + pub particles_shader_handle: Handle, pub has_vertex: bool, pub has_fragment: bool, + /// the vertex input locations the vertex stage reads, as bits + pub vertex_inputs: u32, pub blend_state: Option, pub alpha_mode: AlphaMode, pub double_sided: Option, pub depth_write: Option, + /// the fill is the sRGB8 RGBA color packed in each instance's `MeshTag` + pub instance_fill: bool, +} + +/// How a draw needs a material to differ from the one the sketch made. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub(crate) struct VariantKey { + pub blend_state: Option, + pub instance_fill: bool, +} + +/// Copies of materials for the draws that need them changed, kept in step with the originals. +#[derive(Resource)] +pub(crate) struct Variants { + /// bumped whenever a material may have been written + generation: u64, + variants: HashMap<(AssetId, VariantKey), (Handle, u64)>, +} + +pub(crate) type CustomVariants = Variants; + +impl Default for Variants { + fn default() -> Self { + Self { + generation: 0, + variants: HashMap::new(), + } + } +} + +impl Variants { + /// Starts a flush; `changed` is whether any material was written since the last one. + pub(crate) fn begin(&mut self, changed: bool, materials: &Assets) { + if changed { + self.generation += 1; + self.variants + .retain(|(original, _), _| materials.contains(*original)); + } + } + + /// The variant of `original` for `key`, made or brought up to date as needed. + pub(crate) fn get( + &mut self, + materials: &mut Assets, + original: &Handle, + key: VariantKey, + apply: impl Fn(&mut A, VariantKey), + ) -> Option> { + let current = self.generation; + let make = |source: &A| { + let mut variant = source.clone(); + apply(&mut variant, key); + variant + }; + let source = materials.get(original)?; + match self.variants.get_mut(&(original.id(), key)) { + Some((handle, generation)) => { + if *generation != current { + let variant = make(source); + if let Some(mut stale) = materials.get_mut(handle.id()) { + *stale = variant; + } + *generation = current; + } + Some(handle.clone()) + } + None => { + let handle = materials.add(make(source)); + self.variants + .insert((original.id(), key), (handle.clone(), current)); + Some(handle) + } + } + } +} + +impl CustomMaterial { + /// Makes this the variant a draw asked for. + pub(crate) fn apply_variant(&mut self, key: VariantKey) { + if key.blend_state.is_some() { + self.blend_state = key.blend_state; + } + self.instance_fill = key.instance_fill; + } } #[derive(Component)] pub struct Shader { pub module: naga::Module, pub shader_handle: Handle, + /// the shader that reads the mesh tag as a particle index + pub particles_handle: Handle, } /// A compiled shader and the file it was loaded from, kept so edits to the file reload it. @@ -203,10 +332,6 @@ pub fn shader_packages() -> Vec { ] } -pub(crate) fn compile_shader(source: &str) -> Result<(String, naga::Module)> { - compile_shader_with_features(source, &[]) -} - pub(crate) fn compile_shader_with_features( source: &str, features: &[(&str, bool)], @@ -225,7 +350,7 @@ pub(crate) fn compile_shader_with_features( strip: false, ..Default::default() }; - for (name, enabled) in features { + for (name, enabled) in [(TAG_IS_FILL, true)].iter().chain(features) { options .features .flags @@ -239,19 +364,103 @@ pub(crate) fn compile_shader_with_features( Ok((wgsl, module)) } +/// The feature `processing::mesh` reads the mesh tag as a fill under. +const TAG_IS_FILL: &str = "tag_is_fill"; + +/// A compiled shader, and the variant for particles when it differs. +struct Compiled { + wgsl: String, + module: naga::Module, + particles_wgsl: Option, +} + +impl Compiled { + fn new(source: &str, features: &[(&str, bool)]) -> Result { + let (wgsl, module) = compile_shader_with_features(source, features)?; + check_stages(&module)?; + // only a vertex stage can read the tag + let particles_wgsl = if has_stage(&module, naga::ShaderStage::Vertex) { + let mut features = features.to_vec(); + features.push((TAG_IS_FILL, false)); + let (particles_wgsl, _) = compile_shader_with_features(source, &features)?; + (particles_wgsl != wgsl).then_some(particles_wgsl) + } else { + None + }; + Ok(Self { + wgsl, + module, + particles_wgsl, + }) + } + + fn add(self, shaders: &mut Assets) -> Shader { + let shader_handle = shaders.add(ShaderAsset::from_wgsl(self.wgsl, "custom_material")); + let particles_handle = match self.particles_wgsl { + Some(wgsl) => shaders.add(ShaderAsset::from_wgsl(wgsl, "custom_material")), + None => shader_handle.clone(), + }; + Shader { + module: self.module, + shader_handle, + particles_handle, + } + } +} + +/// The locations a stage reads or writes, as bits. +fn stage_locations(module: &naga::Module, stage: naga::ShaderStage, outputs: bool) -> u32 { + let Some(entry) = module.entry_points.iter().find(|ep| ep.stage == stage) else { + return 0; + }; + let mut bits = 0; + let mut add = |ty: naga::Handle, binding: &Option| { + if let Some(naga::Binding::Location { location, .. }) = binding { + bits |= 1 << location; + } + if let naga::TypeInner::Struct { members, .. } = &module.types[ty].inner { + for member in members { + if let Some(naga::Binding::Location { location, .. }) = &member.binding { + bits |= 1 << location; + } + } + } + }; + if outputs { + if let Some(result) = &entry.function.result { + add(result.ty, &result.binding); + } + } else { + for argument in &entry.function.arguments { + add(argument.ty, &argument.binding); + } + } + bits +} + +/// The built-in fragment stage reads the vertex color. +const COLOR_LOCATION: u32 = 5; + +/// A shader with no fragment stage is paired with the built-in one. +fn check_stages(module: &naga::Module) -> Result<()> { + let vertex_only = has_stage(module, naga::ShaderStage::Vertex) + && !has_stage(module, naga::ShaderStage::Fragment); + let outputs = stage_locations(module, naga::ShaderStage::Vertex, true); + if vertex_only && outputs & (1 << COLOR_LOCATION) == 0 { + return Err(ProcessingError::ShaderCompilationError( + "a shader with no fragment stage must output a color at @location(5)".to_string(), + )); + } + Ok(()) +} + pub fn create_shader( In(source): In, mut commands: Commands, mut shaders: ResMut>, ) -> Result { - let (compiled_wgsl, module) = compile_shader(&source)?; - let shader_handle = shaders.add(ShaderAsset::from_wgsl(compiled_wgsl, "custom_material")); - Ok(commands - .spawn(Shader { - module, - shader_handle, - }) - .id()) + let shader = Compiled::new(&source, &[])?.add(&mut shaders); + Ok(commands.spawn(shader).id()) } pub fn create_shader_with_features( @@ -260,14 +469,8 @@ pub fn create_shader_with_features( mut shaders: ResMut>, ) -> Result { let feats: Vec<(&str, bool)> = features.iter().map(|(k, v)| (k.as_str(), *v)).collect(); - let (compiled_wgsl, module) = compile_shader_with_features(&source, &feats)?; - let shader_handle = shaders.add(ShaderAsset::from_wgsl(compiled_wgsl, "custom_material")); - Ok(commands - .spawn(Shader { - module, - shader_handle, - }) - .id()) + let shader = Compiled::new(&source, &feats)?.add(&mut shaders); + Ok(commands.spawn(shader).id()) } pub fn load_shader(In(path): In, world: &mut World) -> Result { @@ -299,11 +502,7 @@ pub fn load_shader(In(path): In, world: &mut World) -> Result { } let source = shader_file_source(world.resource::>(), handle.id())?; - let (compiled_wgsl, module) = compile_shader(&source)?; - - let shader_handle = world - .resource_mut::>() - .add(ShaderAsset::from_wgsl(compiled_wgsl, "custom_material")); + let shader = Compiled::new(&source, &[])?.add(&mut world.resource_mut::>()); world .get_resource_or_insert_with(ShaderFiles::default) @@ -311,15 +510,10 @@ pub fn load_shader(In(path): In, world: &mut World) -> Result { .push(ShaderFile { file: handle, source, - compiled: shader_handle.id(), + compiled: shader.shader_handle.id(), }); - Ok(world - .spawn(Shader { - module, - shader_handle, - }) - .id()) + Ok(world.spawn(shader).id()) } fn shader_file_source(shaders: &Assets, id: AssetId) -> Result { @@ -360,9 +554,9 @@ fn reload_shaders( if source == entry.source { continue; } - let compiled = compile_shader(&source); + let compiled = Compiled::new(&source, &[]); entry.source = source; - let (wgsl, module) = match compiled { + let compiled = match compiled { Ok(compiled) => compiled, Err(e) => { // keep rendering the last version that compiled @@ -372,13 +566,15 @@ fn reload_shaders( }; // a new asset, not an in-place swap: pipelines built for the old // bindings would otherwise be recompiled against the new shader - let handle = shaders.add(ShaderAsset::from_wgsl(wgsl, "custom_material")); - let old = std::mem::replace(&mut entry.compiled, handle.id()); + let new = compiled.add(&mut shaders); + let module = new.module.clone(); + let old = std::mem::replace(&mut entry.compiled, new.shader_handle.id()); for mut program in &mut programs { if program.shader_handle.id() == old { program.module = module.clone(); - program.shader_handle = handle.clone(); + program.shader_handle = new.shader_handle.clone(); + program.particles_handle = new.particles_handle.clone(); } } @@ -394,7 +590,7 @@ fn reload_shaders( let Ok(mut shader) = DynamicShader::new(module.clone()) else { continue; }; - shader.init(); + init_material_fields(&mut shader); // carry over every value whose uniform survived the edit for i in 0..material.shader.field_len() { if let Some(name) = material.shader.name_at(i) @@ -405,9 +601,11 @@ fn reload_shaders( } } material.shader = shader; - material.shader_handle = handle.clone(); + material.shader_handle = new.shader_handle.clone(); + material.particles_shader_handle = new.particles_handle.clone(); material.has_vertex = has_stage(&module, naga::ShaderStage::Vertex); material.has_fragment = has_stage(&module, naga::ShaderStage::Fragment); + material.vertex_inputs = stage_locations(&module, naga::ShaderStage::Vertex, false); } } } @@ -418,6 +616,22 @@ pub fn destroy_shader(In(entity): In, mut commands: Commands) -> Result< Ok(()) } +/// The bind group a material's own parameters live in. +const MATERIAL_GROUP: u32 = 3; + +/// Gives the material's parameters their defaults; the engine's bindings are not its to set. +fn init_material_fields(shader: &mut DynamicShader) { + let names: Vec = shader + .reflection() + .parameters() + .filter(|p| p.group() == MATERIAL_GROUP) + .filter_map(|p| p.name().map(str::to_string)) + .collect(); + for name in names { + shader.field_mut(&name); + } +} + pub fn create_custom( In(shader_entity): In, mut commands: Commands, @@ -433,17 +647,20 @@ pub fn create_custom( let mut shader = DynamicShader::new(program.module.clone()) .map_err(|e| ProcessingError::ShaderCompilationError(e.to_string()))?; - shader.init(); + init_material_fields(&mut shader); let material = CustomMaterial { shader, shader_handle: program.shader_handle.clone(), + particles_shader_handle: program.particles_handle.clone(), has_vertex, has_fragment, + vertex_inputs: stage_locations(&program.module, naga::ShaderStage::Vertex, false), blend_state: None, alpha_mode: AlphaMode::Opaque, double_sided: None, depth_write: None, + instance_fill: true, }; let handle = custom_materials.add(material); Ok(commands.spawn(UntypedMaterial(handle.untyped())).id()) @@ -691,7 +908,11 @@ impl Plugin for CustomMaterialPlugin { app.init_asset::() .add_plugins(ErasedRenderAssetPlugin::::default()) .init_resource::() - .add_systems(Update, reload_shaders) + .init_resource::() + .add_systems( + Update, + reload_shaders.before(crate::render::flush_draw_commands), + ) .add_systems( PostUpdate, check_entities_needing_specialization.after(AssetEventSystems), @@ -740,6 +961,8 @@ impl ErasedRenderAsset for CustomMaterial { type ErasedAsset = PreparedMaterial; type Param = ( SRes>, + SRes>, + SRes>, SRes, SRes, SResMut, @@ -753,6 +976,8 @@ impl ErasedRenderAsset for CustomMaterial { asset_id: AssetId, ( opaque_draw_functions, + alpha_mask_draw_functions, + transparent_draw_functions, _asset_server, render_device, bind_group_allocators, @@ -763,12 +988,12 @@ impl ErasedRenderAsset for CustomMaterial { ) -> std::result::Result> { let reflection = source_asset.shader.reflection(); - let layout_entries = reflection.bind_group_layout(3); + let layout_entries = reflection.bind_group_layout(MATERIAL_GROUP); let bind_group_layout = BindGroupLayoutDescriptor::new("custom_material_bind_group", &layout_entries); let bindings = reflection.create_bindings( - 3, + MATERIAL_GROUP, &source_asset.shader, render_device, gpu_images, @@ -795,37 +1020,67 @@ impl ErasedRenderAsset for CustomMaterial { .insert(bind_group_allocator.allocate_unprepared(unprepared, &bind_group_layout)), }; - let draw_function = opaque_draw_functions.read().id::(); + // a draw function id only means something in its own phase + let opaque_draw = opaque_draw_functions.read().id::(); + let alpha_mask_draw = alpha_mask_draw_functions.read().id::(); + let transparent_draw = transparent_draw_functions.read().id::(); let blend_state = source_asset.blend_state; + let shader_handle = if source_asset.instance_fill { + &source_asset.shader_handle + } else { + &source_asset.particles_shader_handle + }; + // A custom blend forces the sorted transparent phase (an arbitrary + // blend equation can't be assumed commutative); otherwise honor the + // explicitly-set alpha mode. + let alpha_mode = if blend_state.is_some() { + AlphaMode::Blend + } else { + source_asset.alpha_mode + }; let mut properties = MaterialProperties { mesh_pipeline_key_bits: ErasedMeshPipelineKey::new(MeshPipelineKey::empty()), base_specialize: Some(base_specialize), material_layout: Some(bind_group_layout), material_key: ErasedMaterialKey::new(CustomMaterialKey { - shader: source_asset.shader_handle.id(), + shader: shader_handle.id(), blend_state, double_sided: source_asset.double_sided, depth_write: source_asset.depth_write, + instance_fill: source_asset.instance_fill, + vertex_inputs: source_asset.vertex_inputs, }), user_specialize: Some(specialize), - // A custom blend forces the sorted transparent phase (an arbitrary - // blend equation can't be assumed commutative); otherwise honor the - // explicitly-set alpha mode. - alpha_mode: if blend_state.is_some() { + alpha_mode, + render_phase_type: match alpha_mode { AlphaMode::Blend - } else { - source_asset.alpha_mode + | AlphaMode::Premultiplied + | AlphaMode::Add + | AlphaMode::Multiply => RenderPhaseType::Transparent, + AlphaMode::Mask(_) => RenderPhaseType::AlphaMask, + AlphaMode::Opaque | AlphaMode::AlphaToCoverage => RenderPhaseType::Opaque, }, ..Default::default() }; - properties.add_draw_function(MainPassOpaqueDrawFunction, draw_function); - properties.add_draw_function(MainPassTransparentDrawFunction, draw_function); + properties.add_draw_function(MainPassOpaqueDrawFunction, opaque_draw); + properties.add_draw_function(MainPassAlphaMaskDrawFunction, alpha_mask_draw); + properties.add_draw_function(MainPassTransparentDrawFunction, transparent_draw); if source_asset.has_vertex { - properties.add_shader(MaterialVertexShader, source_asset.shader_handle.clone()); + properties.add_shader(MaterialVertexShader, shader_handle.clone()); + } else { + properties.add_shader( + MaterialVertexShader, + crate::material::PROCESSING_VERTEX_SHADER, + ); } if source_asset.has_fragment { - properties.add_shader(MaterialFragmentShader, source_asset.shader_handle.clone()); + properties.add_shader(MaterialFragmentShader, shader_handle.clone()); + } else if source_asset.has_vertex { + properties.add_shader( + MaterialFragmentShader, + crate::material::PROCESSING_FRAGMENT_SHADER, + ); } Ok(PreparedMaterial { @@ -912,3 +1167,122 @@ fn check_entities_needing_specialization( entities.removed.push(entity); } } + +#[cfg(test)] +mod tests { + use super::*; + + const SOURCE: &str = " + @group(3) @binding(0) var tint: vec4; + @fragment + fn fragment() -> @location(0) vec4 { + return tint; + } + "; + + fn material() -> CustomMaterial { + let (_, module) = compile_shader_with_features(SOURCE, &[]).unwrap(); + let mut shader = DynamicShader::new(module).unwrap(); + init_material_fields(&mut shader); + CustomMaterial { + shader, + shader_handle: Handle::default(), + particles_shader_handle: Handle::default(), + has_vertex: false, + has_fragment: true, + vertex_inputs: 0, + blend_state: None, + alpha_mode: AlphaMode::Opaque, + double_sided: None, + depth_write: None, + instance_fill: true, + } + } + + const PARTICLES: VariantKey = VariantKey { + blend_state: None, + instance_fill: false, + }; + + #[test] + fn a_variant_is_reused_until_a_material_changes() { + let mut materials = Assets::::default(); + let original = materials.add(material()); + let mut variants = CustomVariants::default(); + + variants.begin(true, &materials); + let first = variants + .get( + &mut materials, + &original, + PARTICLES, + CustomMaterial::apply_variant, + ) + .unwrap(); + assert!(!materials.get(&first).unwrap().instance_fill); + + variants.begin(false, &materials); + let second = variants + .get( + &mut materials, + &original, + PARTICLES, + CustomMaterial::apply_variant, + ) + .unwrap(); + assert_eq!(first.id(), second.id()); + assert_eq!(materials.len(), 2); + } + + #[test] + fn a_variant_follows_its_original() { + let mut materials = Assets::::default(); + let original = materials.add(material()); + let mut variants = CustomVariants::default(); + variants.begin(true, &materials); + let variant = variants + .get( + &mut materials, + &original, + PARTICLES, + CustomMaterial::apply_variant, + ) + .unwrap(); + + materials.get_mut(&original).unwrap().double_sided = Some(false); + variants.begin(true, &materials); + let synced = variants + .get( + &mut materials, + &original, + PARTICLES, + CustomMaterial::apply_variant, + ) + .unwrap(); + + assert_eq!(variant.id(), synced.id()); + let synced = materials.get(&synced).unwrap(); + assert_eq!(synced.double_sided, Some(false)); + assert!(!synced.instance_fill, "the override survives the sync"); + } + + #[test] + fn variants_go_with_their_original() { + let mut materials = Assets::::default(); + let original = materials.add(material()); + let mut variants = CustomVariants::default(); + variants.begin(true, &materials); + variants + .get( + &mut materials, + &original, + PARTICLES, + CustomMaterial::apply_variant, + ) + .unwrap(); + + materials.remove(&original); + variants.begin(true, &materials); + assert!(variants.variants.is_empty()); + } +} diff --git a/crates/processing_render/src/material/fragment.wgsl b/crates/processing_render/src/material/fragment.wgsl new file mode 100644 index 00000000..d9684dfc --- /dev/null +++ b/crates/processing_render/src/material/fragment.wgsl @@ -0,0 +1,5 @@ +// the fragment stage of a custom material that has none: the vertex color +@fragment +fn fragment(@location(5) color: vec4) -> @location(0) vec4 { + return color; +} diff --git a/crates/processing_render/src/material/mod.rs b/crates/processing_render/src/material/mod.rs index 4fa24e20..63126b4d 100644 --- a/crates/processing_render/src/material/mod.rs +++ b/crates/processing_render/src/material/mod.rs @@ -16,15 +16,20 @@ use bevy::shader::ShaderRef; use bevy_naga_reflect::reflect::ParameterCategory; use processing_core::error::{self, ProcessingError}; -/// The StandardMaterial fragment shader with the per-instance fill. -const PROCESSING_SHADER: Handle = +/// The mesh vertex stage that reads the per-instance fill. +pub(crate) const PROCESSING_VERTEX_SHADER: Handle = bevy::asset::uuid_handle!("6f1f3c1e-2b7a-4d0e-9a53-8c2f4be7a901"); +/// The fragment stage of a custom material that has none. +pub(crate) const PROCESSING_FRAGMENT_SHADER: Handle = + bevy::asset::uuid_handle!("0b9d7c52-41e6-4f3a-8d27-5a1c9e6f2b04"); + pub struct ProcessingMaterialPlugin; impl Plugin for ProcessingMaterialPlugin { fn build(&self, app: &mut App) { - crate::internal_shader!(app, PROCESSING_SHADER, "processing.wgsl"); + crate::internal_shader!(app, PROCESSING_VERTEX_SHADER, "vertex.wgsl"); + crate::internal_shader!(app, PROCESSING_FRAGMENT_SHADER, "fragment.wgsl"); app.add_plugins(bevy::pbr::MaterialPlugin::< ExtendedMaterial, >::default()); @@ -417,17 +422,17 @@ impl From<&ProcessingMaterial> for ProcessingMaterialKey { impl MaterialExtension for ProcessingMaterial { fn vertex_shader() -> ShaderRef { - ::vertex_shader() + PROCESSING_VERTEX_SHADER.into() } fn fragment_shader() -> ShaderRef { - PROCESSING_SHADER.into() + ::fragment_shader() } fn specialize( _pipeline: &MaterialExtensionPipeline, descriptor: &mut RenderPipelineDescriptor, - _layout: &MeshVertexBufferLayoutRef, + layout: &MeshVertexBufferLayoutRef, key: MaterialExtensionKey, ) -> std::result::Result<(), SpecializedMeshPipelineError> { apply_pipeline_state( @@ -435,15 +440,41 @@ impl MaterialExtension for ProcessingMaterial { key.bind_group_data.blend_state, key.bind_group_data.depth_write, ); - if key.bind_group_data.instance_fill - && let Some(fragment) = &mut descriptor.fragment - { - fragment.shader_defs.push("INSTANCE_FILL".into()); + // the prepass has a vertex stage of its own + if key.bind_group_data.instance_fill && uses_processing_vertex(descriptor) { + descriptor.vertex.shader_defs.push("INSTANCE_FILL".into()); + if !layout.0.contains(Mesh::ATTRIBUTE_COLOR) { + output_missing_colors(descriptor); + } } Ok(()) } } +pub(crate) fn uses_processing_vertex(descriptor: &RenderPipelineDescriptor) -> bool { + descriptor.vertex.shader == PROCESSING_VERTEX_SHADER +} + +/// Has the vertex stage output a white color for a mesh that has none. +pub(crate) fn output_missing_colors(descriptor: &mut RenderPipelineDescriptor) { + descriptor + .vertex + .shader_defs + .extend(["VERTEX_COLORS".into(), "MESH_COLORS_MISSING".into()]); + if let Some(fragment) = &mut descriptor.fragment { + fragment.shader_defs.push("VERTEX_COLORS".into()); + } +} + +/// Has the vertex stage output a zero uv for a mesh that has none. +pub(crate) fn output_missing_uvs(descriptor: &mut RenderPipelineDescriptor) { + descriptor.vertex.shader_defs.extend([ + "VERTEX_UVS".into(), + "VERTEX_UVS_A".into(), + "MESH_UVS_MISSING".into(), + ]); +} + /// The projection's y flip (`graphics::Y_FLIP`) mirrors triangle winding, so clockwise is the /// front face; keeps `cull_mode` and `double_sided` lighting correct. A shadow pass rendered /// from a light's view would need the default winding instead. diff --git a/crates/processing_render/src/material/processing.wgsl b/crates/processing_render/src/material/processing.wgsl deleted file mode 100644 index 681a4fff..00000000 --- a/crates/processing_render/src/material/processing.wgsl +++ /dev/null @@ -1,132 +0,0 @@ -// The StandardMaterial fragment shader plus a per-instance fill packed in the mesh tag. - -#import bevy_pbr::{ - pbr_types, - pbr_functions::alpha_discard, - pbr_fragment::pbr_input_from_standard_material, - decal::clustered::apply_decals, -} - -#ifdef PREPASS_PIPELINE -#import bevy_pbr::{ - prepass_io::{VertexOutput, FragmentOutput}, - pbr_deferred_functions::deferred_output, -} -#else -#import bevy_pbr::{ - forward_io::{VertexOutput, FragmentOutput}, - pbr_functions::{apply_pbr_lighting, main_pass_post_lighting_processing}, - pbr_types::STANDARD_MATERIAL_FLAGS_UNLIT_BIT, -} -#endif - -#ifdef VISIBILITY_RANGE_DITHER -#import bevy_pbr::pbr_functions::visibility_range_dither; -#endif - -#ifdef MESHLET_MESH_MATERIAL_PASS -#import bevy_pbr::meshlet_visibility_buffer_resolve::resolve_vertex_output -#endif - -#ifdef OIT_ENABLED -#import bevy_core_pipeline::oit::oit_draw -#endif // OIT_ENABLED - -#ifdef FORWARD_DECAL -#import bevy_pbr::decal::forward::get_forward_decal_info -#endif - -#ifdef INSTANCE_FILL -#import bevy_pbr::mesh_functions::get_tag - -// r in the low byte, as `instance_fill` packs it -fn unpack_instance_fill(tag: u32) -> vec4 { - let srgb = vec4( - f32(tag & 0xffu), - f32((tag >> 8u) & 0xffu), - f32((tag >> 16u) & 0xffu), - f32(tag >> 24u), - ) / 255.0; - let linear = select( - pow((srgb.rgb + 0.055) / 1.055, vec3(2.4)), - srgb.rgb / 12.92, - srgb.rgb <= vec3(0.04045), - ); - return vec4(linear, srgb.a); -} -#endif - -@fragment -fn fragment( -#ifdef MESHLET_MESH_MATERIAL_PASS - @builtin(position) frag_coord: vec4, -#else - vertex_output: VertexOutput, - @builtin(front_facing) is_front: bool, -#endif -) -> FragmentOutput { -#ifdef MESHLET_MESH_MATERIAL_PASS - let vertex_output = resolve_vertex_output(frag_coord); - let is_front = true; -#endif - - var in = vertex_output; - - // If we're in the crossfade section of a visibility range, conditionally - // discard the fragment according to the visibility pattern. -#ifdef VISIBILITY_RANGE_DITHER - visibility_range_dither(in.position, in.visibility_range_dither); -#endif - -#ifdef FORWARD_DECAL - let forward_decal_info = get_forward_decal_info(in); - in.world_position = forward_decal_info.world_position; - in.uv = forward_decal_info.uv; -#endif - - // generate a PbrInput struct from the StandardMaterial bindings - var pbr_input = pbr_input_from_standard_material(in, is_front); - -#ifdef INSTANCE_FILL - pbr_input.material.base_color *= unpack_instance_fill(get_tag(in.instance_index)); -#endif - - // alpha discard - pbr_input.material.base_color = alpha_discard(pbr_input.material, pbr_input.material.base_color); - - // clustered decals - apply_decals(&pbr_input); - -#ifdef PREPASS_PIPELINE - // write the gbuffer, lighting pass id, and optionally normal and motion_vector textures - let out = deferred_output(in, pbr_input); -#else - // in forward mode, we calculate the lit color immediately, and then apply some post-lighting effects here. - // in deferred mode the lit color and these effects will be calculated in the deferred lighting shader - var out: FragmentOutput; - if (pbr_input.material.flags & STANDARD_MATERIAL_FLAGS_UNLIT_BIT) == 0u { - out.color = apply_pbr_lighting(pbr_input); - } else { - out.color = pbr_input.material.base_color; - } - - // apply in-shader post processing (fog, alpha-premultiply, and also tonemapping, debanding if the camera is non-hdr) - // note this does not include fullscreen postprocessing effects like bloom. - out.color = main_pass_post_lighting_processing(pbr_input, out.color); -#endif - -#ifdef OIT_ENABLED - let alpha_mode = pbr_input.material.flags & pbr_types::STANDARD_MATERIAL_FLAGS_ALPHA_MODE_RESERVED_BITS; - if alpha_mode != pbr_types::STANDARD_MATERIAL_FLAGS_ALPHA_MODE_OPAQUE { - // The fragments will only be drawn during the oit resolve pass. - oit_draw(in.position, out.color); - discard; - } -#endif // OIT_ENABLED - -#ifdef FORWARD_DECAL - out.color.a = min(forward_decal_info.alpha, out.color.a); -#endif - - return out; -} diff --git a/crates/processing_render/src/material/vertex.wgsl b/crates/processing_render/src/material/vertex.wgsl new file mode 100644 index 00000000..5b3fc976 --- /dev/null +++ b/crates/processing_render/src/material/vertex.wgsl @@ -0,0 +1,176 @@ +// bevy_pbr's mesh vertex stage, with the per-instance fill multiplied into the vertex color +// and defaults for the uv and color a mesh lacks +#import bevy_pbr::{ + mesh_bindings::mesh, + mesh_functions, + skinning, + morph::{morph_position, morph_normal, morph_tangent}, + forward_io::VertexOutput, + view_transformations::position_world_to_clip, +} + +// forward_io's Vertex, without the attributes a mesh lacks +struct Vertex { + @builtin(instance_index) instance_index: u32, +#ifdef VERTEX_POSITIONS + @location(0) position: vec3, +#endif +#ifdef VERTEX_NORMALS + @location(1) normal: vec3, +#endif +#ifdef VERTEX_UVS_A +#ifndef MESH_UVS_MISSING + @location(2) uv: vec2, +#endif +#endif +#ifdef VERTEX_UVS_B + @location(3) uv_b: vec2, +#endif +#ifdef VERTEX_TANGENTS + @location(4) tangent: vec4, +#endif +#ifdef VERTEX_COLORS +#ifndef MESH_COLORS_MISSING + @location(5) color: vec4, +#endif +#endif +#ifdef SKINNED + @location(6) joint_indices: vec4, + @location(7) joint_weights: vec4, +#endif +#ifdef MORPH_TARGETS + @builtin(vertex_index) index: u32, +#endif +}; + +#ifdef INSTANCE_FILL +// r in the low byte, as `instance_fill` packs it +fn unpack_instance_fill(tag: u32) -> vec4 { + let srgb = vec4( + f32(tag & 0xffu), + f32((tag >> 8u) & 0xffu), + f32((tag >> 16u) & 0xffu), + f32(tag >> 24u), + ) / 255.0; + let linear = select( + pow((srgb.rgb + 0.055) / 1.055, vec3(2.4)), + srgb.rgb / 12.92, + srgb.rgb <= vec3(0.04045), + ); + return vec4(linear, srgb.a); +} +#endif + +#ifdef MORPH_TARGETS +// The instance_index parameter must match vertex_in.instance_index. This is a work around for a wgpu dx12 bug. +// See https://github.com/gfx-rs/naga/issues/2416 +fn morph_vertex(vertex_in: Vertex, instance_index: u32) -> Vertex { + var vertex = vertex_in; + let first_vertex = mesh[instance_index].first_vertex_index; + let vertex_index = vertex.index - first_vertex; + + let weight_count = bevy_pbr::morph::layer_count(instance_index); + for (var i: u32 = 0u; i < weight_count; i ++) { + let weight = bevy_pbr::morph::weight_at(i, instance_index); + if weight == 0.0 { + continue; + } + vertex.position += weight * morph_position(vertex_index, i, instance_index); +#ifdef VERTEX_NORMALS + vertex.normal += weight * morph_normal(vertex_index, i, instance_index); +#endif +#ifdef VERTEX_TANGENTS + vertex.tangent += vec4(weight * morph_tangent(vertex_index, i, instance_index), 0.0); +#endif + } + return vertex; +} +#endif + +@vertex +fn vertex(vertex_no_morph: Vertex) -> VertexOutput { + var out: VertexOutput; + +#ifdef MORPH_TARGETS + var vertex = morph_vertex(vertex_no_morph, vertex_no_morph.instance_index); +#else + var vertex = vertex_no_morph; +#endif + + let mesh_world_from_local = mesh_functions::get_world_from_local(vertex_no_morph.instance_index); + +#ifdef SKINNED + // Use vertex_no_morph.instance_index instead of vertex.instance_index to work around a wgpu dx12 bug. + // See https://github.com/gfx-rs/naga/issues/2416 . + var world_from_local = skinning::skin_model( + vertex.joint_indices, + vertex.joint_weights, + vertex_no_morph.instance_index + ); +#else + var world_from_local = mesh_world_from_local; +#endif + +#ifdef VERTEX_NORMALS +#ifdef SKINNED + out.world_normal = skinning::skin_normals(world_from_local, vertex.normal); +#else + out.world_normal = mesh_functions::mesh_normal_local_to_world( + vertex.normal, + // Use vertex_no_morph.instance_index instead of vertex.instance_index to work around a wgpu dx12 bug. + // See https://github.com/gfx-rs/naga/issues/2416 + vertex_no_morph.instance_index + ); +#endif +#endif + +#ifdef VERTEX_POSITIONS + out.world_position = mesh_functions::mesh_position_local_to_world(world_from_local, vec4(vertex.position, 1.0)); + out.position = position_world_to_clip(out.world_position.xyz); +#endif + +#ifdef VERTEX_UVS_A +#ifdef MESH_UVS_MISSING + out.uv = vec2(0.0); +#else + out.uv = vertex.uv; +#endif +#endif +#ifdef VERTEX_UVS_B + out.uv_b = vertex.uv_b; +#endif + +#ifdef VERTEX_TANGENTS + out.world_tangent = mesh_functions::mesh_tangent_local_to_world( + world_from_local, + vertex.tangent, + // Use vertex_no_morph.instance_index instead of vertex.instance_index to work around a wgpu dx12 bug. + // See https://github.com/gfx-rs/naga/issues/2416 + vertex_no_morph.instance_index + ); +#endif + +#ifdef VERTEX_COLORS +#ifdef MESH_COLORS_MISSING + out.color = vec4(1.0); +#else + out.color = vertex.color; +#endif +#ifdef INSTANCE_FILL + out.color *= unpack_instance_fill(mesh_functions::get_tag(vertex_no_morph.instance_index)); +#endif +#endif + +#ifdef VERTEX_OUTPUT_INSTANCE_INDEX + // Use vertex_no_morph.instance_index instead of vertex.instance_index to work around a wgpu dx12 bug. + // See https://github.com/gfx-rs/naga/issues/2416 + out.instance_index = vertex_no_morph.instance_index; +#endif + +#ifdef VISIBILITY_RANGE_DITHER + out.visibility_range_dither = mesh_functions::get_visibility_range_dither_level( + vertex_no_morph.instance_index, mesh_world_from_local[3]); +#endif + + return out; +} diff --git a/crates/processing_render/src/render/mod.rs b/crates/processing_render/src/render/mod.rs index d1b15766..0d251bef 100644 --- a/crates/processing_render/src/render/mod.rs +++ b/crates/processing_render/src/render/mod.rs @@ -17,7 +17,7 @@ use bevy::{ }, ecs::{query::Has, system::SystemParam}, math::{Affine2, Affine3A, Vec3A}, - mesh::PrimitiveTopology, + mesh::{MeshTag, PrimitiveTopology, VertexAttributeValues}, pbr::gpu_instance_batch::GpuBatchedMesh3d, pbr::wireframe::{WireframeMaterial, WireframeTopology}, prelude::*, @@ -44,7 +44,7 @@ use crate::{ image::Image, light::ProcessingLight, material::ProcessingMaterial, - material::custom::CustomMaterial, + material::custom::{CustomMaterial, CustomVariants, VariantKey}, particles::{Particles, ParticlesDraw}, render::{material::UntypedMaterial, primitive::rect}, text::font::TextContext, @@ -76,6 +76,7 @@ pub struct RenderResources<'w, 's> { meshes: ResMut<'w, Assets>, materials: ResMut<'w, Assets>, custom_materials: ResMut<'w, Assets>, + custom_variants: ResMut<'w, CustomVariants>, line_materials: Res<'w, LineMaterials>, line_material_assets: ResMut<'w, Assets>, wireframe_materials: ResMut<'w, Assets>, @@ -277,6 +278,10 @@ pub fn flush_draw_commands( >, p_lights: Query<(&ProcessingLight, &Transform)>, ) { + let materials_changed = res.custom_materials.is_changed(); + res.custom_variants + .begin(materials_changed, &res.custom_materials); + for ( graphics_entity, mut cmd_buffer, @@ -1203,11 +1208,8 @@ pub fn flush_draw_commands( warn!("Could not find material for entity {:?}", mat_entity); continue; }; - clone_custom_material_with_blend( - &mut res.custom_materials, - &untyped.0, - *blend_state, - ) + // a particle's tag is not a fill + material_variant(&mut res, &untyped.0, *blend_state, false) } _ => material_key .to_material(&mut res.materials, sort_bias(batch.draw_index)), @@ -1619,6 +1621,7 @@ fn spawn_mesh( // the matrix is baked into the vertices let transform = Transform::from_xyz(0.0, 0.0, z_offset); + let mut custom_shader = false; let material_handle = match key { MaterialKey::Custom { entity, @@ -1628,18 +1631,23 @@ fn spawn_mesh( warn!("Custom material entity {:?} not found", entity); return; }; - clone_custom_material_with_blend(&mut res.custom_materials, &untyped.0, *blend_state) + custom_shader = is_custom_shader(&untyped.0); + material_variant(res, &untyped.0, *blend_state, true) } _ => key.to_material(&mut res.materials, sort_bias(batch.draw_index)), }; - res.commands.spawn(( + let mut entity = res.commands.spawn(( Mesh3d(mesh_handle), UntypedMaterial(material_handle), FlushTransient(batch.graphics_entity), transform, batch.render_layers.clone(), )); + if custom_shader { + // the vertices carry the fill + entity.insert(MeshTag(WHITE_FILL)); + } } fn needs_batch(batch: &BatchState, state: &RenderState, material_key: &MaterialKey) -> bool { @@ -1689,25 +1697,39 @@ fn apply_shape_mode(mode: ShapeMode, a: f32, b: f32, c: f32, d: f32) -> (f32, f3 } } -fn clone_custom_material_with_blend( - custom_materials: &mut Assets, +/// Whether a user material is a custom shader, not a built-in material kind. +fn is_custom_shader(material: &UntypedHandle) -> bool { + material.type_id() == std::any::TypeId::of::() +} + +/// The custom material as a draw needs it; the original when nothing differs. +/// A sketch's custom material as a draw needs it; the original when nothing differs. +fn material_variant( + res: &mut RenderResources, original: &UntypedHandle, blend_state: Option, + instance_fill: bool, ) -> UntypedHandle { - match blend_state { - None => original.clone(), - Some(bs) => { - let Ok(handle) = original.clone().try_typed::() else { - return original.clone(); - }; - let Some(original_mat) = custom_materials.get(&handle) else { - return original.clone(); - }; - let mut variant = original_mat.clone(); - variant.blend_state = Some(bs); - custom_materials.add(variant).untyped() - } + let Ok(handle) = original.clone().try_typed::() else { + return original.clone(); + }; + let Some(material) = res.custom_materials.get(&handle) else { + return original.clone(); + }; + if blend_state.is_none() && material.instance_fill == instance_fill { + return original.clone(); } + let key = VariantKey { + blend_state, + instance_fill, + }; + let variant = res.custom_variants.get( + &mut res.custom_materials, + &handle, + key, + CustomMaterial::apply_variant, + ); + variant.map_or_else(|| original.clone(), Handle::untyped) } fn material_key_with_color( @@ -2061,22 +2083,54 @@ enum MeshPaint { Lines, } -/// The key and mesh tag for a fill carried per instance as 8-bit sRGB, if it can be. -fn instance_fill(key: MaterialKey, fill: Color, quantize: bool) -> (MaterialKey, Option) { +/// A white opaque fill as a mesh tag. +const WHITE_FILL: u32 = u32::MAX; + +/// A fill as a mesh tag: sRGB8 RGBA with red in the low byte. +fn pack_fill(fill: Color) -> u32 { + u32::from_le_bytes(fill.to_srgba().to_u8_array()) +} + +/// The fill as a mesh tag, if 8-bit sRGB can carry it. +fn fill_tag(fill: Color, quantize: bool) -> Option { let srgba = fill.to_srgba(); let components = srgba.to_f32_array(); if components.iter().any(|c| !(0.0..=1.0).contains(c)) { - return (key, None); + return None; } let bytes = srgba.to_u8_array(); let exact = components .iter() .zip(bytes) .all(|(c, b)| (c - b as f32 / 255.0).abs() < 1e-4); - if !exact && !quantize { - return (key, None); + (exact || quantize).then(|| pack_fill(fill)) +} + +/// A copy of the mesh with the fill multiplied into its vertex colors. +fn mesh_with_fill(mesh: &Mesh, fill: Color) -> Mesh { + let fill = fill.to_linear().to_f32_array(); + let mut mesh = mesh.clone(); + match mesh.attribute_mut(Mesh::ATTRIBUTE_COLOR) { + Some(VertexAttributeValues::Float32x4(colors)) => { + for color in colors { + for (channel, fill) in color.iter_mut().zip(fill) { + *channel *= fill; + } + } + } + _ => { + let colors = vec![fill; mesh.count_vertices()]; + mesh.insert_attribute(Mesh::ATTRIBUTE_COLOR, colors); + } } - let tag = u32::from_le_bytes(bytes); + mesh +} + +/// The key and mesh tag for a fill carried per instance as 8-bit sRGB, if it can be. +fn instance_fill(key: MaterialKey, fill: Color, quantize: bool) -> (MaterialKey, Option) { + let Some(tag) = fill_tag(fill, quantize) else { + return (key, None); + }; match key { MaterialKey::Color { .. } => (key, Some(tag)), MaterialKey::Pbr { .. } => { @@ -2104,6 +2158,7 @@ fn draw_mesh3d( if res.meshes.get(&draw.mesh).is_some_and(mesh_is_empty) { return; } + let mut mesh = draw.mesh; let (color, stroke) = match draw.paint { MeshPaint::Surface { edges } => { @@ -2128,12 +2183,19 @@ fn draw_mesh3d( warn!("Custom material entity {:?} not found", entity); return; }; - let material = clone_custom_material_with_blend( - &mut res.custom_materials, - &untyped.0, - state.style.blend_state, - ); - (Some(material), None) + let material = material_variant(res, &untyped.0, state.style.blend_state, true); + let tag = if !is_custom_shader(&untyped.0) { + None + } else if let Some(tag) = fill_tag(color, draws.quantize_fill) { + Some(tag) + } else { + // a fill 8-bit sRGB cannot carry is baked into the vertex colors + if let Some(filled) = res.meshes.get(&mesh).map(|m| mesh_with_fill(m, color)) { + mesh = res.meshes.add(filled); + } + Some(WHITE_FILL) + }; + (Some(material), tag) } style_key => { let textured_translucent = matches!( @@ -2215,7 +2277,7 @@ fn draw_mesh3d( &mut res.commands, batch.graphics_entity, PooledDraw { - mesh: draw.mesh, + mesh, material, tag, wireframe, diff --git a/tests/visual/cases.toml b/tests/visual/cases.toml index 843b0229..9ccd4a3b 100644 --- a/tests/visual/cases.toml +++ b/tests/visual/cases.toml @@ -53,6 +53,10 @@ python = "curves.py" name = "py_custom_material" python = "custom_material.py" +[[case]] +name = "py_custom_vertex" +python = "custom_vertex.py" + [[case]] name = "py_feedback" python = "feedback.py" From 8b49a2720331a272066ebd10ace74c417e0a7644 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?charlotte=20=F0=9F=8C=B8?= Date: Mon, 30 Nov 2026 13:41:35 -0800 Subject: [PATCH 3/4] Clippy. --- crates/processing_render/src/render/primitive/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/processing_render/src/render/primitive/mod.rs b/crates/processing_render/src/render/primitive/mod.rs index 33e69905..0d08ece4 100644 --- a/crates/processing_render/src/render/primitive/mod.rs +++ b/crates/processing_render/src/render/primitive/mod.rs @@ -255,7 +255,7 @@ pub fn bake_transform( && let Some(Indices::U32(indices)) = mesh.indices_mut() { let first_index = first_index.min(indices.len()); - for triangle in indices[first_index..].chunks_exact_mut(3) { + for triangle in indices[first_index..].as_chunks_mut::<3>().0 { triangle.swap(1, 2); } } From 57b00fb3d0ae3fdfa7608c2f2177c4e33fd33689 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?charlotte=20=F0=9F=8C=B8?= Date: Mon, 30 Nov 2026 14:28:32 -0800 Subject: [PATCH 4/4] One first frame test. --- .../examples/Demos/Tests/first_frame.py | 75 +++++++++++++++++++ tests/visual/cases.toml | 27 +------ 2 files changed, 78 insertions(+), 24 deletions(-) create mode 100644 crates/processing_pyo3/examples/Demos/Tests/first_frame.py diff --git a/crates/processing_pyo3/examples/Demos/Tests/first_frame.py b/crates/processing_pyo3/examples/Demos/Tests/first_frame.py new file mode 100644 index 00000000..b94cb009 --- /dev/null +++ b/crates/processing_pyo3/examples/Demos/Tests/first_frame.py @@ -0,0 +1,75 @@ +"""One of everything, captured on the first frame. + +A shader or pipeline that is not ready on frame 1 silently drops its draws, so each kind +of draw gets its own part of the canvas: whatever is missing is the kind that dropped. +""" +from processing_py import * +from random import seed, uniform + +points = None +mat = None + + +def setup(): + global points, mat + size(800, 600) + mode_3d() + + mat = create_material(load_shader("shaders/custom_material.wesl"), color=[0.3, 0.6, 1.0, 1.0]) + + seed(1) + count = 2000 + points = create_particles(count, attributes=[Attribute.position()]) + positions = [] + for _ in range(count): + positions.append([220 + uniform(-60, 60), 120 + uniform(-60, 60), uniform(-60, 60)]) + points.buffer("position").write(positions) + + +def draw(): + camera_position(0.0, 0.0, 500.0) + camera_look_at(0.0, 0.0, 0.0) + background(20) + + # a 2D shape + no_stroke() + fill(255, 150, 40) + rect(-340, -240, 160, 120) + + # strokes + no_fill() + stroke(255) + stroke_weight(6) + ellipse(0, -180, 140, 110) + line(-60, -180, 60, -180) + + # text + no_stroke() + fill(255) + text_size(40) + text_align(CENTER, CENTER) + text("frame 1", 250, -180) + + # a 3D primitive + fill(60, 200, 110) + push_matrix() + translate(-250, 120, 0) + rotate_y(0.6) + rotate_x(0.4) + box(110) + pop_matrix() + + # a custom material + push_style() + material(mat) + push_matrix() + translate(0, 120, 0) + sphere(65) + pop_matrix() + pop_style() + + # particle points + particles(points) + + +run() diff --git a/tests/visual/cases.toml b/tests/visual/cases.toml index 9ccd4a3b..e6b650cf 100644 --- a/tests/visual/cases.toml +++ b/tests/visual/cases.toml @@ -182,29 +182,8 @@ python = "text.py" name = "py_window_controls" python = "window_controls.py" -# first-frame captures: an unready shader or pipeline drops its draws - -[[case]] -name = "py_first_frame_shapes" -python = "shapes.py" -frame = 1 - -[[case]] -name = "py_first_frame_primitives_3d" -python = "primitives_3d.py" -frame = 1 - +# an unready shader or pipeline drops its draws on the first frame [[case]] -name = "py_first_frame_text" -python = "text.py" -frame = 1 - -[[case]] -name = "py_first_frame_custom_material" -python = "custom_material.py" -frame = 1 - -[[case]] -name = "py_first_frame_particles_points" -python = "particles_points.py" +name = "py_first_frame" +python = "Demos/Tests/first_frame.py" frame = 1