Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 72 additions & 72 deletions Cargo.lock

Large diffs are not rendered by default.

15 changes: 15 additions & 0 deletions assets/shaders/mask.wesl
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { lygia::generative::snoise::snoise3 };
import { processing::{globals, VertexOutput} };
import { processing::material::mask };

@group(3) @binding(0) var<uniform> color: vec4<f32>;

@fragment
fn fragment(mesh: VertexOutput) -> @location(0) vec4<f32> {
let p = mesh.world_position.xyz * 0.03 + globals.time * 0.1;
let alpha = snoise3(p) * 0.5 + 0.5;

// discards this fragment when alpha is below the material's mask cutoff
mask(alpha);
return vec4(color.rgb, 1.0);
}
40 changes: 34 additions & 6 deletions crates/processing_ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
});
}

Expand All @@ -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))),
)
});
}

Expand Down Expand Up @@ -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)]
Expand Down Expand Up @@ -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)),
)
});
}

Expand Down
37 changes: 30 additions & 7 deletions crates/processing_node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
})())
}

Expand All @@ -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))),
)
})())
}

Expand Down Expand Up @@ -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")]
Expand Down Expand Up @@ -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)))
})())
}

Expand Down
73 changes: 73 additions & 0 deletions crates/processing_pyo3/examples/mask.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Mask.
#
# A material's mask discards every fragment whose alpha is below a cutoff.
# Left: a mask alone cuts a hard edge. Middle: a mask with blending cuts the
# faint part away and blends the rest. Right: a custom shader calls mask().
from processing_py import *

img = None
cutout = None
blended = None
noisy = None


def setup():
global img, cutout, blended, noisy
size(800, 600)
mode_3d()

# an image that fades from opaque at its center to transparent at its corners
img = create_image(128, 128)
px = []
for y in range(128):
for x in range(128):
d = dist(x, y, 64, 64) / 64
a = constrain(1.0 - d, 0.0, 1.0)
px.append(color(1.0, 0.6, 0.1, a))
img.update_pixels(px)

cutout = create_material(texture=img, unlit=True)
cutout.mask(0.5)

blended = create_material(texture=img, unlit=True)
blended.blend_mode(BLEND)
blended.mask(0.5)

shader = load_shader("shaders/mask.wesl")
noisy = create_material(shader, color=[0.2, 0.8, 1.0, 1.0])
noisy.mask(0.5)


def draw():
camera_position(0.0, 0.0, 500.0)
camera_look_at(0.0, 0.0, 0.0)
background(20, 30, 60)
no_stroke()

# a white bar behind the panels shows what each one lets through
fill(255)
push()
translate(0.0, 0.0, -60.0)
box(700.0, 40.0, 10.0)
pop()

# push() and pop() keep each material to its own panel
push()
translate(-230.0, 0.0, 0.0)
material(cutout)
box(180.0, 180.0, 1.0)
pop()

push()
material(blended)
box(180.0, 180.0, 1.0)
pop()

push()
translate(230.0, 0.0, 0.0)
material(noisy)
box(180.0, 180.0, 1.0)
pop()


run()
7 changes: 6 additions & 1 deletion crates/processing_pyo3/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)?;

Expand Down Expand Up @@ -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(())
}
11 changes: 10 additions & 1 deletion crates/processing_pyo3/src/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,16 @@ pub fn resolve_filter(
return resolve_user_filter(shader.entity, args, kwargs);
}

let Ok(kind_u8) = kind.extract::<u8>() else {
// `OPAQUE` is one constant, shared with `blend_mode()`
let opaque = kind
.extract::<PyRef<crate::graphics::PyBlendMode>>()
.is_ok_and(|mode| mode.is_opaque());
let kind_u8 = if opaque {
Ok(OPAQUE_U8)
} else {
kind.extract::<u8>()
};
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",
));
Expand Down
26 changes: 21 additions & 5 deletions crates/processing_pyo3/src/graphics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,22 +232,38 @@ fn cuda_import_from_interface(
#[pyclass(name = "BlendMode", from_py_object)]
#[derive(Clone)]
pub struct PyBlendMode {
pub(crate) blend_state: Option<bevy::render::render_resource::BlendState>,
/// `None` is `BLEND`, the default
pub(crate) blend: Option<Blend>,
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()),
}
}

/// 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<u32> {
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)
}
}

Expand All @@ -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,
})
}
Expand Down Expand Up @@ -2670,7 +2686,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}")))
}

Expand Down
25 changes: 9 additions & 16 deletions crates/processing_pyo3/src/material.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<u8>()?, 0.5).map_err(rt)?
}
_ => {
let v = py_to_shader_value(&value)?;
material_set(entity, &name, v).map_err(rt)?;
Expand Down Expand Up @@ -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.
Expand All @@ -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<PyRef<crate::graphics::PyBlendMode>>) -> PyResult<()> {
let blend = mode.map(|mode| mode.material_blend());
material_set_blend_mode(self.entity, blend).map_err(rt)
}
}

Expand Down
21 changes: 21 additions & 0 deletions crates/processing_render/shaders/processing/material.wesl
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// What a custom fragment stage can ask of its material:
//
// import { processing::material::{mask, mask_cutoff} };
//
// @fragment
// fn fragment(mesh: VertexOutput) -> @location(0) vec4<f32> {
// let color = ...;
// mask(color.a);
// return color;
// }

// the alpha the material's `mask()` cuts below; 0 without a mask
// (material bindings from 100 up are the engine's; a shader's own go below)
@group(constants::MATERIAL_BIND_GROUP) @binding(102) var<uniform> mask_cutoff: f32;

// drops the fragment when the material's mask cuts `alpha` away
fn mask(alpha: f32) {
if alpha < mask_cutoff {
discard;
}
}
Loading
Loading