Skip to content
Merged
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
2 changes: 2 additions & 0 deletions crates/processing_core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ pub type Result<T> = std::result::Result<T, ProcessingError>;
pub enum ProcessingError {
#[error("App was accessed from multiple threads")]
AppAccess,
#[error("Not initialized yet; call size() first")]
AppNotInitialized,
#[error("Error initializing tracing: {0}")]
Tracing(#[from] tracing::subscriber::SetGlobalDefaultError),
#[error("Surface not found")]
Expand Down
2 changes: 1 addition & 1 deletion crates/processing_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub fn app_mut<T>(cb: impl FnOnce(&mut App) -> error::Result<T>) -> error::Resul
.map_err(|_| error::ProcessingError::AppAccess)?;
let app = app_borrow
.as_mut()
.ok_or(error::ProcessingError::AppAccess)?;
.ok_or(error::ProcessingError::AppNotInitialized)?;
cb(app)
});
match res {
Expand Down
14 changes: 12 additions & 2 deletions crates/processing_pyo3/src/compute.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use bevy::color::ColorToComponents;
use bevy::prelude::Entity;
use processing::prelude::*;
use pyo3::{
Expand Down Expand Up @@ -112,7 +113,7 @@ impl Buffer {
value: &Bound<'_, PyAny>,
) -> PyResult<()> {
if let Ok(i) = index.extract::<isize>() {
let sv = py_to_shader_value(value)?;
let sv = buffer_element(value)?;
self.check_element_type(&sv)?;
let bytes = sv
.to_bytes()
Expand Down Expand Up @@ -246,11 +247,19 @@ fn slice_positions(indices: &PySliceIndices) -> impl Iterator<Item = isize> + us
(0..slicelength as isize).map(move |i| start + i * step)
}

/// A `Color` is stored as its linear RGBA floats.
fn buffer_element(value: &Bound<'_, PyAny>) -> PyResult<ShaderValue> {
Ok(match py_to_shader_value(value)? {
ShaderValue::Color(c) => ShaderValue::Float4(c.to_linear().to_f32_array()),
sv => sv,
})
}

fn shader_values_to_bytes(values: &Bound<'_, PyAny>) -> PyResult<(Vec<u8>, Option<ShaderValue>)> {
let mut bytes = Vec::new();
let mut element_type: Option<ShaderValue> = None;
for item in values.try_iter()? {
let sv = py_to_shader_value(&item?)?;
let sv = buffer_element(&item?)?;
if let Some(ref existing) = element_type
&& std::mem::discriminant(existing) != std::mem::discriminant(&sv)
{
Expand Down Expand Up @@ -288,6 +297,7 @@ fn shader_value_to_py<'py>(py: Python<'py>, sv: &ShaderValue) -> PyResult<Bound<
ShaderValue::UInt3(v) => list(py, v),
ShaderValue::UInt4(v) => list(py, v),
ShaderValue::Mat4(v) => list(py, v),
ShaderValue::Color(c) => Ok(crate::color::PyColor(*c).into_pyobject(py)?.into_any()),
ShaderValue::Texture(_)
| ShaderValue::Buffer(_)
| ShaderValue::MeshAttribute(..)
Expand Down
9 changes: 8 additions & 1 deletion crates/processing_pyo3/src/gltf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use bevy::prelude::Entity;
use processing::prelude::*;
use pyo3::{exceptions::PyRuntimeError, prelude::*};

use crate::graphics::{Geometry, Light};
use crate::graphics::{Geometry, Image, Light};
use crate::material::Material;

#[pyclass(unsendable)]
Expand Down Expand Up @@ -35,6 +35,13 @@ impl Gltf {
Ok(Material { entity })
}

/// The texture on the named mesh.
pub fn texture(&self, name: &str) -> PyResult<Image> {
let entity =
gltf_texture(self.entity, name).map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
Ok(Image::wrap(entity))
}

pub fn mesh_names(&self) -> PyResult<Vec<String>> {
gltf_mesh_names(self.entity).map_err(|e| PyRuntimeError::new_err(format!("{e}")))
}
Expand Down
21 changes: 19 additions & 2 deletions crates/processing_pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,11 @@ fn create_graphics_context(
let env = detect_environment(module)?;

let interactive = env != "script";
let log_level = if interactive { Some("error") } else { None };
let log_level = if interactive {
Some("error")
} else {
Some("warn")
};

let has_existing = module
.getattr("_graphics")
Expand Down Expand Up @@ -1290,6 +1294,7 @@ pub mod processing_py {
.end_draw()?;

loop {
py.check_signals()?;
{
let mut graphics = get_graphics_mut(module)?
.ok_or_else(|| PyRuntimeError::new_err("call size() first"))?;
Expand All @@ -1315,6 +1320,8 @@ pub mod processing_py {
let mut draw_failed = false;

loop {
// catches Ctrl-C while paused
py.check_signals()?;
if let Some(ref hot) = hot {
let setup_changed = hot.call_method0("poll")?;
if !setup_changed.is_none() {
Expand Down Expand Up @@ -1387,7 +1394,7 @@ pub mod processing_py {
}
if let Err(e) = drawn {
if hot.is_none() {
return Err(PyRuntimeError::new_err(format!("{e}")));
return Err(e);
}
report_live_error(py, e)?;
draw_failed = true;
Expand All @@ -1403,6 +1410,16 @@ pub mod processing_py {
}

Ok(())
})
.or_else(|e: PyErr| {
// Ctrl-C quits the sketch like closing its window
Python::attach(|py| {
if e.is_instance_of::<pyo3::exceptions::PyKeyboardInterrupt>(py) {
Ok(())
} else {
Err(e)
}
})
});

// tear down the app while the thread-local is still alive; the eager
Expand Down
4 changes: 4 additions & 0 deletions crates/processing_pyo3/src/material.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ pub(crate) fn py_to_shader_value(value: &Bound<'_, PyAny>) -> PyResult<shader_va
if let Ok(v) = value.extract::<PyRef<PyVec2>>() {
return Ok(shader_value::ShaderValue::Float2(v.0.to_array()));
}
// before the sequence fallbacks: a Color iterates in its own space
if let Ok(c) = value.extract::<PyRef<PyColor>>() {
return Ok(shader_value::ShaderValue::Color(c.0));
}

if let Ok(buf) = value.extract::<PyRef<Buffer>>() {
return Ok(shader_value::ShaderValue::Buffer(buf.entity));
Expand Down
28 changes: 24 additions & 4 deletions crates/processing_pyo3/src/particles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,25 @@ fn parse_falloff(s: &str) -> PyResult<u32> {
}
}

/// `emit()` data: flat numbers, or one value per particle.
fn emit_bytes(name: &str, value: &Bound<'_, PyAny>) -> PyResult<Vec<u8>> {
let mut bytes = Vec::new();
for item in value.try_iter()? {
let item = item?;
// a bare int would become an i32 shader value
if let Ok(f) = item.extract::<f32>() {
bytes.extend_from_slice(&f.to_le_bytes());
continue;
}
let sv = crate::material::py_to_shader_value(&item)?;
let b = sv.to_bytes().ok_or_else(|| {
PyTypeError::new_err(format!("attribute '{name}': unsupported value {sv:?}"))
})?;
bytes.extend_from_slice(&b);
}
Ok(bytes)
}

#[pyclass(unsendable)]
pub struct Grid {
pub(crate) entity: Entity,
Expand Down Expand Up @@ -977,19 +996,20 @@ impl Particles {
for (key, value) in kwargs.iter() {
let name: String = key.extract()?;
let attr_entity = self.resolve_attribute(&key)?;
particles_ensure_attribute(self.entity, attr_entity)
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
let (_, fmt) = geometry_attribute_info(attr_entity)
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
let fmt = AttributeFormat::from_inner(fmt);
let floats: Vec<f32> = value.extract()?;
let bytes = emit_bytes(&name, &value)?;
let expected = (n as usize) * fmt.float_count();
if floats.len() != expected {
if bytes.len() != expected * 4 {
return Err(PyRuntimeError::new_err(format!(
"attribute '{name}': expected {expected} floats ({} per particle × {n}), got {}",
fmt.float_count(),
floats.len(),
bytes.len() / 4,
)));
}
let bytes: Vec<u8> = floats.iter().flat_map(|f| f.to_le_bytes()).collect();
data.push((attr_entity, bytes));
}
particles_emit(self.entity, n, data).map_err(|e| PyRuntimeError::new_err(format!("{e}")))
Expand Down
15 changes: 14 additions & 1 deletion crates/processing_render/src/compute.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::collections::{BTreeSet, HashMap};
use std::collections::{BTreeSet, HashMap, HashSet};

use bevy::asset::{AssetId, RenderAssetUsages};
use bevy::mesh::MeshVertexAttribute;
Expand All @@ -21,6 +21,7 @@ use bevy::{
};

use bevy_naga_reflect::dynamic_shader::DynamicShader;
use bevy_naga_reflect::reflect::ParameterCategory;

use crate::geometry::{Attribute, Geometry};
use crate::material::custom::Shader;
Expand Down Expand Up @@ -220,6 +221,8 @@ pub struct Compute {
pub pipeline_id: CachedComputePipelineId,
pub bind_group_layout_descriptors: Vec<(u32, BindGroupLayoutDescriptor)>,
pub mesh_bindings: HashMap<String, MeshBindingRef>,
/// Storage arrays bound to a particle system's columns by the last apply or emit.
pub column_bindings: HashSet<String>,
}

fn queue_pipeline(
Expand Down Expand Up @@ -328,6 +331,7 @@ pub fn create_compute(app: &mut App, shader_entity: Entity) -> Result<Entity> {
pipeline_id,
bind_group_layout_descriptors,
mesh_bindings: HashMap::new(),
column_bindings: HashSet::new(),
})
.id());
}
Expand Down Expand Up @@ -370,6 +374,15 @@ pub fn dispatch(
if !ready {
return Err(ProcessingError::ResourceNotReady(name.to_string()));
}
// wgpu treats an incomplete bind group as fatal
if matches!(param.category(), ParameterCategory::Storage { .. })
&& shader.buffer_handle(name).is_none()
&& !mesh_bindings.iter().any(|(n, _)| n == name)
{
return Err(ProcessingError::InvalidArgument(format!(
"nothing is bound to the shader's storage array `{name}`"
)));
}
}

let mut bind_groups = Vec::new();
Expand Down
73 changes: 57 additions & 16 deletions crates/processing_render/src/gltf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use bevy::{
io::{AssetSourceId, embedded::GetAssetServer},
},
ecs::system::RunSystemOnce,
gltf::{Gltf, GltfMaterial, GltfMeshName},
gltf::{Gltf, GltfMaterial, GltfMaterialName, GltfMeshName},
pbr::ExtendedMaterial,
platform::collections::HashSet,
prelude::*,
Expand Down Expand Up @@ -185,21 +185,7 @@ pub fn geometry(
let instance_id = gltf_handle.instance_id;

let (mesh_handle, global_transform) = {
let spawner = world.resource::<WorldInstanceSpawner>();

// find the mesh with the given name component that bevy added post-spawn
// name is derived from gltf node or computed
let mesh_entity = spawner
.iter_instance_entities(instance_id)
.find(|&e| {
world
.get::<GltfMeshName>(e)
.map(|n| n.0 == name)
.unwrap_or(false)
})
.ok_or_else(|| {
ProcessingError::GltfLoadError(format!("Mesh '{}' not found in GLTF scene", name))
})?;
let mesh_entity = find_mesh_entity(world, instance_id, &name)?;

let mesh3d = world.get::<Mesh3d>(mesh_entity).ok_or_else(|| {
ProcessingError::GltfLoadError(format!(
Expand Down Expand Up @@ -229,6 +215,61 @@ pub fn geometry(
Ok(entity)
}

/// The scene entity bevy spawned for a mesh, by the name it gave that mesh.
fn find_mesh_entity(
world: &World,
instance_id: bevy::world_serialization::InstanceId,
name: &str,
) -> Result<Entity> {
world
.resource::<WorldInstanceSpawner>()
.iter_instance_entities(instance_id)
.find(|&e| world.get::<GltfMeshName>(e).is_some_and(|n| n.0 == name))
.ok_or_else(|| {
ProcessingError::GltfLoadError(format!("Mesh '{}' not found in GLTF scene", name))
})
}

/// The base color texture of a mesh's material.
pub fn texture(In((gltf_entity, name)): In<(Entity, String)>, world: &mut World) -> Result<Entity> {
let gltf_handle = world
.get::<GltfHandle>(gltf_entity)
.ok_or(ProcessingError::InvalidEntity)?;
let (instance_id, handle) = (gltf_handle.instance_id, gltf_handle.handle.clone());

let mesh_entity = find_mesh_entity(world, instance_id, &name)?;
let material_name = world
.get::<GltfMaterialName>(mesh_entity)
.ok_or_else(|| ProcessingError::GltfLoadError(format!("Mesh '{}' has no material", name)))?
.0
.clone();

let texture = {
let gltf = world
.resource::<Assets<Gltf>>()
.get(&handle)
.ok_or_else(|| ProcessingError::GltfLoadError("GLTF asset not found".into()))?;
let material = gltf
.named_materials
.get(material_name.as_str())
.and_then(|h| world.resource::<Assets<GltfMaterial>>().get(h))
.ok_or_else(|| {
ProcessingError::GltfLoadError(format!(
"Material '{}' not found in GLTF",
material_name
))
})?;
material.base_color_texture.clone().ok_or_else(|| {
ProcessingError::GltfLoadError(format!("Mesh '{}' has no texture", name))
})?
};

block_on_load(world, |w| w.get_asset_server().load_state(&texture))?;
world
.run_system_once_with(crate::image::from_handle, texture)
.unwrap()
}

/// Translate a bevy [`GltfMaterial`] into the [`StandardMaterial`] base of a
/// [`ProcessingExtendedMaterial`]. `GltfMaterial` mirrors `StandardMaterial`'s
/// fields, so we copy across the ones that drive shading and let the rest fall
Expand Down
16 changes: 12 additions & 4 deletions crates/processing_render/src/graphics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use bevy::{
CameraMainTextureUsages, CameraOutputMode, CameraProjection, ClearColorConfig, Hdr,
ImageRenderTarget, MsaaWriteback, Projection, RenderTarget, visibility::RenderLayers,
},
core_pipeline::tonemapping::Tonemapping,
core_pipeline::tonemapping::{DebandDither, Tonemapping},
ecs::query::QueryEntityError,
math::{Mat4, Vec3A, Vec4},
prelude::*,
Expand Down Expand Up @@ -329,6 +329,8 @@ pub fn create(
},
target,
Tonemapping::None,
// dithering only applies after tonemapping
DebandDither::Disabled,
// we need to be able to write to the texture
CameraMainTextureUsages::default().with(TextureUsages::COPY_DST),
Projection::custom(ProcessingProjection::new(width as f32, height as f32)),
Expand Down Expand Up @@ -658,11 +660,17 @@ pub fn tonemapping_from_u8(v: u8) -> Option<Tonemapping> {

pub fn set_tonemapping(
In((entity, tonemapping)): In<(Entity, Tonemapping)>,
mut query: Query<&mut Tonemapping>,
mut query: Query<(&mut Tonemapping, &mut DebandDither)>,
) -> Result<()> {
*query
let (mut current, mut dither) = query
.get_mut(entity)
.map_err(|_| ProcessingError::GraphicsNotFound)? = tonemapping;
.map_err(|_| ProcessingError::GraphicsNotFound)?;
*dither = if tonemapping == Tonemapping::None {
DebandDither::Disabled
} else {
DebandDither::Enabled
};
*current = tonemapping;
Ok(())
}

Expand Down
Loading
Loading