forked from djeedai/bevy_hanabi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
accel.rs
377 lines (333 loc) Β· 12.1 KB
/
accel.rs
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
//! Modifiers influencing the acceleration of particles.
//!
//! The particle acceleration directly drives their velocity. It's applied each
//! frame during simulation update.
/// ```txt
/// particle.velocity += acceleration * simulation.delta_time;
/// ```
use std::hash::Hash;
use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{
calc_func_id,
expr::PropertyHandle,
graph::{BuiltInExpr, EvalContext, ExprError},
Attribute, BoxedModifier, ExprHandle, Modifier, ModifierContext, Module, ShaderWriter,
};
/// A modifier to apply a uniform acceleration to all particles each frame, to
/// simulate gravity or any other global force.
///
/// The acceleration is the same for all particles of the effect, and is applied
/// each frame to modify the particle's velocity based on the simulation
/// timestep.
///
/// ```txt
/// particle.velocity += acceleration * simulation.delta_time;
/// ```
///
/// # Attributes
///
/// This modifier requires the following particle attributes:
/// - [`Attribute::VELOCITY`]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
pub struct AccelModifier {
/// The acceleration to apply to all particles in the effect each frame.
///
/// Expression type: `Vec3`
accel: ExprHandle,
}
impl AccelModifier {
/// Create a new modifier from an acceleration expression.
pub fn new(accel: ExprHandle) -> Self {
Self { accel }
}
/// Create a new modifier with an acceleration derived from a property.
///
/// To create a new property, use [`Module::add_property()`].
pub fn via_property(module: &mut Module, property: PropertyHandle) -> Self {
Self {
accel: module.prop(property),
}
}
/// Create a new modifier with a constant acceleration.
pub fn constant(module: &mut Module, acceleration: Vec3) -> Self {
Self {
accel: module.lit(acceleration),
}
}
}
#[typetag::serde]
impl Modifier for AccelModifier {
fn context(&self) -> ModifierContext {
ModifierContext::Update
}
fn attributes(&self) -> &[Attribute] {
&[Attribute::VELOCITY]
}
fn boxed_clone(&self) -> BoxedModifier {
Box::new(*self)
}
fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
let attr = module.attr(Attribute::VELOCITY);
let attr = context.eval(module, attr)?;
let expr = context.eval(module, self.accel)?;
let dt = BuiltInExpr::new(crate::graph::BuiltInOperator::DeltaTime).eval(context)?;
context.main_code += &format!("{} += ({}) * {};", attr, expr, dt);
Ok(())
}
}
/// A modifier to apply a radial acceleration to all particles each frame.
///
/// The acceleration is the same for all particles of the effect, and is applied
/// each frame to modify the particle's velocity based on the simulation
/// timestep.
///
/// ```txt
/// particle.velocity += acceleration * simulation.delta_time;
/// ```
///
/// In the absence of other modifiers, the radial acceleration alone, if
/// oriented toward the center point, makes particles move toward that center
/// point. The radial direction is calculated as the direction from the modifier
/// origin to the particle position.
///
/// # Attributes
///
/// This modifier requires the following particle attributes:
/// - [`Attribute::POSITION`]
/// - [`Attribute::VELOCITY`]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
pub struct RadialAccelModifier {
/// The center point the radial direction is calculated from.
///
/// Expression type: `Vec3`
origin: ExprHandle,
/// The acceleration to apply to all particles in the effect each frame.
///
/// Expression type: `f32`
accel: ExprHandle,
}
impl RadialAccelModifier {
/// Create a new modifier from an origin expression and an acceleration
/// expression.
pub fn new(origin: ExprHandle, accel: ExprHandle) -> Self {
Self { origin, accel }
}
/// Create a new modifier with an acceleration derived from a property.
///
/// The origin of the sphere defining the radial direction is constant.
///
/// To create a new property, use [`Module::add_property()`].
pub fn via_property(module: &mut Module, origin: Vec3, property: PropertyHandle) -> Self {
Self {
origin: module.lit(origin),
accel: module.prop(property),
}
}
/// Create a new modifier with a constant radial origin and acceleration.
pub fn constant(module: &mut Module, origin: Vec3, acceleration: f32) -> Self {
Self {
origin: module.lit(origin),
accel: module.lit(acceleration),
}
}
}
#[typetag::serde]
impl Modifier for RadialAccelModifier {
fn context(&self) -> ModifierContext {
ModifierContext::Update
}
fn attributes(&self) -> &[Attribute] {
&[Attribute::POSITION, Attribute::VELOCITY]
}
fn boxed_clone(&self) -> BoxedModifier {
Box::new(*self)
}
fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
let func_id = calc_func_id(self);
let func_name = format!("radial_accel_{0:016X}", func_id);
context.make_fn(
&func_name,
"particle: ptr<function, Particle>",
module,
&mut |m: &mut Module, ctx: &mut dyn EvalContext| -> Result<String, ExprError> {
let origin = ctx.eval(m, self.origin)?;
let accel = ctx.eval(m, self.accel)?;
Ok(format!(
r##"let radial = normalize((*particle).{} - {});
(*particle).{} += radial * (({}) * sim_params.delta_time);
"##,
Attribute::POSITION.name(),
origin,
Attribute::VELOCITY.name(),
accel,
))
},
)?;
context.main_code += &format!("{}(&particle);\n", func_name);
Ok(())
}
}
/// A modifier to apply a tangential acceleration to all particles each frame.
///
/// The acceleration is the same for all particles of the effect, and is applied
/// each frame to modify the particle's velocity based on the simulation
/// timestep.
///
/// ```txt
/// particle.velocity += acceleration * simulation.delta_time;
/// ```
///
/// In the absence of other modifiers, the tangential acceleration alone makes
/// particles rotate around the center point. The tangent direction is
/// calculated as the cross product of the rotation plane axis and the direction
/// from the modifier origin to the particle position. The effect is undefined
/// if those two directions align.
///
/// # Attributes
///
/// This modifier requires the following particle attributes:
/// - [`Attribute::POSITION`]
/// - [`Attribute::VELOCITY`]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
pub struct TangentAccelModifier {
/// The center point the tangent direction is calculated from.
///
/// Expression type: `Vec3`
origin: ExprHandle,
/// The axis defining the rotation plane and orientation.
///
/// Expression type: `Vec3`
axis: ExprHandle,
/// The acceleration to apply to all particles in the effect each frame.
///
/// Expression type: `f32`
accel: ExprHandle,
}
impl TangentAccelModifier {
/// Create a new modifier from origin and axis expressions, and an
/// acceleration expression.
pub fn new(origin: ExprHandle, axis: ExprHandle, accel: ExprHandle) -> Self {
Self {
origin,
axis,
accel,
}
}
/// Create a new modifier with an acceleration derived from a property.
///
/// The origin and axis are constant.
///
/// To create a new property, use [`Module::add_property()`].
pub fn via_property(
module: &mut Module,
origin: Vec3,
axis: Vec3,
property: PropertyHandle,
) -> Self {
Self {
origin: module.lit(origin),
axis: module.lit(axis),
accel: module.prop(property),
}
}
/// Create a new modifier with constant values.
pub fn constant(module: &mut Module, origin: Vec3, axis: Vec3, acceleration: f32) -> Self {
Self {
origin: module.lit(origin),
axis: module.lit(axis),
accel: module.lit(acceleration),
}
}
}
#[typetag::serde]
impl Modifier for TangentAccelModifier {
fn context(&self) -> ModifierContext {
ModifierContext::Update
}
fn attributes(&self) -> &[Attribute] {
&[Attribute::POSITION, Attribute::VELOCITY]
}
fn boxed_clone(&self) -> BoxedModifier {
Box::new(*self)
}
fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
let func_id = calc_func_id(self);
let func_name = format!("tangent_accel_{0:016X}", func_id);
let origin = context.eval(module, self.origin)?;
let axis = context.eval(module, self.axis)?;
let accel = context.eval(module, self.accel)?;
context.extra_code += &format!(
r##"fn {}(particle: ptr<function, Particle>) {{
let radial = normalize((*particle).{} - {});
let tangent = normalize(cross({}, radial));
(*particle).{} += tangent * (({}) * sim_params.delta_time);
}}
"##,
func_name,
Attribute::POSITION.name(),
origin,
axis,
Attribute::VELOCITY.name(),
accel,
);
context.main_code += &format!("{}(&particle);\n", func_name);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{ParticleLayout, Property, PropertyLayout, ToWgslString};
#[test]
fn mod_accel() {
let mut module = Module::default();
let accel = Vec3::new(1., 2., 3.);
let modifier = AccelModifier::constant(&mut module, accel);
let property_layout = PropertyLayout::default();
let particle_layout = ParticleLayout::default();
let mut context =
ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);
assert!(modifier.apply(&mut module, &mut context).is_ok());
assert!(context.main_code.contains(&accel.to_wgsl_string()));
}
#[test]
fn mod_radial_accel() {
let mut module = Module::default();
let property_layout = PropertyLayout::new(&[Property::new("my_prop", 3.)]);
let particle_layout = ParticleLayout::default();
let origin = Vec3::new(-1.2, 5.3, -8.5);
let accel = 6.;
let modifier = RadialAccelModifier::constant(&mut module, origin, accel);
let mut context =
ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);
assert!(modifier.apply(&mut module, &mut context).is_ok());
// TODO: less weak check...
assert!(context.extra_code.contains(&accel.to_wgsl_string()));
let origin = module.attr(Attribute::POSITION);
let my_prop = module.add_property("my_prop", 3.0.into());
let accel = module.prop(my_prop);
let modifier = RadialAccelModifier::new(origin, accel);
let mut context =
ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);
assert!(modifier.apply(&mut module, &mut context).is_ok());
// TODO: less weak check...
assert!(context.extra_code.contains(Attribute::POSITION.name()));
assert!(context.extra_code.contains("my_prop"));
}
#[test]
fn mod_tangent_accel() {
let mut module = Module::default();
let origin = Vec3::new(-1.2, 5.3, -8.5);
let axis = Vec3::Y;
let accel = 6.;
let modifier = TangentAccelModifier::constant(&mut module, origin, axis, accel);
let property_layout = PropertyLayout::default();
let particle_layout = ParticleLayout::default();
let mut context =
ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);
assert!(modifier.apply(&mut module, &mut context).is_ok());
// TODO: less weak check...
assert!(context.extra_code.contains(&accel.to_wgsl_string()));
}
}