diff --git a/crates/processing_ffi/src/lib.rs b/crates/processing_ffi/src/lib.rs index 6c3797e9..1ee0a73f 100644 --- a/crates/processing_ffi/src/lib.rs +++ b/crates/processing_ffi/src/lib.rs @@ -631,8 +631,8 @@ pub extern "C" fn processing_set_blend_mode(graphics_id: u64, mode: u8) { error::clear_error(); let graphics_entity = Entity::from_bits(graphics_id); error::check(|| { - let blend_state = processing::prelude::BlendMode::try_from(mode)?.to_blend_state(); - graphics_record_command(graphics_entity, DrawCommand::BlendMode(blend_state)) + let blend = processing::prelude::BlendMode::try_from(mode)?.to_blend(); + graphics_record_command(graphics_entity, DrawCommand::BlendMode(blend)) }); } @@ -652,7 +652,10 @@ pub extern "C" fn processing_set_custom_blend_mode( let blend_state = custom_blend_state( color_src, color_dst, color_op, alpha_src, alpha_dst, alpha_op, )?; - graphics_record_command(graphics_entity, DrawCommand::BlendMode(Some(blend_state))) + graphics_record_command( + graphics_entity, + DrawCommand::BlendMode(Some(Blend::Equation(blend_state))), + ) }); } @@ -2986,9 +2989,31 @@ pub extern "C" fn processing_material(window_id: u64, mat_id: u64) { } #[unsafe(no_mangle)] -pub extern "C" fn processing_material_set_alpha_mode(mat_id: u64, mode: u8, cutoff: f32) { +pub extern "C" fn processing_material_set_mask(mat_id: u64, cutoff: f32) { + error::clear_error(); + error::check(|| material_set_mask(Entity::from_bits(mat_id), Some(cutoff))); +} + +#[unsafe(no_mangle)] +pub extern "C" fn processing_material_no_mask(mat_id: u64) { error::clear_error(); - error::check(|| material_set_alpha_mode(Entity::from_bits(mat_id), mode, cutoff)); + error::check(|| material_set_mask(Entity::from_bits(mat_id), None)); +} + +#[unsafe(no_mangle)] +pub extern "C" fn processing_material_set_blend_mode(mat_id: u64, mode: u8) { + error::clear_error(); + error::check(|| { + let blend = processing::prelude::BlendMode::try_from(mode)?.to_material_blend(); + material_set_blend_mode(Entity::from_bits(mat_id), Some(blend)) + }); +} + +/// The material follows the current blend mode again. +#[unsafe(no_mangle)] +pub extern "C" fn processing_material_no_blend_mode(mat_id: u64) { + error::clear_error(); + error::check(|| material_set_blend_mode(Entity::from_bits(mat_id), None)); } #[unsafe(no_mangle)] @@ -3024,7 +3049,10 @@ pub extern "C" fn processing_material_set_custom_blend_mode( let blend_state = custom_blend_state( color_src, color_dst, color_op, alpha_src, alpha_dst, alpha_op, )?; - material_set_custom_blend(Entity::from_bits(mat_id), blend_state) + material_set_blend_mode( + Entity::from_bits(mat_id), + Some(Blend::Equation(blend_state)), + ) }); } diff --git a/crates/processing_node/src/lib.rs b/crates/processing_node/src/lib.rs index a11e97db..d268b84c 100644 --- a/crates/processing_node/src/lib.rs +++ b/crates/processing_node/src/lib.rs @@ -485,8 +485,8 @@ pub fn js_shear_y(graphics_id: BigInt, angle: f64) -> Result<()> { pub fn js_set_blend_mode(graphics_id: BigInt, mode: u8) -> Result<()> { let graphics = ent(graphics_id); check((|| { - let blend_state = BlendMode::try_from(mode)?.to_blend_state(); - graphics_record_command(graphics, DrawCommand::BlendMode(blend_state)) + let blend = BlendMode::try_from(mode)?.to_blend(); + graphics_record_command(graphics, DrawCommand::BlendMode(blend)) })()) } @@ -505,7 +505,10 @@ pub fn js_set_custom_blend_mode( let blend_state = custom_blend_state( color_src, color_dst, color_op, alpha_src, alpha_dst, alpha_op, )?; - graphics_record_command(graphics, DrawCommand::BlendMode(Some(blend_state))) + graphics_record_command( + graphics, + DrawCommand::BlendMode(Some(Blend::Equation(blend_state))), + ) })()) } @@ -2088,9 +2091,29 @@ pub fn js_material(graphics_id: BigInt, mat_id: BigInt) -> Result<()> { record(graphics_id, DrawCommand::Material(ent(mat_id))) } -#[napi(js_name = "materialSetAlphaMode")] -pub fn js_material_set_alpha_mode(mat_id: BigInt, mode: u8, cutoff: f64) -> Result<()> { - check(material_set_alpha_mode(ent(mat_id), mode, cutoff as f32)) +#[napi(js_name = "materialSetMask")] +pub fn js_material_set_mask(mat_id: BigInt, cutoff: f64) -> Result<()> { + check(material_set_mask(ent(mat_id), Some(cutoff as f32))) +} + +#[napi(js_name = "materialNoMask")] +pub fn js_material_no_mask(mat_id: BigInt) -> Result<()> { + check(material_set_mask(ent(mat_id), None)) +} + +#[napi(js_name = "materialSetBlendMode")] +pub fn js_material_set_blend_mode(mat_id: BigInt, mode: u8) -> Result<()> { + let mat = ent(mat_id); + check((|| { + let blend = BlendMode::try_from(mode)?.to_material_blend(); + material_set_blend_mode(mat, Some(blend)) + })()) +} + +/// The material follows the current blend mode again. +#[napi(js_name = "materialNoBlendMode")] +pub fn js_material_no_blend_mode(mat_id: BigInt) -> Result<()> { + check(material_set_blend_mode(ent(mat_id), None)) } #[napi(js_name = "materialSetDoubleSided")] @@ -2123,7 +2146,7 @@ pub fn js_material_set_custom_blend_mode( let blend_state = custom_blend_state( color_src, color_dst, color_op, alpha_src, alpha_dst, alpha_op, )?; - material_set_custom_blend(mat, blend_state) + material_set_blend_mode(mat, Some(Blend::Equation(blend_state))) })()) } diff --git a/crates/processing_pyo3/src/constants.rs b/crates/processing_pyo3/src/constants.rs index 81a19100..f5fe72be 100644 --- a/crates/processing_pyo3/src/constants.rs +++ b/crates/processing_pyo3/src/constants.rs @@ -33,7 +33,6 @@ pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add("THRESHOLD", crate::filter::THRESHOLD_U8)?; m.add("POSTERIZE", crate::filter::POSTERIZE_U8)?; m.add("BLUR", crate::filter::BLUR_U8)?; - m.add("OPAQUE", crate::filter::OPAQUE_U8)?; m.add("ERODE", crate::filter::ERODE_U8)?; m.add("DILATE", crate::filter::DILATE_U8)?; @@ -192,6 +191,12 @@ pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add("MULTIPLY", PyBlendMode::from_preset(BlendMode::Multiply))?; m.add("SCREEN", PyBlendMode::from_preset(BlendMode::Screen))?; m.add("REPLACE", PyBlendMode::from_preset(BlendMode::Replace))?; + // also the `filter(OPAQUE)` constant + m.add("OPAQUE", PyBlendMode::from_preset(BlendMode::Opaque))?; + m.add( + "PREMULTIPLIED", + PyBlendMode::from_preset(BlendMode::Premultiplied), + )?; Ok(()) } diff --git a/crates/processing_pyo3/src/filter.rs b/crates/processing_pyo3/src/filter.rs index c59aeaef..c7b50b50 100644 --- a/crates/processing_pyo3/src/filter.rs +++ b/crates/processing_pyo3/src/filter.rs @@ -75,7 +75,16 @@ pub fn resolve_filter( return resolve_user_filter(shader.entity, args, kwargs); } - let Ok(kind_u8) = kind.extract::() else { + // `OPAQUE` is one constant, shared with `blend_mode()` + let opaque = kind + .extract::>() + .is_ok_and(|mode| mode.is_opaque()); + let kind_u8 = if opaque { + Ok(OPAQUE_U8) + } else { + kind.extract::() + }; + let Ok(kind_u8) = kind_u8 else { return Err(PyTypeError::new_err( "filter(): first argument must be a filter constant (INVERT, GRAY, ...) or a Shader", )); diff --git a/crates/processing_pyo3/src/graphics.rs b/crates/processing_pyo3/src/graphics.rs index 28f24fb6..f10ee559 100644 --- a/crates/processing_pyo3/src/graphics.rs +++ b/crates/processing_pyo3/src/graphics.rs @@ -232,14 +232,15 @@ fn cuda_import_from_interface( #[pyclass(name = "BlendMode", from_py_object)] #[derive(Clone)] pub struct PyBlendMode { - pub(crate) blend_state: Option, + /// `None` is `BLEND`, the default + pub(crate) blend: Option, name: Option<&'static str>, } impl PyBlendMode { pub(crate) fn from_preset(mode: BlendMode) -> Self { Self { - blend_state: mode.to_blend_state(), + blend: mode.to_blend(), name: Some(mode.name()), } } @@ -247,7 +248,22 @@ impl PyBlendMode { /// The composite-shader mode code (the `BlendMode` discriminant) for this /// blend mode, or `None` for custom modes with no named preset. pub(crate) fn composite_mode(&self) -> Option { - self.name.and_then(BlendMode::from_name).map(|m| m as u32) + self.name + .and_then(BlendMode::from_name) + // the compositor has no code past `REPLACE` + .filter(|m| *m as u32 <= BlendMode::Replace as u32) + .map(|m| m as u32) + } + + /// What a material set to this mode does; `BLEND` always alpha blends there. + pub(crate) fn material_blend(&self) -> Blend { + self.blend.unwrap_or(Blend::Equation( + bevy::render::render_resource::BlendState::ALPHA_BLENDING, + )) + } + + pub(crate) fn is_opaque(&self) -> bool { + self.blend == Some(Blend::Opaque) } } @@ -268,7 +284,7 @@ impl PyBlendMode { ) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; Ok(Self { - blend_state: Some(blend_state), + blend: Some(Blend::Equation(blend_state)), name: None, }) } @@ -2646,7 +2662,7 @@ impl Graphics { } pub fn blend_mode(&self, mode: &PyBlendMode) -> PyResult<()> { - graphics_record_command(self.entity, DrawCommand::BlendMode(mode.blend_state)) + graphics_record_command(self.entity, DrawCommand::BlendMode(mode.blend)) .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } diff --git a/crates/processing_pyo3/src/material.rs b/crates/processing_pyo3/src/material.rs index 282a63e2..f94c7c88 100644 --- a/crates/processing_pyo3/src/material.rs +++ b/crates/processing_pyo3/src/material.rs @@ -144,9 +144,6 @@ fn apply_kwargs(entity: Entity, kwargs: &Bound<'_, PyDict>) -> PyResult<()> { "unlit" => material_set_unlit(entity, py_truthy(&value)?).map_err(rt)?, "double_sided" => material_set_double_sided(entity, py_truthy(&value)?).map_err(rt)?, "depth_write" => material_set_depth_write(entity, py_truthy(&value)?).map_err(rt)?, - "alpha_mode" => { - material_set_alpha_mode(entity, value.extract::()?, 0.5).map_err(rt)? - } _ => { let v = py_to_shader_value(&value)?; material_set(entity, &name, v).map_err(rt)?; @@ -197,18 +194,14 @@ impl Material { apply_kwargs(self.entity, kwargs) } - pub fn opaque(&self) -> PyResult<()> { - material_set_alpha_mode(self.entity, 0, 0.0).map_err(rt) - } - /// Discards fragments with alpha below `cutoff`. #[pyo3(signature = (cutoff=0.5))] pub fn mask(&self, cutoff: f32) -> PyResult<()> { - material_set_alpha_mode(self.entity, 1, cutoff).map_err(rt) + material_set_mask(self.entity, Some(cutoff)).map_err(rt) } - pub fn transparent(&self) -> PyResult<()> { - material_set_alpha_mode(self.entity, 2, 0.0).map_err(rt) + pub fn no_mask(&self) -> PyResult<()> { + material_set_mask(self.entity, None).map_err(rt) } /// Skips lighting; errors on a custom shader, which does its own. @@ -227,12 +220,12 @@ impl Material { material_set_depth_write(self.entity, value).map_err(rt) } - /// Blends with what's behind it using a `BlendMode` (`ADD`, `MULTIPLY`, a custom one, ...). - pub fn blend_mode(&self, mode: &crate::graphics::PyBlendMode) -> PyResult<()> { - let state = mode - .blend_state - .unwrap_or(bevy::render::render_resource::BlendState::ALPHA_BLENDING); - material_set_custom_blend(self.entity, state).map_err(rt) + /// How it combines with what's behind it (`OPAQUE`, `BLEND`, `ADD`, a custom `BlendMode`, + /// ...); `None` follows the current `blend_mode()`. + #[pyo3(signature = (mode, /))] + pub fn blend_mode(&self, mode: Option>) -> PyResult<()> { + let blend = mode.map(|mode| mode.material_blend()); + material_set_blend_mode(self.entity, blend).map_err(rt) } } diff --git a/crates/processing_render/src/gltf.rs b/crates/processing_render/src/gltf.rs index 3ca6e1c7..bbe19100 100644 --- a/crates/processing_render/src/gltf.rs +++ b/crates/processing_render/src/gltf.rs @@ -331,11 +331,7 @@ pub fn material( .resource_mut::>() .add(ExtendedMaterial { base: standard, - extension: ProcessingMaterial { - blend_state: None, - depth_write: None, - instance_fill: false, - }, + extension: ProcessingMaterial::default(), }); let entity = world.spawn(UntypedMaterial(handle.untyped())).id(); Ok(entity) diff --git a/crates/processing_render/src/lib.rs b/crates/processing_render/src/lib.rs index c0590bbd..a3c97714 100644 --- a/crates/processing_render/src/lib.rs +++ b/crates/processing_render/src/lib.rs @@ -2106,10 +2106,11 @@ pub fn material_set( }) } -pub fn material_set_alpha_mode(entity: Entity, mode: u8, cutoff: f32) -> error::Result<()> { +/// Discards a material's fragments with alpha below `cutoff`; `None` keeps them all. +pub fn material_set_mask(entity: Entity, cutoff: Option) -> error::Result<()> { app_mut(|app| { app.world_mut() - .run_system_cached_with(material::set_alpha_mode, (entity, mode, cutoff)) + .run_system_cached_with(material::set_mask, (entity, cutoff)) .unwrap() }) } @@ -2138,13 +2139,14 @@ pub fn material_set_depth_write(entity: Entity, value: bool) -> error::Result<() }) } -pub fn material_set_custom_blend( +/// How a material combines with what is behind it; `None` follows the current blend mode. +pub fn material_set_blend_mode( entity: Entity, - blend: bevy::render::render_resource::BlendState, + blend: Option, ) -> error::Result<()> { app_mut(|app| { app.world_mut() - .run_system_cached_with(material::set_custom_blend, (entity, blend)) + .run_system_cached_with(material::set_blend_mode, (entity, blend)) .unwrap() }) } diff --git a/crates/processing_render/src/material/custom.rs b/crates/processing_render/src/material/custom.rs index 52db2ea8..043b0118 100644 --- a/crates/processing_render/src/material/custom.rs +++ b/crates/processing_render/src/material/custom.rs @@ -131,6 +131,9 @@ pub struct CustomMaterial { /// the vertex input locations the vertex stage reads, as bits pub vertex_inputs: u32, pub blend_state: Option, + /// no blend mode of its own, so it follows the current one when drawn + pub inherit_blend: bool, + pub mask: Option, pub alpha_mode: AlphaMode, pub double_sided: Option, pub depth_write: Option, @@ -657,6 +660,8 @@ pub fn create_custom( has_fragment, vertex_inputs: stage_locations(&program.module, naga::ShaderStage::Vertex, false), blend_state: None, + inherit_blend: true, + mask: None, alpha_mode: AlphaMode::Opaque, double_sided: None, depth_write: None, @@ -1192,6 +1197,8 @@ mod tests { has_fragment: true, vertex_inputs: 0, blend_state: None, + inherit_blend: true, + mask: None, alpha_mode: AlphaMode::Opaque, double_sided: None, depth_write: None, diff --git a/crates/processing_render/src/material/mod.rs b/crates/processing_render/src/material/mod.rs index 63126b4d..1f8dbac7 100644 --- a/crates/processing_render/src/material/mod.rs +++ b/crates/processing_render/src/material/mod.rs @@ -2,6 +2,7 @@ pub mod custom; pub mod pbr; use crate::compute; +use crate::render::command::Blend; use crate::render::material::UntypedMaterial; use crate::shader_value::ShaderValue; use bevy::material::descriptor::RenderPipelineDescriptor; @@ -30,6 +31,7 @@ impl Plugin for ProcessingMaterialPlugin { fn build(&self, app: &mut App) { crate::internal_shader!(app, PROCESSING_VERTEX_SHADER, "vertex.wgsl"); crate::internal_shader!(app, PROCESSING_FRAGMENT_SHADER, "fragment.wgsl"); + app.init_resource::>(); app.add_plugins(bevy::pbr::MaterialPlugin::< ExtendedMaterial, >::default()); @@ -62,9 +64,8 @@ pub fn create_pbr( ..default() }, extension: ProcessingMaterial { - blend_state: None, - depth_write: None, - instance_fill: false, + inherit_blend: true, + ..default() }, }); commands.spawn(UntypedMaterial(handle.untyped())).id() @@ -198,36 +199,36 @@ fn edit_material( Err(ProcessingError::MaterialNotFound) } -fn resolve_alpha_mode(mode: u8, cutoff: f32) -> error::Result { - Ok(match mode { - 0 => AlphaMode::Opaque, - 1 => AlphaMode::Mask(cutoff), - 2 => AlphaMode::Blend, - 3 => AlphaMode::Premultiplied, - 4 => AlphaMode::Add, - 5 => AlphaMode::Multiply, - _ => { - return Err(ProcessingError::InvalidArgument(format!( - "unknown alpha_mode value: {mode}" - ))); - } - }) -} - fn set_base_double_sided(base: &mut StandardMaterial, value: bool) { base.double_sided = value; base.cull_mode = if value { None } else { Some(Face::Back) }; } -pub fn set_alpha_mode( - In((entity, mode, cutoff)): In<(Entity, u8, f32)>, +/// The alpha mode of a material that blends by `blend_state` and masks at `mask`. +fn alpha_mode(blend_state: Option, mask: Option) -> AlphaMode { + match (blend_state, mask) { + // bevy's own alpha mode for this equation + (Some(BlendState::PREMULTIPLIED_ALPHA_BLENDING), _) => AlphaMode::Premultiplied, + (Some(_), mask) => { + if mask.is_some() { + // bevy's alpha modes cannot mask and blend at once + bevy::log::warn_once!("a mask has no effect on a material that blends"); + } + AlphaMode::Blend + } + (None, Some(cutoff)) => AlphaMode::Mask(cutoff), + (None, None) => AlphaMode::Opaque, + } +} + +/// Discards a material's fragments with alpha below `cutoff`; `None` keeps them all. +pub fn set_mask( + In((entity, cutoff)): In<(Entity, Option)>, material_handles: Query<&UntypedMaterial>, mut pbr: ResMut>, mut particles: ResMut>, mut custom: ResMut>, ) -> error::Result<()> { - let alpha_mode = resolve_alpha_mode(mode, cutoff)?; - let opaque = matches!(alpha_mode, AlphaMode::Opaque); edit_material( entity, &material_handles, @@ -237,17 +238,13 @@ pub fn set_alpha_mode( |m| { match m { MaterialMut::Pbr(mat) => { - mat.base.alpha_mode = alpha_mode; - if opaque { - mat.extension.blend_state = None; - } + mat.extension.mask = cutoff; + mat.base.alpha_mode = alpha_mode(mat.extension.blend_state, cutoff); } - MaterialMut::Particles(mat) => mat.base.alpha_mode = alpha_mode, + MaterialMut::Particles(mat) => mat.base.alpha_mode = alpha_mode(None, cutoff), MaterialMut::Custom(mat) => { - mat.alpha_mode = alpha_mode; - if opaque { - mat.blend_state = None; - } + mat.mask = cutoff; + mat.alpha_mode = alpha_mode(mat.blend_state, cutoff); } } Ok(()) @@ -338,13 +335,18 @@ pub fn set_depth_write( ) } -pub fn set_custom_blend( - In((entity, blend)): In<(Entity, BlendState)>, +/// How a material combines with what is behind it; `None` follows the current blend mode. +pub fn set_blend_mode( + In((entity, blend)): In<(Entity, Option)>, material_handles: Query<&UntypedMaterial>, mut pbr: ResMut>, mut particles: ResMut>, mut custom: ResMut>, ) -> error::Result<()> { + let blend_state = match blend { + Some(Blend::Equation(blend_state)) => Some(blend_state), + Some(Blend::Opaque) | None => None, + }; edit_material( entity, &material_handles, @@ -353,16 +355,18 @@ pub fn set_custom_blend( &mut custom, |m| match m { MaterialMut::Pbr(mat) => { - mat.extension.blend_state = Some(blend); - mat.base.alpha_mode = AlphaMode::Blend; + mat.extension.inherit_blend = blend.is_none(); + mat.extension.blend_state = blend_state; + mat.base.alpha_mode = alpha_mode(blend_state, mat.extension.mask); Ok(()) } MaterialMut::Particles(_) => Err(ProcessingError::InvalidArgument( - "custom blend is not yet configurable on particle materials".to_string(), + "a blend mode is not yet configurable on particle materials".to_string(), )), MaterialMut::Custom(mat) => { - mat.blend_state = Some(blend); - mat.alpha_mode = AlphaMode::Blend; + mat.inherit_blend = blend.is_none(); + mat.blend_state = blend_state; + mat.alpha_mode = alpha_mode(blend_state, mat.mask); Ok(()) } }, @@ -397,6 +401,10 @@ pub fn destroy( #[bind_group_data(ProcessingMaterialKey)] pub struct ProcessingMaterial { pub blend_state: Option, + /// no blend mode of its own, so it follows the current one when drawn + pub inherit_blend: bool, + /// kept apart from the alpha mode, which a blend mode replaces + pub mask: Option, pub depth_write: Option, /// the fill is the sRGB8 RGBA color packed in each instance's `MeshTag` pub instance_fill: bool, diff --git a/crates/processing_render/src/render/command.rs b/crates/processing_render/src/render/command.rs index 4dee737f..5187af8a 100644 --- a/crates/processing_render/src/render/command.rs +++ b/crates/processing_render/src/render/command.rs @@ -349,6 +349,16 @@ pub enum BlendMode { Multiply = 7, Screen = 8, Replace = 9, + Opaque = 10, + Premultiplied = 11, +} + +/// How a draw combines with what is behind it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Blend { + /// drawn solid, whatever its alpha + Opaque, + Equation(BlendState), } impl TryFrom for BlendMode { @@ -366,6 +376,8 @@ impl TryFrom for BlendMode { 7 => Ok(Self::Multiply), 8 => Ok(Self::Screen), 9 => Ok(Self::Replace), + 10 => Ok(Self::Opaque), + 11 => Ok(Self::Premultiplied), _ => Err(ProcessingError::InvalidArgument(format!( "unknown blend mode: {v}" ))), @@ -446,6 +458,8 @@ impl BlendMode { Self::Multiply => "MULTIPLY", Self::Screen => "SCREEN", Self::Replace => "REPLACE", + Self::Opaque => "OPAQUE", + Self::Premultiplied => "PREMULTIPLIED", } } @@ -461,11 +475,27 @@ impl BlendMode { "MULTIPLY" => Some(Self::Multiply), "SCREEN" => Some(Self::Screen), "REPLACE" => Some(Self::Replace), + "OPAQUE" => Some(Self::Opaque), + "PREMULTIPLIED" => Some(Self::Premultiplied), _ => None, } } - pub fn to_blend_state(self) -> Option { + /// `None` is the default: alpha blending where a color is translucent. + pub fn to_blend(self) -> Option { + match self { + Self::Opaque => Some(Blend::Opaque), + mode => mode.equation().map(Blend::Equation), + } + } + + /// What a material set to this mode does; `Blend` always alpha blends there. + pub fn to_material_blend(self) -> Blend { + self.to_blend() + .unwrap_or(Blend::Equation(BlendState::ALPHA_BLENDING)) + } + + fn equation(self) -> Option { use BlendFactor::*; use BlendOperation::*; @@ -476,7 +506,8 @@ impl BlendMode { }; match self { - Self::Blend => None, + Self::Blend | Self::Opaque => None, + Self::Premultiplied => Some(BlendState::PREMULTIPLIED_ALPHA_BLENDING), Self::Add => Some(BlendState { color: color(SrcAlpha, One, Add), alpha: ALPHA_ADDITIVE, @@ -710,7 +741,7 @@ pub enum DrawCommand { geometry: Option, topology: crate::geometry::Topology, }, - BlendMode(Option), + BlendMode(Option), Material(Entity), Box { width: f32, diff --git a/crates/processing_render/src/render/line.rs b/crates/processing_render/src/render/line.rs index c1612c36..8e2779d4 100644 --- a/crates/processing_render/src/render/line.rs +++ b/crates/processing_render/src/render/line.rs @@ -239,6 +239,8 @@ impl Segments { pub struct LineMesh { opaque: Segments, blended: Segments, + /// nothing goes in the blended mesh + solid: bool, /// physical pixels per logical pixel of the graphics pixel_density: f32, /// weights are in world units instead of pixels @@ -252,11 +254,12 @@ pub struct LineMesh { } impl LineMesh { - /// Strokes for a graphics of `pixel_density`. - pub fn new(pixel_density: f32, perspective: bool) -> Self { + /// Strokes for a graphics of `pixel_density`; `solid` draws translucent ones solid too. + pub fn new(pixel_density: f32, perspective: bool, solid: bool) -> Self { let mut mesh = Self { opaque: Segments::default(), blended: Segments::default(), + solid, pixel_density, perspective, transform: Affine3A::IDENTITY, @@ -300,7 +303,7 @@ impl LineMesh { { return; } - let translucent = ends.iter().any(|end| end.color.alpha() < 1.0); + let translucent = !self.solid && ends.iter().any(|end| end.color.alpha() < 1.0); let segments = if translucent { &mut self.blended } else { diff --git a/crates/processing_render/src/render/material.rs b/crates/processing_render/src/render/material.rs index bf4d615c..4bbfcfd7 100644 --- a/crates/processing_render/src/render/material.rs +++ b/crates/processing_render/src/render/material.rs @@ -40,6 +40,17 @@ pub enum MaterialKey { }, } +/// The alpha mode for a blend equation, or for a translucent color without one. +pub(crate) fn blended_alpha_mode(blend_state: Option, translucent: bool) -> AlphaMode { + match blend_state { + // bevy's own alpha mode for this equation + Some(BlendState::PREMULTIPLIED_ALPHA_BLENDING) => AlphaMode::Premultiplied, + Some(_) => AlphaMode::Blend, + None if translucent => AlphaMode::Blend, + None => AlphaMode::Opaque, + } +} + // float fields: a NaN or -0.0 key only misses the cache impl Eq for MaterialKey {} @@ -199,8 +210,7 @@ impl MaterialKey { } } - /// The same key, but rendered in the blended phase (translucent vertex colors). Custom - /// materials own their blend state and are returned unchanged. + /// The same key, but rendered in the blended phase (translucent vertex colors). pub fn transparent(self) -> MaterialKey { match self { MaterialKey::Color { @@ -219,6 +229,7 @@ impl MaterialKey { pbr.transparent = true; pbr.into() } + // a custom material's own alpha mode decides how it blends custom => custom, } } @@ -236,6 +247,33 @@ impl MaterialKey { } } + /// The same key drawn solid, whatever alpha its colors have. + pub fn opaque(self) -> MaterialKey { + match self { + MaterialKey::Color { + background_image, + uv_transform, + .. + } => MaterialKey::Color { + transparent: false, + background_image, + uv_transform, + blend_state: None, + }, + MaterialKey::Pbr { .. } => { + let mut pbr = self.as_pbr(); + pbr.transparent = false; + pbr.albedo[3] = 255; + pbr.blend_state = None; + pbr.into() + } + MaterialKey::Custom { entity, .. } => MaterialKey::Custom { + entity, + blend_state: None, + }, + } + } + /// The key with both faces lit; unlit keys are unchanged. pub fn two_sided(self) -> MaterialKey { match self { @@ -287,11 +325,7 @@ impl MaterialKey { cull_mode: None, base_color_texture: background_image.clone(), uv_transform: *uv_transform, - alpha_mode: if blend_state.is_some() || *transparent { - AlphaMode::Blend - } else { - AlphaMode::Opaque - }, + alpha_mode: blended_alpha_mode(*blend_state, *transparent), ..default() }, MaterialKey::Pbr { @@ -316,11 +350,7 @@ impl MaterialKey { unlit: false, cull_mode: None, double_sided: *two_sided, - alpha_mode: if blend_state.is_some() || albedo[3] < 255 || *transparent { - AlphaMode::Blend - } else { - AlphaMode::Opaque - }, + alpha_mode: blended_alpha_mode(*blend_state, albedo[3] < 255 || *transparent), perceptual_roughness: *roughness as f32 / 255.0, metallic: *metallic as f32 / 255.0, emissive: LinearRgba::new( @@ -350,8 +380,7 @@ impl MaterialKey { base, extension: ProcessingMaterial { blend_state, - depth_write: None, - instance_fill: false, + ..default() }, }; materials.add(extended).untyped() diff --git a/crates/processing_render/src/render/mod.rs b/crates/processing_render/src/render/mod.rs index 0d251bef..e436bbf2 100644 --- a/crates/processing_render/src/render/mod.rs +++ b/crates/processing_render/src/render/mod.rs @@ -24,7 +24,7 @@ use bevy::{ render::render_resource::BlendState, window::WindowRef, }; -use command::{CommandBuffer, DrawCommand, ShapeMode, TextureMode}; +use command::{Blend, CommandBuffer, DrawCommand, ShapeMode, TextureMode}; use line::{LineEnd, LineMaterial, LineMaterials, LineMesh}; use material::{MaterialKey, ProcessingExtendedMaterial}; use pool::{DrawCaches, DrawPool, MaterialDesc, PooledDraw, ShapeKey, WireframeKey}; @@ -44,7 +44,7 @@ use crate::{ image::Image, light::ProcessingLight, material::ProcessingMaterial, - material::custom::{CustomMaterial, CustomVariants, VariantKey}, + material::custom::{CustomMaterial, CustomVariants, VariantKey, Variants}, particles::{Particles, ParticlesDraw}, render::{material::UntypedMaterial, primitive::rect}, text::font::TextContext, @@ -77,6 +77,7 @@ pub struct RenderResources<'w, 's> { materials: ResMut<'w, Assets>, custom_materials: ResMut<'w, Assets>, custom_variants: ResMut<'w, CustomVariants>, + pbr_variants: ResMut<'w, Variants>, line_materials: Res<'w, LineMaterials>, line_material_assets: ResMut<'w, Assets>, wireframe_materials: ResMut<'w, Assets>, @@ -105,6 +106,7 @@ struct BatchState { struct LineBatch { mesh: LineMesh, blend_state: Option, + opaque: bool, perspective: bool, } @@ -281,6 +283,8 @@ pub fn flush_draw_commands( let materials_changed = res.custom_materials.is_changed(); res.custom_variants .begin(materials_changed, &res.custom_materials); + let materials_changed = res.materials.is_changed(); + res.pbr_variants.begin(materials_changed, &res.materials); for ( graphics_entity, @@ -966,12 +970,15 @@ pub fn flush_draw_commands( }; let tint = state.style.tint_color.unwrap_or(Color::WHITE); - let material_key = MaterialKey::Color { - transparent: tint.alpha() < 1.0 || p_image.translucent, - background_image: Some(p_image.handle.clone()), - uv_transform: uv_xform, - blend_state: state.style.blend_state, - }; + let material_key = styled( + &state, + MaterialKey::Color { + transparent: tint.alpha() < 1.0 || p_image.translucent, + background_image: Some(p_image.handle.clone()), + uv_transform: uv_xform, + blend_state: state.style.blend_state, + }, + ); let stroke_config = state.style.stroke_config; flush_batch(&mut res, &mut batch, &p_material_handles); @@ -1257,8 +1264,12 @@ pub fn flush_draw_commands( batch.draw_index += 1; } - DrawCommand::BlendMode(blend_state) => { - state.style.blend_state = blend_state; + DrawCommand::BlendMode(blend) => { + state.style.opaque = blend == Some(Blend::Opaque); + state.style.blend_state = match blend { + Some(Blend::Equation(blend_state)) => Some(blend_state), + Some(Blend::Opaque) | None => None, + }; } DrawCommand::Material(entity) => { state.style.material_key = MaterialKey::Custom { @@ -1703,33 +1714,64 @@ fn is_custom_shader(material: &UntypedHandle) -> bool { } /// 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. +/// `key` under the current blend mode's override, if it has one. +fn styled(state: &RenderState, key: MaterialKey) -> MaterialKey { + if state.style.opaque { + key.opaque() + } else { + key + } +} + +/// A sketch's 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 { - 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(); + if let Ok(handle) = original.clone().try_typed::() { + let Some(material) = res.custom_materials.get(&handle) else { + return original.clone(); + }; + // a material with a blend mode of its own keeps it + let blend_state = blend_state.filter(|_| material.inherit_blend); + 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, + ); + return variant.map_or_else(|| original.clone(), Handle::untyped); } - 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) + if let Ok(handle) = original.clone().try_typed::() { + let Some(material) = res.materials.get(&handle) else { + return original.clone(); + }; + let blend_state = blend_state.filter(|_| material.extension.inherit_blend); + if blend_state.is_none() { + return original.clone(); + } + let key = VariantKey { + blend_state, + instance_fill: material.extension.instance_fill, + }; + let variant = res + .pbr_variants + .get(&mut res.materials, &handle, key, |material, key| { + material.extension.blend_state = key.blend_state; + material.base.alpha_mode = material::blended_alpha_mode(key.blend_state, false); + }); + return variant.map_or_else(|| original.clone(), Handle::untyped); + } + original.clone() } fn material_key_with_color( @@ -1831,16 +1873,18 @@ fn material_key_with_colors(state: &RenderState, colors: &[Color]) -> Option MaterialKey { let color = state.style.fill.color().unwrap_or(Color::WHITE); - material_key_with_color(&state.style.material_key, color, state.style.blend_state) + let key = material_key_with_color(&state.style.material_key, color, state.style.blend_state); + styled(state, key) } fn add_fill( @@ -1925,12 +1969,13 @@ fn line_batch<'a>( ) -> &'a mut LineMesh { let transform = state.transform.current(); let blend_state = state.style.blend_state; + let opaque = state.style.opaque; let perspective = state.stroke_perspective; - if batch - .lines - .as_ref() - .is_some_and(|lines| lines.blend_state != blend_state || lines.perspective != perspective) - { + if batch.lines.as_ref().is_some_and(|lines| { + lines.blend_state != blend_state + || lines.opaque != opaque + || lines.perspective != perspective + }) { flush_lines(res, batch); } let pixel_density = res @@ -1942,8 +1987,9 @@ fn line_batch<'a>( }) .unwrap_or(1.0); let lines = batch.lines.get_or_insert_with(|| LineBatch { - mesh: LineMesh::new(pixel_density, perspective), + mesh: LineMesh::new(pixel_density, perspective, opaque), blend_state, + opaque, perspective, }); lines.mesh.set_transform(transform, matrix_scale(transform)); @@ -2210,6 +2256,7 @@ fn draw_mesh3d( key = key.transparent(); } let (key, tag) = instance_fill(key, color, draws.quantize_fill); + let key = styled(state, key); // an unlit fill the tag cannot carry goes in the material let base_color = match (&key, tag) { (MaterialKey::Color { .. }, None) => Some(color), @@ -2239,8 +2286,8 @@ fn draw_mesh3d( base, extension: ProcessingMaterial { blend_state: key.blend_state(), - depth_write: None, instance_fill: tag.is_some(), + ..default() }, }) .untyped() diff --git a/crates/processing_render/src/render/style.rs b/crates/processing_render/src/render/style.rs index 15793ad3..f470f954 100644 --- a/crates/processing_render/src/render/style.rs +++ b/crates/processing_render/src/render/style.rs @@ -31,6 +31,8 @@ pub struct Style { pub stroke_config: StrokeConfig, pub material_key: MaterialKey, pub blend_state: Option, + /// `blend_mode(OPAQUE)`: nothing blends, whatever its alpha + pub opaque: bool, pub tint_color: Option, pub image_mode: ShapeMode, /// the size of the current texture, which `TextureMode::Image` coordinates are in @@ -72,6 +74,7 @@ impl Default for Style { blend_state: None, }, blend_state: None, + opaque: false, tint_color: None, image_mode: ShapeMode::Corner, texture_size: None, diff --git a/crates/processing_wasm/src/lib.rs b/crates/processing_wasm/src/lib.rs index f929fb9e..672e3aed 100644 --- a/crates/processing_wasm/src/lib.rs +++ b/crates/processing_wasm/src/lib.rs @@ -361,8 +361,8 @@ pub fn js_shear_y(graphics_id: u64, angle: f32) -> Result<(), JsValue> { pub fn js_set_blend_mode(graphics_id: u64, mode: u8) -> Result<(), JsValue> { let graphics_entity = Entity::from_bits(graphics_id); check((|| { - let blend_state = processing::prelude::BlendMode::try_from(mode)?.to_blend_state(); - graphics_record_command(graphics_entity, DrawCommand::BlendMode(blend_state)) + let blend = processing::prelude::BlendMode::try_from(mode)?.to_blend(); + graphics_record_command(graphics_entity, DrawCommand::BlendMode(blend)) })()) } @@ -381,7 +381,10 @@ pub fn js_set_custom_blend_mode( let blend_state = custom_blend_state( color_src, color_dst, color_op, alpha_src, alpha_dst, alpha_op, )?; - graphics_record_command(graphics_entity, DrawCommand::BlendMode(Some(blend_state))) + graphics_record_command( + graphics_entity, + DrawCommand::BlendMode(Some(Blend::Equation(blend_state))), + ) })()) } diff --git a/examples/blend_modes.rs b/examples/blend_modes.rs index e23cb810..634f4938 100644 --- a/examples/blend_modes.rs +++ b/examples/blend_modes.rs @@ -52,10 +52,7 @@ fn sketch() -> error::Result<()> { DrawCommand::BackgroundColor(bevy::color::Color::srgba(0.15, 0.15, 0.15, 1.0)), )?; graphics_record_command(graphics, DrawCommand::NoStroke)?; - graphics_record_command( - graphics, - DrawCommand::BlendMode(MODES[index].to_blend_state()), - )?; + graphics_record_command(graphics, DrawCommand::BlendMode(MODES[index].to_blend()))?; graphics_record_command( graphics, diff --git a/src/prelude.rs b/src/prelude.rs index 22b4b160..cb13329b 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -12,7 +12,7 @@ pub use processing_midi::{ }; pub use processing_render::{ render::command::{ - ArcMode, BlendMode, DrawCommand, LightKind, ShapeKind, ShapeMode, StrokeCapMode, + ArcMode, Blend, BlendMode, DrawCommand, LightKind, ShapeKind, ShapeMode, StrokeCapMode, StrokeJoinMode, TextAlignH, TextAlignV, TextStyle, TextWrapMode, TextureMode, custom_blend_state, },