Skip to content

Commit e29cdfa

Browse files
committed
Material blend modes.
1 parent eafbb2f commit e29cdfa

25 files changed

Lines changed: 742 additions & 244 deletions

File tree

‎Cargo.lock‎

Lines changed: 72 additions & 72 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎assets/shaders/mask.wesl‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { lygia::generative::snoise::snoise3 };
2+
import { processing::{globals, VertexOutput} };
3+
import { processing::material::mask };
4+
5+
@group(3) @binding(0) var<uniform> color: vec4<f32>;
6+
7+
@fragment
8+
fn fragment(mesh: VertexOutput) -> @location(0) vec4<f32> {
9+
let p = mesh.world_position.xyz * 0.03 + globals.time * 0.1;
10+
let alpha = snoise3(p) * 0.5 + 0.5;
11+
12+
// discards this fragment when alpha is below the material's mask cutoff
13+
mask(alpha);
14+
return vec4(color.rgb, 1.0);
15+
}

‎crates/processing_ffi/src/lib.rs‎

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -631,8 +631,8 @@ pub extern "C" fn processing_set_blend_mode(graphics_id: u64, mode: u8) {
631631
error::clear_error();
632632
let graphics_entity = Entity::from_bits(graphics_id);
633633
error::check(|| {
634-
let blend_state = processing::prelude::BlendMode::try_from(mode)?.to_blend_state();
635-
graphics_record_command(graphics_entity, DrawCommand::BlendMode(blend_state))
634+
let blend = processing::prelude::BlendMode::try_from(mode)?.to_blend();
635+
graphics_record_command(graphics_entity, DrawCommand::BlendMode(blend))
636636
});
637637
}
638638

@@ -652,7 +652,10 @@ pub extern "C" fn processing_set_custom_blend_mode(
652652
let blend_state = custom_blend_state(
653653
color_src, color_dst, color_op, alpha_src, alpha_dst, alpha_op,
654654
)?;
655-
graphics_record_command(graphics_entity, DrawCommand::BlendMode(Some(blend_state)))
655+
graphics_record_command(
656+
graphics_entity,
657+
DrawCommand::BlendMode(Some(Blend::Equation(blend_state))),
658+
)
656659
});
657660
}
658661

@@ -2986,9 +2989,31 @@ pub extern "C" fn processing_material(window_id: u64, mat_id: u64) {
29862989
}
29872990

29882991
#[unsafe(no_mangle)]
2989-
pub extern "C" fn processing_material_set_alpha_mode(mat_id: u64, mode: u8, cutoff: f32) {
2992+
pub extern "C" fn processing_material_set_mask(mat_id: u64, cutoff: f32) {
2993+
error::clear_error();
2994+
error::check(|| material_set_mask(Entity::from_bits(mat_id), Some(cutoff)));
2995+
}
2996+
2997+
#[unsafe(no_mangle)]
2998+
pub extern "C" fn processing_material_no_mask(mat_id: u64) {
29902999
error::clear_error();
2991-
error::check(|| material_set_alpha_mode(Entity::from_bits(mat_id), mode, cutoff));
3000+
error::check(|| material_set_mask(Entity::from_bits(mat_id), None));
3001+
}
3002+
3003+
#[unsafe(no_mangle)]
3004+
pub extern "C" fn processing_material_set_blend_mode(mat_id: u64, mode: u8) {
3005+
error::clear_error();
3006+
error::check(|| {
3007+
let blend = processing::prelude::BlendMode::try_from(mode)?.to_material_blend();
3008+
material_set_blend_mode(Entity::from_bits(mat_id), Some(blend))
3009+
});
3010+
}
3011+
3012+
/// The material follows the current blend mode again.
3013+
#[unsafe(no_mangle)]
3014+
pub extern "C" fn processing_material_no_blend_mode(mat_id: u64) {
3015+
error::clear_error();
3016+
error::check(|| material_set_blend_mode(Entity::from_bits(mat_id), None));
29923017
}
29933018

29943019
#[unsafe(no_mangle)]
@@ -3024,7 +3049,10 @@ pub extern "C" fn processing_material_set_custom_blend_mode(
30243049
let blend_state = custom_blend_state(
30253050
color_src, color_dst, color_op, alpha_src, alpha_dst, alpha_op,
30263051
)?;
3027-
material_set_custom_blend(Entity::from_bits(mat_id), blend_state)
3052+
material_set_blend_mode(
3053+
Entity::from_bits(mat_id),
3054+
Some(Blend::Equation(blend_state)),
3055+
)
30283056
});
30293057
}
30303058

‎crates/processing_node/src/lib.rs‎

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -485,8 +485,8 @@ pub fn js_shear_y(graphics_id: BigInt, angle: f64) -> Result<()> {
485485
pub fn js_set_blend_mode(graphics_id: BigInt, mode: u8) -> Result<()> {
486486
let graphics = ent(graphics_id);
487487
check((|| {
488-
let blend_state = BlendMode::try_from(mode)?.to_blend_state();
489-
graphics_record_command(graphics, DrawCommand::BlendMode(blend_state))
488+
let blend = BlendMode::try_from(mode)?.to_blend();
489+
graphics_record_command(graphics, DrawCommand::BlendMode(blend))
490490
})())
491491
}
492492

@@ -505,7 +505,10 @@ pub fn js_set_custom_blend_mode(
505505
let blend_state = custom_blend_state(
506506
color_src, color_dst, color_op, alpha_src, alpha_dst, alpha_op,
507507
)?;
508-
graphics_record_command(graphics, DrawCommand::BlendMode(Some(blend_state)))
508+
graphics_record_command(
509+
graphics,
510+
DrawCommand::BlendMode(Some(Blend::Equation(blend_state))),
511+
)
509512
})())
510513
}
511514

@@ -2088,9 +2091,29 @@ pub fn js_material(graphics_id: BigInt, mat_id: BigInt) -> Result<()> {
20882091
record(graphics_id, DrawCommand::Material(ent(mat_id)))
20892092
}
20902093

2091-
#[napi(js_name = "materialSetAlphaMode")]
2092-
pub fn js_material_set_alpha_mode(mat_id: BigInt, mode: u8, cutoff: f64) -> Result<()> {
2093-
check(material_set_alpha_mode(ent(mat_id), mode, cutoff as f32))
2094+
#[napi(js_name = "materialSetMask")]
2095+
pub fn js_material_set_mask(mat_id: BigInt, cutoff: f64) -> Result<()> {
2096+
check(material_set_mask(ent(mat_id), Some(cutoff as f32)))
2097+
}
2098+
2099+
#[napi(js_name = "materialNoMask")]
2100+
pub fn js_material_no_mask(mat_id: BigInt) -> Result<()> {
2101+
check(material_set_mask(ent(mat_id), None))
2102+
}
2103+
2104+
#[napi(js_name = "materialSetBlendMode")]
2105+
pub fn js_material_set_blend_mode(mat_id: BigInt, mode: u8) -> Result<()> {
2106+
let mat = ent(mat_id);
2107+
check((|| {
2108+
let blend = BlendMode::try_from(mode)?.to_material_blend();
2109+
material_set_blend_mode(mat, Some(blend))
2110+
})())
2111+
}
2112+
2113+
/// The material follows the current blend mode again.
2114+
#[napi(js_name = "materialNoBlendMode")]
2115+
pub fn js_material_no_blend_mode(mat_id: BigInt) -> Result<()> {
2116+
check(material_set_blend_mode(ent(mat_id), None))
20942117
}
20952118

20962119
#[napi(js_name = "materialSetDoubleSided")]
@@ -2123,7 +2146,7 @@ pub fn js_material_set_custom_blend_mode(
21232146
let blend_state = custom_blend_state(
21242147
color_src, color_dst, color_op, alpha_src, alpha_dst, alpha_op,
21252148
)?;
2126-
material_set_custom_blend(mat, blend_state)
2149+
material_set_blend_mode(mat, Some(Blend::Equation(blend_state)))
21272150
})())
21282151
}
21292152

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# Mask.
2+
#
3+
# A material's mask discards every fragment whose alpha is below a cutoff.
4+
# Left: a mask alone cuts a hard edge. Middle: a mask with blending cuts the
5+
# faint part away and blends the rest. Right: a custom shader calls mask().
6+
from processing_py import *
7+
8+
img = None
9+
cutout = None
10+
blended = None
11+
noisy = None
12+
13+
14+
def setup():
15+
global img, cutout, blended, noisy
16+
size(800, 600)
17+
mode_3d()
18+
19+
# an image that fades from opaque at its center to transparent at its corners
20+
img = create_image(128, 128)
21+
px = []
22+
for y in range(128):
23+
for x in range(128):
24+
d = dist(x, y, 64, 64) / 64
25+
a = constrain(1.0 - d, 0.0, 1.0)
26+
px.append(color(1.0, 0.6, 0.1, a))
27+
img.update_pixels(px)
28+
29+
cutout = create_material(texture=img, unlit=True)
30+
cutout.mask(0.5)
31+
32+
blended = create_material(texture=img, unlit=True)
33+
blended.blend_mode(BLEND)
34+
blended.mask(0.5)
35+
36+
shader = load_shader("shaders/mask.wesl")
37+
noisy = create_material(shader, color=[0.2, 0.8, 1.0, 1.0])
38+
noisy.mask(0.5)
39+
40+
41+
def draw():
42+
camera_position(0.0, 0.0, 500.0)
43+
camera_look_at(0.0, 0.0, 0.0)
44+
background(20, 30, 60)
45+
no_stroke()
46+
47+
# a white bar behind the panels shows what each one lets through
48+
fill(255)
49+
push()
50+
translate(0.0, 0.0, -60.0)
51+
box(700.0, 40.0, 10.0)
52+
pop()
53+
54+
# push() and pop() keep each material to its own panel
55+
push()
56+
translate(-230.0, 0.0, 0.0)
57+
material(cutout)
58+
box(180.0, 180.0, 1.0)
59+
pop()
60+
61+
push()
62+
material(blended)
63+
box(180.0, 180.0, 1.0)
64+
pop()
65+
66+
push()
67+
translate(230.0, 0.0, 0.0)
68+
material(noisy)
69+
box(180.0, 180.0, 1.0)
70+
pop()
71+
72+
73+
run()

‎crates/processing_pyo3/src/constants.rs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
3333
m.add("THRESHOLD", crate::filter::THRESHOLD_U8)?;
3434
m.add("POSTERIZE", crate::filter::POSTERIZE_U8)?;
3535
m.add("BLUR", crate::filter::BLUR_U8)?;
36-
m.add("OPAQUE", crate::filter::OPAQUE_U8)?;
3736
m.add("ERODE", crate::filter::ERODE_U8)?;
3837
m.add("DILATE", crate::filter::DILATE_U8)?;
3938

@@ -192,6 +191,12 @@ pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
192191
m.add("MULTIPLY", PyBlendMode::from_preset(BlendMode::Multiply))?;
193192
m.add("SCREEN", PyBlendMode::from_preset(BlendMode::Screen))?;
194193
m.add("REPLACE", PyBlendMode::from_preset(BlendMode::Replace))?;
194+
// also the `filter(OPAQUE)` constant
195+
m.add("OPAQUE", PyBlendMode::from_preset(BlendMode::Opaque))?;
196+
m.add(
197+
"PREMULTIPLIED",
198+
PyBlendMode::from_preset(BlendMode::Premultiplied),
199+
)?;
195200

196201
Ok(())
197202
}

‎crates/processing_pyo3/src/filter.rs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,16 @@ pub fn resolve_filter(
7575
return resolve_user_filter(shader.entity, args, kwargs);
7676
}
7777

78-
let Ok(kind_u8) = kind.extract::<u8>() else {
78+
// `OPAQUE` is one constant, shared with `blend_mode()`
79+
let opaque = kind
80+
.extract::<PyRef<crate::graphics::PyBlendMode>>()
81+
.is_ok_and(|mode| mode.is_opaque());
82+
let kind_u8 = if opaque {
83+
Ok(OPAQUE_U8)
84+
} else {
85+
kind.extract::<u8>()
86+
};
87+
let Ok(kind_u8) = kind_u8 else {
7988
return Err(PyTypeError::new_err(
8089
"filter(): first argument must be a filter constant (INVERT, GRAY, ...) or a Shader",
8190
));

‎crates/processing_pyo3/src/graphics.rs‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -232,22 +232,38 @@ fn cuda_import_from_interface(
232232
#[pyclass(name = "BlendMode", from_py_object)]
233233
#[derive(Clone)]
234234
pub struct PyBlendMode {
235-
pub(crate) blend_state: Option<bevy::render::render_resource::BlendState>,
235+
/// `None` is `BLEND`, the default
236+
pub(crate) blend: Option<Blend>,
236237
name: Option<&'static str>,
237238
}
238239

239240
impl PyBlendMode {
240241
pub(crate) fn from_preset(mode: BlendMode) -> Self {
241242
Self {
242-
blend_state: mode.to_blend_state(),
243+
blend: mode.to_blend(),
243244
name: Some(mode.name()),
244245
}
245246
}
246247

247248
/// The composite-shader mode code (the `BlendMode` discriminant) for this
248249
/// blend mode, or `None` for custom modes with no named preset.
249250
pub(crate) fn composite_mode(&self) -> Option<u32> {
250-
self.name.and_then(BlendMode::from_name).map(|m| m as u32)
251+
self.name
252+
.and_then(BlendMode::from_name)
253+
// the compositor has no code past `REPLACE`
254+
.filter(|m| *m as u32 <= BlendMode::Replace as u32)
255+
.map(|m| m as u32)
256+
}
257+
258+
/// What a material set to this mode does; `BLEND` always alpha blends there.
259+
pub(crate) fn material_blend(&self) -> Blend {
260+
self.blend.unwrap_or(Blend::Equation(
261+
bevy::render::render_resource::BlendState::ALPHA_BLENDING,
262+
))
263+
}
264+
265+
pub(crate) fn is_opaque(&self) -> bool {
266+
self.blend == Some(Blend::Opaque)
251267
}
252268
}
253269

@@ -268,7 +284,7 @@ impl PyBlendMode {
268284
)
269285
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
270286
Ok(Self {
271-
blend_state: Some(blend_state),
287+
blend: Some(Blend::Equation(blend_state)),
272288
name: None,
273289
})
274290
}
@@ -2670,7 +2686,7 @@ impl Graphics {
26702686
}
26712687

26722688
pub fn blend_mode(&self, mode: &PyBlendMode) -> PyResult<()> {
2673-
graphics_record_command(self.entity, DrawCommand::BlendMode(mode.blend_state))
2689+
graphics_record_command(self.entity, DrawCommand::BlendMode(mode.blend))
26742690
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))
26752691
}
26762692

‎crates/processing_pyo3/src/material.rs‎

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -144,9 +144,6 @@ fn apply_kwargs(entity: Entity, kwargs: &Bound<'_, PyDict>) -> PyResult<()> {
144144
"unlit" => material_set_unlit(entity, py_truthy(&value)?).map_err(rt)?,
145145
"double_sided" => material_set_double_sided(entity, py_truthy(&value)?).map_err(rt)?,
146146
"depth_write" => material_set_depth_write(entity, py_truthy(&value)?).map_err(rt)?,
147-
"alpha_mode" => {
148-
material_set_alpha_mode(entity, value.extract::<u8>()?, 0.5).map_err(rt)?
149-
}
150147
_ => {
151148
let v = py_to_shader_value(&value)?;
152149
material_set(entity, &name, v).map_err(rt)?;
@@ -197,18 +194,14 @@ impl Material {
197194
apply_kwargs(self.entity, kwargs)
198195
}
199196

200-
pub fn opaque(&self) -> PyResult<()> {
201-
material_set_alpha_mode(self.entity, 0, 0.0).map_err(rt)
202-
}
203-
204197
/// Discards fragments with alpha below `cutoff`.
205198
#[pyo3(signature = (cutoff=0.5))]
206199
pub fn mask(&self, cutoff: f32) -> PyResult<()> {
207-
material_set_alpha_mode(self.entity, 1, cutoff).map_err(rt)
200+
material_set_mask(self.entity, Some(cutoff)).map_err(rt)
208201
}
209202

210-
pub fn transparent(&self) -> PyResult<()> {
211-
material_set_alpha_mode(self.entity, 2, 0.0).map_err(rt)
203+
pub fn no_mask(&self) -> PyResult<()> {
204+
material_set_mask(self.entity, None).map_err(rt)
212205
}
213206

214207
/// Skips lighting; errors on a custom shader, which does its own.
@@ -227,12 +220,12 @@ impl Material {
227220
material_set_depth_write(self.entity, value).map_err(rt)
228221
}
229222

230-
/// Blends with what's behind it using a `BlendMode` (`ADD`, `MULTIPLY`, a custom one, ...).
231-
pub fn blend_mode(&self, mode: &crate::graphics::PyBlendMode) -> PyResult<()> {
232-
let state = mode
233-
.blend_state
234-
.unwrap_or(bevy::render::render_resource::BlendState::ALPHA_BLENDING);
235-
material_set_custom_blend(self.entity, state).map_err(rt)
223+
/// How it combines with what's behind it (`OPAQUE`, `BLEND`, `ADD`, a custom `BlendMode`,
224+
/// ...); `None` follows the current `blend_mode()`.
225+
#[pyo3(signature = (mode, /))]
226+
pub fn blend_mode(&self, mode: Option<PyRef<crate::graphics::PyBlendMode>>) -> PyResult<()> {
227+
let blend = mode.map(|mode| mode.material_blend());
228+
material_set_blend_mode(self.entity, blend).map_err(rt)
236229
}
237230
}
238231

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// What a custom fragment stage can ask of its material:
2+
//
3+
// import { processing::material::{mask, mask_cutoff} };
4+
//
5+
// @fragment
6+
// fn fragment(mesh: VertexOutput) -> @location(0) vec4<f32> {
7+
// let color = ...;
8+
// mask(color.a);
9+
// return color;
10+
// }
11+
12+
// the alpha the material's `mask()` cuts below; 0 without a mask
13+
// (material bindings from 100 up are the engine's; a shader's own go below)
14+
@group(constants::MATERIAL_BIND_GROUP) @binding(102) var<uniform> mask_cutoff: f32;
15+
16+
// drops the fragment when the material's mask cuts `alpha` away
17+
fn mask(alpha: f32) {
18+
if alpha < mask_cutoff {
19+
discard;
20+
}
21+
}

0 commit comments

Comments
 (0)