From e29cdfad397d2e0cb66c17ea9d4345b908abebab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?charlotte=20=F0=9F=8C=B8?= Date: Mon, 30 Nov 2026 14:08:16 -0800 Subject: [PATCH] Material blend modes. --- Cargo.lock | 144 ++++++++-------- assets/shaders/mask.wesl | 15 ++ crates/processing_ffi/src/lib.rs | 40 ++++- crates/processing_node/src/lib.rs | 37 +++- crates/processing_pyo3/examples/mask.py | 73 ++++++++ crates/processing_pyo3/src/constants.rs | 7 +- crates/processing_pyo3/src/filter.rs | 11 +- crates/processing_pyo3/src/graphics.rs | 26 ++- crates/processing_pyo3/src/material.rs | 25 +-- .../shaders/processing/material.wesl | 21 +++ crates/processing_render/src/gltf.rs | 7 +- crates/processing_render/src/lib.rs | 12 +- .../processing_render/src/material/custom.rs | 162 ++++++++++++++++-- crates/processing_render/src/material/mod.rs | 124 +++++++++----- .../src/particles/material.rs | 1 + .../processing_render/src/render/command.rs | 37 +++- crates/processing_render/src/render/line.rs | 9 +- .../processing_render/src/render/material.rs | 57 ++++-- crates/processing_render/src/render/mod.rs | 150 +++++++++++----- crates/processing_render/src/render/style.rs | 3 + crates/processing_wasm/src/lib.rs | 9 +- docs/api.md | 5 + examples/blend_modes.rs | 5 +- src/prelude.rs | 2 +- tests/visual/cases.toml | 4 + 25 files changed, 742 insertions(+), 244 deletions(-) create mode 100644 assets/shaders/mask.wesl create mode 100644 crates/processing_pyo3/examples/mask.py create mode 100644 crates/processing_render/shaders/processing/material.wesl diff --git a/Cargo.lock b/Cargo.lock index 99d71672..85461328 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -539,7 +539,7 @@ checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" [[package]] name = "bevy" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_internal", ] @@ -547,7 +547,7 @@ dependencies = [ [[package]] name = "bevy_a11y" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "accesskit", "bevy_app", @@ -559,7 +559,7 @@ dependencies = [ [[package]] name = "bevy_android" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "android-activity", ] @@ -567,7 +567,7 @@ dependencies = [ [[package]] name = "bevy_animation" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_animation_macros", "bevy_app", @@ -601,7 +601,7 @@ dependencies = [ [[package]] name = "bevy_animation_macros" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_macro_utils", "quote", @@ -611,12 +611,12 @@ dependencies = [ [[package]] name = "bevy_annotations" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" [[package]] name = "bevy_anti_alias" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", @@ -638,7 +638,7 @@ dependencies = [ [[package]] name = "bevy_app" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_derive", "bevy_ecs", @@ -659,7 +659,7 @@ dependencies = [ [[package]] name = "bevy_asset" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "async-broadcast", "async-channel", @@ -702,7 +702,7 @@ dependencies = [ [[package]] name = "bevy_asset_macros" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_macro_utils", "proc-macro2", @@ -713,7 +713,7 @@ dependencies = [ [[package]] name = "bevy_audio" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", @@ -728,7 +728,7 @@ dependencies = [ [[package]] name = "bevy_camera" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", @@ -754,7 +754,7 @@ dependencies = [ [[package]] name = "bevy_camera_controller" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_camera", @@ -777,7 +777,7 @@ dependencies = [ [[package]] name = "bevy_clipboard" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "arboard", "bevy_app", @@ -792,7 +792,7 @@ dependencies = [ [[package]] name = "bevy_color" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_curve", "bevy_math", @@ -808,7 +808,7 @@ dependencies = [ [[package]] name = "bevy_core_pipeline" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", @@ -851,7 +851,7 @@ dependencies = [ [[package]] name = "bevy_curve" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "approx", "bevy_math", @@ -865,7 +865,7 @@ dependencies = [ [[package]] name = "bevy_derive" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_macro_utils", "quote", @@ -875,7 +875,7 @@ dependencies = [ [[package]] name = "bevy_dev_tools" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_animation", "bevy_app", @@ -914,7 +914,7 @@ dependencies = [ [[package]] name = "bevy_diagnostic" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "atomic-waker", "bevy_app", @@ -931,7 +931,7 @@ dependencies = [ [[package]] name = "bevy_ecs" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "arrayvec", "bevy_ecs_macros", @@ -958,7 +958,7 @@ dependencies = [ [[package]] name = "bevy_ecs_macro_logic" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_macro_utils", "proc-macro2", @@ -969,7 +969,7 @@ dependencies = [ [[package]] name = "bevy_ecs_macros" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_ecs_macro_logic", "bevy_macro_utils", @@ -981,7 +981,7 @@ dependencies = [ [[package]] name = "bevy_encase_derive" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_macro_utils", "encase_derive_impl", @@ -990,7 +990,7 @@ dependencies = [ [[package]] name = "bevy_extract" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_camera", @@ -1007,7 +1007,7 @@ dependencies = [ [[package]] name = "bevy_extract_macros" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_macro_utils", "proc-macro2", @@ -1018,7 +1018,7 @@ dependencies = [ [[package]] name = "bevy_feathers" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "accesskit", "bevy_a11y", @@ -1049,12 +1049,12 @@ dependencies = [ [[package]] name = "bevy_fuzzy" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" [[package]] name = "bevy_gilrs" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_ecs", @@ -1069,7 +1069,7 @@ dependencies = [ [[package]] name = "bevy_gizmos" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", @@ -1093,7 +1093,7 @@ dependencies = [ [[package]] name = "bevy_gizmos_macros" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_macro_utils", "quote", @@ -1103,7 +1103,7 @@ dependencies = [ [[package]] name = "bevy_gizmos_render" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", @@ -1133,7 +1133,7 @@ dependencies = [ [[package]] name = "bevy_gltf" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "async-lock", "base64", @@ -1169,7 +1169,7 @@ dependencies = [ [[package]] name = "bevy_image" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", @@ -1197,7 +1197,7 @@ dependencies = [ [[package]] name = "bevy_input" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_ecs", @@ -1213,7 +1213,7 @@ dependencies = [ [[package]] name = "bevy_input_focus" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_camera", @@ -1230,7 +1230,7 @@ dependencies = [ [[package]] name = "bevy_internal" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_a11y", "bevy_android", @@ -1294,7 +1294,7 @@ dependencies = [ [[package]] name = "bevy_light" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", @@ -1321,7 +1321,7 @@ dependencies = [ [[package]] name = "bevy_log" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "android_log-sys", "bevy_app", @@ -1338,7 +1338,7 @@ dependencies = [ [[package]] name = "bevy_macro_utils" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "proc-macro2", "quote", @@ -1349,7 +1349,7 @@ dependencies = [ [[package]] name = "bevy_material" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_asset", "bevy_derive", @@ -1371,7 +1371,7 @@ dependencies = [ [[package]] name = "bevy_material_macros" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_macro_utils", "quote", @@ -1381,7 +1381,7 @@ dependencies = [ [[package]] name = "bevy_math" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "approx", "bevy_reflect", @@ -1397,7 +1397,7 @@ dependencies = [ [[package]] name = "bevy_mesh" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", @@ -1440,7 +1440,7 @@ dependencies = [ [[package]] name = "bevy_pbr" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "arrayvec", "bevy_app", @@ -1484,7 +1484,7 @@ dependencies = [ [[package]] name = "bevy_picking" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", @@ -1508,7 +1508,7 @@ dependencies = [ [[package]] name = "bevy_platform" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bytemuck", "critical-section", @@ -1530,7 +1530,7 @@ dependencies = [ [[package]] name = "bevy_post_process" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", @@ -1556,12 +1556,12 @@ dependencies = [ [[package]] name = "bevy_ptr" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" [[package]] name = "bevy_reflect" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "assert_type_match", "bevy_annotations", @@ -1590,7 +1590,7 @@ dependencies = [ [[package]] name = "bevy_reflect_derive" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_macro_utils", "indexmap", @@ -1603,7 +1603,7 @@ dependencies = [ [[package]] name = "bevy_render" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "async-channel", "bevy_app", @@ -1661,7 +1661,7 @@ dependencies = [ [[package]] name = "bevy_render_macros" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_extract_macros", "bevy_macro_utils", @@ -1673,7 +1673,7 @@ dependencies = [ [[package]] name = "bevy_scene" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", @@ -1692,7 +1692,7 @@ dependencies = [ [[package]] name = "bevy_scene_macros" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_ecs_macro_logic", "bevy_macro_utils", @@ -1704,7 +1704,7 @@ dependencies = [ [[package]] name = "bevy_shader" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_asset", "bevy_platform", @@ -1720,7 +1720,7 @@ dependencies = [ [[package]] name = "bevy_shape" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "arrayvec", "bevy_math", @@ -1735,7 +1735,7 @@ dependencies = [ [[package]] name = "bevy_sprite" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", @@ -1760,7 +1760,7 @@ dependencies = [ [[package]] name = "bevy_sprite_render" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", @@ -1796,7 +1796,7 @@ dependencies = [ [[package]] name = "bevy_state" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_ecs", @@ -1811,7 +1811,7 @@ dependencies = [ [[package]] name = "bevy_state_macros" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_macro_utils", "quote", @@ -1821,7 +1821,7 @@ dependencies = [ [[package]] name = "bevy_tasks" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "async-channel", "async-executor", @@ -1839,7 +1839,7 @@ dependencies = [ [[package]] name = "bevy_text" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", @@ -1866,7 +1866,7 @@ dependencies = [ [[package]] name = "bevy_time" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_ecs", @@ -1880,7 +1880,7 @@ dependencies = [ [[package]] name = "bevy_transform" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_ecs", @@ -1896,7 +1896,7 @@ dependencies = [ [[package]] name = "bevy_ui" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "accesskit", "bevy_a11y", @@ -1933,7 +1933,7 @@ dependencies = [ [[package]] name = "bevy_ui_render" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_a11y", "bevy_app", @@ -1968,7 +1968,7 @@ dependencies = [ [[package]] name = "bevy_ui_widgets" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "accesskit", "bevy_a11y", @@ -1995,7 +1995,7 @@ dependencies = [ [[package]] name = "bevy_utils" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "async-channel", "bevy_platform", @@ -2007,7 +2007,7 @@ dependencies = [ [[package]] name = "bevy_window" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", @@ -2026,7 +2026,7 @@ dependencies = [ [[package]] name = "bevy_winit" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "accesskit", "accesskit_winit", @@ -2058,7 +2058,7 @@ dependencies = [ [[package]] name = "bevy_world_serialization" version = "0.20.0-dev" -source = "git+https://github.com/processing/bevy?branch=main#f65b12082e0322f0a498b2958fb0712ff5c73bd6" +source = "git+https://github.com/processing/bevy?branch=main#7cb6fca4707344806093ef473bbbeb3dc8f52c3b" dependencies = [ "bevy_app", "bevy_asset", diff --git a/assets/shaders/mask.wesl b/assets/shaders/mask.wesl new file mode 100644 index 00000000..a8ce3589 --- /dev/null +++ b/assets/shaders/mask.wesl @@ -0,0 +1,15 @@ +import { lygia::generative::snoise::snoise3 }; +import { processing::{globals, VertexOutput} }; +import { processing::material::mask }; + +@group(3) @binding(0) var color: vec4; + +@fragment +fn fragment(mesh: VertexOutput) -> @location(0) vec4 { + 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); +} 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/examples/mask.py b/crates/processing_pyo3/examples/mask.py new file mode 100644 index 00000000..e9f5f551 --- /dev/null +++ b/crates/processing_pyo3/examples/mask.py @@ -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() 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 1b92398e..104d3356 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, }) } @@ -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}"))) } 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/shaders/processing/material.wesl b/crates/processing_render/shaders/processing/material.wesl new file mode 100644 index 00000000..590638af --- /dev/null +++ b/crates/processing_render/shaders/processing/material.wesl @@ -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 { +// 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 mask_cutoff: f32; + +// drops the fragment when the material's mask cuts `alpha` away +fn mask(alpha: f32) { + if alpha < mask_cutoff { + discard; + } +} diff --git a/crates/processing_render/src/gltf.rs b/crates/processing_render/src/gltf.rs index 3ca6e1c7..a8b6d962 100644 --- a/crates/processing_render/src/gltf.rs +++ b/crates/processing_render/src/gltf.rs @@ -294,6 +294,7 @@ fn gltf_material_to_standard(m: &GltfMaterial) -> StandardMaterial { cull_mode: m.cull_mode, unlit: m.unlit, alpha_mode: m.alpha_mode, + alpha_cutoff: m.alpha_cutoff, uv_transform: m.uv_transform, ..default() } @@ -331,11 +332,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 90bfd729..1cef2997 100644 --- a/crates/processing_render/src/lib.rs +++ b/crates/processing_render/src/lib.rs @@ -2121,10 +2121,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() }) } @@ -2153,13 +2154,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 725ecb01..42bd20d3 100644 --- a/crates/processing_render/src/material/custom.rs +++ b/crates/processing_render/src/material/custom.rs @@ -25,7 +25,7 @@ use bevy::{ lifetimeless::{SRes, SResMut}, }, material::{ - MaterialProperties, RenderPhaseType, + MaterialProperties, descriptor::RenderPipelineDescriptor, key::{ErasedMaterialKey, ErasedMaterialPipelineKey, ErasedMeshPipelineKey}, specialize::SpecializedMeshPipelineError, @@ -141,6 +141,9 @@ pub struct CustomMaterial { /// the vertex input locations the vertex stage cannot do without, 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, @@ -343,6 +346,17 @@ pub struct ShaderPackage { pub files: Vec<(String, Cow<'static, str>)>, } +/// An error's message followed by the messages of what caused it. +fn with_causes(error: &dyn std::error::Error) -> String { + let mut message = error.to_string(); + let mut cause = error.source(); + while let Some(error) = cause { + message += &format!(": {error}"); + cause = error.source(); + } + message +} + /// The package a module belongs to. fn package_of(module: &ShaderModule) -> &'static str { module.path.split("::").next().unwrap() @@ -489,6 +503,7 @@ impl Compiled { let engine = engine_modules(shaders); let (wgsl, module) = compile_shader_with_features(source, features, &engine)?; check_stages(&module)?; + check_bindings(&module)?; // what the vertex stage still reads when `processing::mesh` defaults all it can let vertex_inputs = if has_stage(&module, naga::ShaderStage::Vertex) { let features: Vec<_> = features.iter().copied().chain(MISSING_FEATURES).collect(); @@ -727,6 +742,7 @@ fn reload_shaders( } } material.shader = shader; + apply_mask(&mut material); material.shader_handle = new.material_handle.clone(); material.compiled = compiled; material.has_vertex = has_stage(&module, naga::ShaderStage::Vertex); @@ -745,6 +761,48 @@ pub fn destroy_shader(In(entity): In, mut commands: Commands) -> Result< /// The bind group a material's own parameters live in. const MATERIAL_GROUP: u32 = 3; +/// Material bindings from here up are the engine's; a sketch's shader declares its own below. +pub(crate) const ENGINE_BINDINGS: u32 = 100; + +/// Where `processing::material` declares the mask cutoff; 100 and 101 are the particle buffers. +const MASK_CUTOFF_BINDING: u32 = ENGINE_BINDINGS + 2; + +/// A shader's own material bindings stay below the engine's. +fn check_bindings(module: &naga::Module) -> Result<()> { + for (_, variable) in module.global_variables.iter() { + let Some(binding) = &variable.binding else { + continue; + }; + if binding.group != MATERIAL_GROUP || binding.binding < ENGINE_BINDINGS { + continue; + } + let name = variable.name.as_deref().unwrap_or_default(); + // what a built-in module declares arrives under its package's name + if !name.starts_with("processing_") { + return Err(ProcessingError::ShaderCompilationError(format!( + "`{name}` is at @binding({}); a material's own bindings are below {ENGINE_BINDINGS}", + binding.binding + ))); + } + } + Ok(()) +} + +/// Writes the material's mask where a shader that imports `processing::material` reads it. +pub(crate) fn apply_mask(material: &mut CustomMaterial) { + let name = material + .shader + .reflection() + .parameters() + .find(|p| p.group() == MATERIAL_GROUP && p.binding() == MASK_CUTOFF_BINDING) + .and_then(|p| p.name().map(str::to_string)); + if let Some(name) = name + && let Some(field) = material.shader.field_mut(&name) + { + apply_field_coerced(field, &material.mask.unwrap_or(0.0)); + } +} + /// 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 @@ -772,7 +830,7 @@ pub fn create_custom( let has_fragment = has_stage(&program.module, naga::ShaderStage::Fragment); let mut shader = DynamicShader::new(program.module.clone()) - .map_err(|e| ProcessingError::ShaderCompilationError(e.to_string()))?; + .map_err(|e| ProcessingError::ShaderCompilationError(with_causes(&e)))?; init_material_fields(&mut shader); let material = CustomMaterial { @@ -783,6 +841,8 @@ pub fn create_custom( has_fragment, vertex_inputs: program.vertex_inputs, blend_state: None, + inherit_blend: true, + mask: None, alpha_mode: AlphaMode::Opaque, double_sided: None, depth_write: None, @@ -1197,14 +1257,11 @@ impl ErasedRenderAsset for CustomMaterial { }), user_specialize: Some(specialize), alpha_mode, - render_phase_type: match alpha_mode { - AlphaMode::Blend - | AlphaMode::Premultiplied - | AlphaMode::Add - | AlphaMode::Multiply => RenderPhaseType::Transparent, - AlphaMode::Mask(_) => RenderPhaseType::AlphaMask, - AlphaMode::Opaque | AlphaMode::AlphaToCoverage => RenderPhaseType::Opaque, - }, + alpha_cutoff: source_asset.mask, + render_phase_type: bevy::pbr::alpha_mode_render_phase_type( + alpha_mode, + source_asset.mask, + ), ..Default::default() }; properties.add_draw_function(MainPassOpaqueDrawFunction, opaque_draw); @@ -1336,6 +1393,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, @@ -1356,6 +1415,89 @@ mod tests { .collect() } + #[test] + fn a_shader_that_imports_the_mask_reads_the_materials_cutoff() { + const MASKED: &str = " + import { processing::material::mask }; + @fragment + fn fragment() -> @location(0) vec4 { + mask(0.3); + return vec4(1.0); + } + "; + let (_, module) = compile_shader_with_features(MASKED, &[], &exported_engine()).unwrap(); + let mut masked = material(); + masked.shader = DynamicShader::new(module).unwrap(); + init_material_fields(&mut masked.shader); + let cutoff = |material: &CustomMaterial| { + let name = material + .shader + .reflection() + .parameters() + .find(|p| p.binding() == MASK_CUTOFF_BINDING) + .and_then(|p| p.name().map(str::to_string)) + .expect("the cutoff is one of the shader's parameters"); + material + .shader + .field(&name) + .and_then(|field| field.try_downcast_ref::().copied()) + }; + + masked.mask = Some(0.5); + apply_mask(&mut masked); + assert_eq!(cutoff(&masked), Some(0.5)); + // no mask cuts nothing + masked.mask = None; + apply_mask(&mut masked); + assert_eq!(cutoff(&masked), Some(0.0)); + + // a shader that never asks is left alone + let mut plain = material(); + plain.mask = Some(0.5); + apply_mask(&mut plain); + } + + #[test] + fn a_shaders_own_bindings_stay_below_the_engines() { + let compile = |source: &str| { + let (_, module) = + compile_shader_with_features(source, &[], &exported_engine()).unwrap(); + check_bindings(&module) + }; + assert!(compile(SOURCE).is_ok()); + // the engine's own binding, reached through its module + assert!( + compile( + "import { processing::material::mask_cutoff }; + @fragment + fn fragment() -> @location(0) vec4 { + return vec4(mask_cutoff); + }" + ) + .is_ok() + ); + let error = compile( + "@group(3) @binding(100) var tint: vec4; + @fragment + fn fragment() -> @location(0) vec4 { + return tint; + }", + ) + .unwrap_err(); + assert!(error.to_string().contains("below 100")); + // another group is not the material's + assert!( + compile( + "@group(2) @binding(100) var tint: vec4; + @fragment + fn fragment() -> @location(0) vec4 { + return tint; + }" + ) + .is_ok() + ); + } + #[test] fn the_example_shaders_resolve_against_the_exported_packages() { let engine = exported_engine(); diff --git a/crates/processing_render/src/material/mod.rs b/crates/processing_render/src/material/mod.rs index 81bf14bd..b6924239 100644 --- a/crates/processing_render/src/material/mod.rs +++ b/crates/processing_render/src/material/mod.rs @@ -2,7 +2,8 @@ pub mod custom; pub mod pbr; use crate::compute; -use crate::render::material::UntypedMaterial; +use crate::render::command::Blend; +use crate::render::material::{UntypedMaterial, blended_alpha_mode}; use crate::shader_value::ShaderValue; use bevy::material::descriptor::RenderPipelineDescriptor; use bevy::material::specialize::SpecializedMeshPipelineError; @@ -30,6 +31,7 @@ impl Plugin for ProcessingMaterialPlugin { fn build(&self, app: &mut App) { crate::internal_shader!(app, PROCESSING_VERTEX_SHADER, "vertex.wesl"); crate::internal_shader!(app, PROCESSING_FRAGMENT_SHADER, "fragment.wesl"); + 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,29 @@ 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)>, +/// Changes a copy of a built-in material into what a draw needs. +pub(crate) fn apply_pbr_variant(material: &mut PbrMaterial, key: custom::VariantKey) { + material.extension.instance_fill = key.instance_fill; + // without a blend mode to follow, the material keeps its own + if key.blend_state.is_some() { + material.extension.blend_state = key.blend_state; + material.base.alpha_mode = blended_alpha_mode(key.blend_state, false); + } +} + +/// 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, @@ -236,18 +230,11 @@ pub fn set_alpha_mode( &mut custom, |m| { match m { - MaterialMut::Pbr(mat) => { - mat.base.alpha_mode = alpha_mode; - if opaque { - mat.extension.blend_state = None; - } - } - MaterialMut::Particles(mat) => mat.base.alpha_mode = alpha_mode, + MaterialMut::Pbr(mat) => mat.base.alpha_cutoff = cutoff, + MaterialMut::Particles(mat) => mat.base.alpha_cutoff = cutoff, MaterialMut::Custom(mat) => { - mat.alpha_mode = alpha_mode; - if opaque { - mat.blend_state = None; - } + mat.mask = cutoff; + custom::apply_mask(mat); } } Ok(()) @@ -338,13 +325,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 +345,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 = blended_alpha_mode(blend_state, false); 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 = blended_alpha_mode(blend_state, false); Ok(()) } }, @@ -397,6 +391,8 @@ 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, pub depth_write: Option, /// the fill is the sRGB8 RGBA color packed in each instance's `MeshTag` pub instance_fill: bool, @@ -506,3 +502,47 @@ pub(crate) fn apply_pipeline_state( depth_stencil.depth_write_enabled = Some(depth_write); } } + +#[cfg(test)] +mod tests { + use super::*; + use custom::VariantKey; + + fn material(blend_state: Option) -> PbrMaterial { + let mut material = PbrMaterial::default(); + material.extension.blend_state = blend_state; + material.base.alpha_mode = blended_alpha_mode(blend_state, false); + material.base.alpha_cutoff = Some(0.5); + material + } + + #[test] + fn a_fill_only_variant_keeps_the_materials_own_blending() { + let mut variant = material(Some(BlendState::ALPHA_BLENDING)); + let key = VariantKey { + blend_state: None, + instance_fill: true, + }; + apply_pbr_variant(&mut variant, key); + assert!(variant.extension.instance_fill); + assert_eq!( + variant.extension.blend_state, + Some(BlendState::ALPHA_BLENDING) + ); + assert_eq!(variant.base.alpha_mode, AlphaMode::Blend); + assert_eq!(variant.base.alpha_cutoff, Some(0.5)); + } + + #[test] + fn a_variant_follows_the_blend_mode_it_is_drawn_with() { + let mut variant = material(None); + let key = VariantKey { + blend_state: Some(BlendState::PREMULTIPLIED_ALPHA_BLENDING), + instance_fill: false, + }; + apply_pbr_variant(&mut variant, key); + assert_eq!(variant.extension.blend_state, key.blend_state); + assert_eq!(variant.base.alpha_mode, AlphaMode::Premultiplied); + assert_eq!(variant.base.alpha_cutoff, Some(0.5)); + } +} diff --git a/crates/processing_render/src/particles/material.rs b/crates/processing_render/src/particles/material.rs index 9cb53bb7..461b70ca 100644 --- a/crates/processing_render/src/particles/material.rs +++ b/crates/processing_render/src/particles/material.rs @@ -46,6 +46,7 @@ impl From<&ParticlesExtension> for ParticlesExtensionKey { #[derive(Asset, AsBindGroup, Reflect, Debug, Clone)] #[bind_group_data(ParticlesExtensionKey)] pub struct ParticlesExtension { + // the first of the engine's material bindings, `material::custom::ENGINE_BINDINGS` #[storage(100, read_only)] pub colors: Option>, #[storage(101, read_only)] diff --git a/crates/processing_render/src/render/command.rs b/crates/processing_render/src/render/command.rs index ca4e1924..f7d2b39a 100644 --- a/crates/processing_render/src/render/command.rs +++ b/crates/processing_render/src/render/command.rs @@ -351,6 +351,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 { @@ -368,6 +378,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}" ))), @@ -448,6 +460,8 @@ impl BlendMode { Self::Multiply => "MULTIPLY", Self::Screen => "SCREEN", Self::Replace => "REPLACE", + Self::Opaque => "OPAQUE", + Self::Premultiplied => "PREMULTIPLIED", } } @@ -463,11 +477,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::*; @@ -478,7 +508,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, @@ -712,7 +743,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 6c8068e4..1a15c84c 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 dc64a41d..4950add3 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, @@ -969,12 +973,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); @@ -1265,8 +1272,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 { @@ -1629,7 +1640,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 mut takes_fill = false; let material_handle = match key { MaterialKey::Custom { entity, @@ -1639,8 +1650,8 @@ fn spawn_mesh( warn!("Custom material entity {:?} not found", entity); return; }; - custom_shader = is_custom_shader(&untyped.0); - material_variant(res, &untyped.0, *blend_state, true) + takes_fill = is_custom_shader(&untyped.0) || is_pbr_material(&untyped.0); + material_variant(res, &untyped.0, *blend_state, takes_fill) } _ => key.to_material(&mut res.materials, sort_bias(batch.draw_index)), }; @@ -1652,7 +1663,7 @@ fn spawn_mesh( transform, batch.render_layers.clone(), )); - if custom_shader { + if takes_fill { // the vertices carry the fill entity.insert(MeshTag::new(WHITE_FILL)); } @@ -1742,34 +1753,69 @@ fn is_custom_shader(material: &UntypedHandle) -> bool { material.type_id() == std::any::TypeId::of::() } +fn is_pbr_material(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. +/// `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() && material.extension.instance_fill == instance_fill { + return original.clone(); + } + let key = VariantKey { + blend_state, + instance_fill, + }; + let variant = res.pbr_variants.get( + &mut res.materials, + &handle, + key, + crate::material::apply_pbr_variant, + ); + return variant.map_or_else(|| original.clone(), Handle::untyped); + } + original.clone() } fn material_key_with_color( @@ -1871,16 +1917,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( @@ -1965,12 +2013,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 @@ -1982,8 +2031,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)); @@ -2223,9 +2273,16 @@ fn draw_mesh3d( warn!("Custom material entity {:?} not found", entity); return; }; - let material = material_variant(res, &untyped.0, state.style.blend_state, true); - let tag = if !is_custom_shader(&untyped.0) { + // a particle material reads its tag as a particle index, not a fill + let takes_fill = is_custom_shader(&untyped.0) || is_pbr_material(&untyped.0); + let material = + material_variant(res, &untyped.0, state.style.blend_state, takes_fill); + let lines = matches!(draw.paint, MeshPaint::Lines); + let tag = if !takes_fill { None + } else if lines && is_pbr_material(&untyped.0) { + // the stroke decides whether lines draw; the material colors them + Some(WHITE_FILL) } else if let Some(tag) = fill_tag(color, draws.quantize_fill) { Some(tag) } else { @@ -2250,6 +2307,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), @@ -2279,8 +2337,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/docs/api.md b/docs/api.md index ef760330..f2cbd1cb 100644 --- a/docs/api.md +++ b/docs/api.md @@ -91,6 +91,11 @@ While materials are typically defined in terms of their interaction with light i implementation of a shader is simply a fragment shader that is applied to a full-screen quad. In this way, materials can also be used to implement 2D image processing effects, etc. +A material's blend mode sets how it combines with what is behind it; a material without one follows the blend mode it +is drawn with. Its mask is separate: fragments with alpha below the cutoff are discarded, with or without blending. A +custom shader takes part by importing `processing::material` and calling `mask(alpha)`, or by reading `mask_cutoff` +itself. Material bindings from 100 up are the engine's; a shader declares its own below that. + ### Shader [//]: # (TODO: Document Shader API object, do we even need this with a sufficiently robust Material API?) 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, }, diff --git a/tests/visual/cases.toml b/tests/visual/cases.toml index 26b40681..7f2c7b48 100644 --- a/tests/visual/cases.toml +++ b/tests/visual/cases.toml @@ -87,6 +87,10 @@ python = "gltf_load.py" name = "py_lights" python = "lights.py" +[[case]] +name = "py_mask" +python = "mask.py" + [[case]] name = "py_materials" python = "materials.py"