-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathparticles.rs
More file actions
275 lines (252 loc) · 9.57 KB
/
Copy pathparticles.rs
File metadata and controls
275 lines (252 loc) · 9.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
use bevy::prelude::Entity;
use processing::prelude::*;
use processing_render::geometry;
use pyo3::types::PyDict;
use pyo3::{exceptions::PyRuntimeError, prelude::*};
use std::collections::HashMap;
use crate::compute::{Buffer, Compute};
use crate::graphics::Geometry;
#[pyclass(eq, eq_int, from_py_object)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum AttributeFormat {
Float = 1,
Float2 = 2,
Float3 = 3,
Float4 = 4,
}
impl AttributeFormat {
pub(crate) fn to_inner(self) -> geometry::AttributeFormat {
match self {
Self::Float => geometry::AttributeFormat::Float,
Self::Float2 => geometry::AttributeFormat::Float2,
Self::Float3 => geometry::AttributeFormat::Float3,
Self::Float4 => geometry::AttributeFormat::Float4,
}
}
pub(crate) fn from_inner(inner: geometry::AttributeFormat) -> Self {
match inner {
geometry::AttributeFormat::Float => Self::Float,
geometry::AttributeFormat::Float2 => Self::Float2,
geometry::AttributeFormat::Float3 => Self::Float3,
geometry::AttributeFormat::Float4 => Self::Float4,
}
}
pub(crate) fn float_count(self) -> usize {
match self {
Self::Float => 1,
Self::Float2 => 2,
Self::Float3 => 3,
Self::Float4 => 4,
}
}
}
/// named typed attribute. use the `position()`/`color()`/etc. classmethods for
/// builtins or `Attribute(name, format)` for custom ones.
#[pyclass(unsendable, frozen, hash, eq, from_py_object)]
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Attribute {
pub(crate) entity: Entity,
}
#[pymethods]
impl Attribute {
#[new]
pub fn new(name: &str, format: AttributeFormat) -> PyResult<Self> {
let entity = geometry_attribute_create(name, format.to_inner())
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
Ok(Self { entity })
}
#[staticmethod]
pub fn position() -> Self {
Self {
entity: geometry_attribute_position(),
}
}
#[staticmethod]
pub fn normal() -> Self {
Self {
entity: geometry_attribute_normal(),
}
}
#[staticmethod]
pub fn color() -> Self {
Self {
entity: geometry_attribute_color(),
}
}
#[staticmethod]
pub fn uv() -> Self {
Self {
entity: geometry_attribute_uv(),
}
}
#[staticmethod]
pub fn rotation() -> Self {
Self {
entity: geometry_attribute_rotation(),
}
}
#[staticmethod]
pub fn scale() -> Self {
Self {
entity: geometry_attribute_scale(),
}
}
#[staticmethod]
pub fn dead() -> Self {
Self {
entity: geometry_attribute_dead(),
}
}
#[getter]
pub fn name(&self) -> PyResult<String> {
let (name, _) = geometry_attribute_info(self.entity)
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
Ok(name)
}
#[getter]
pub fn format(&self) -> PyResult<AttributeFormat> {
let (_, fmt) = geometry_attribute_info(self.entity)
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
Ok(AttributeFormat::from_inner(fmt))
}
}
#[pyclass(unsendable)]
pub struct Particles {
pub(crate) entity: Entity,
// name → (entity, format); used by `emit(**kwargs)` to route kwargs and pack bytes
name_to_attr: HashMap<String, (Entity, AttributeFormat)>,
}
impl Particles {
fn build_name_index(
attrs: &[Attribute],
) -> PyResult<HashMap<String, (Entity, AttributeFormat)>> {
let mut map = HashMap::with_capacity(attrs.len());
for attr in attrs {
let (name, fmt) = geometry_attribute_info(attr.entity)
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
map.insert(name, (attr.entity, AttributeFormat::from_inner(fmt)));
}
Ok(map)
}
}
#[pymethods]
impl Particles {
/// pass `capacity` for empty buffers, or `geometry` to seed from a source mesh.
#[new]
#[pyo3(signature = (capacity=None, attributes=None, geometry=None))]
pub fn new(
capacity: Option<u32>,
attributes: Option<Vec<PyRef<Attribute>>>,
geometry: Option<&Geometry>,
) -> PyResult<Self> {
let attrs: Vec<Attribute> = attributes
.unwrap_or_default()
.iter()
.map(|a| (**a).clone())
.collect();
let attr_entities: Vec<Entity> = attrs.iter().map(|a| a.entity).collect();
let entity = match (capacity, geometry) {
(Some(cap), None) => particles_create(cap, attr_entities)
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?,
(None, Some(g)) => particles_create_from_geometry(g.entity, attr_entities)
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?,
(None, None) => {
return Err(PyRuntimeError::new_err(
"Particles requires either capacity or geometry",
));
}
(Some(_), Some(_)) => {
return Err(PyRuntimeError::new_err(
"Particles accepts capacity or geometry, not both",
));
}
};
Ok(Self {
entity,
name_to_attr: Particles::build_name_index(&attrs)?,
})
}
#[getter]
pub fn capacity(&self) -> PyResult<u32> {
particles_capacity(self.entity).map_err(|e| PyRuntimeError::new_err(format!("{e}")))
}
/// backing `Buffer` for a registered attribute, or `None` if not registered.
pub fn buffer(&self, attribute: &Attribute) -> PyResult<Option<Buffer>> {
let buf = particles_buffer(self.entity, attribute.entity)
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
let (_, fmt) = geometry_attribute_info(attribute.entity)
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
let element_type = match AttributeFormat::from_inner(fmt) {
AttributeFormat::Float => shader_value::ShaderValue::Float(0.0),
AttributeFormat::Float2 => shader_value::ShaderValue::Float2([0.0; 2]),
AttributeFormat::Float3 => shader_value::ShaderValue::Float3([0.0; 3]),
AttributeFormat::Float4 => shader_value::ShaderValue::Float4([0.0; 4]),
};
Ok(buf.map(|e| Buffer::from_entity(e, Some(element_type))))
}
/// dispatch a compute kernel against these particles' buffers. buffers are
/// auto-bound by attribute name; kwargs are forwarded to `compute.set(...)`.
#[pyo3(signature = (compute, **kwargs))]
pub fn apply(&self, compute: &Compute, kwargs: Option<&Bound<'_, PyDict>>) -> PyResult<()> {
if let Some(kwargs) = kwargs {
compute.set(Some(kwargs))?;
}
particles_apply(self.entity, compute.entity)
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))
}
/// emit `n` particles into the next ring-buffer slots. per-attribute data
/// is a kwarg keyed by attribute name; each value is a flat list of
/// `n * format.float_count()` floats.
#[pyo3(signature = (n, **kwargs))]
pub fn emit(&self, n: u32, kwargs: Option<&Bound<'_, PyDict>>) -> PyResult<()> {
let Some(kwargs) = kwargs else {
return particles_emit(self.entity, n, vec![])
.map_err(|e| PyRuntimeError::new_err(format!("{e}")));
};
let mut data: Vec<(Entity, Vec<u8>)> = Vec::new();
for (key, value) in kwargs.iter() {
let name: String = key.extract()?;
let (attr_entity, fmt) = self.name_to_attr.get(&name).copied().ok_or_else(|| {
PyRuntimeError::new_err(format!(
"no attribute named '{name}' (registered: {:?})",
self.name_to_attr.keys().collect::<Vec<_>>()
))
})?;
let floats: Vec<f32> = value.extract()?;
let expected = (n as usize) * fmt.float_count();
if floats.len() != expected {
return Err(PyRuntimeError::new_err(format!(
"attribute '{name}': expected {expected} floats ({} per particle × {n}), got {}",
fmt.float_count(),
floats.len(),
)));
}
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}")))
}
/// emit `n` particles via a GPU kernel. auto-binds buffers and an
/// `emit_range: vec4<f32> = (base_slot, n, capacity, 0)` uniform.
pub fn emit_gpu(&self, n: u32, compute: &Compute) -> PyResult<()> {
particles_emit_gpu(self.entity, n, compute.entity)
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))
}
}
impl Drop for Particles {
fn drop(&mut self) {
let _ = particles_destroy(self.entity);
}
}
/// built-in noise kernel. uniforms: `scale`, `strength`, `time`.
pub fn kernel_noise() -> PyResult<Compute> {
let entity = particles_kernel_noise().map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
Ok(Compute::from_entity(entity))
}
/// built-in transform kernel: scale → axis-angle rotate → translate. uniforms:
/// `translate: vec3`, `rotation_axis: vec3`, `rotation_angle: f32`, `scale: vec3`.
pub fn kernel_transform() -> PyResult<Compute> {
let entity =
particles_kernel_transform().map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
Ok(Compute::from_entity(entity))
}