authoravatarclover caruso<git@paperclover.net>2026-11-30 21:20:18-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 21:26:34-08:00
log32cbfb85162699b92240dff7e0f5253f861c4ea3
treee55bbc7a66961d2dcc49dd9168b578efc29f1853
parent0e60fad05e3b97d36ea194f3ff65775d12de6c00
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Split engine particles.rs and eval/mod.rs into submodules; fix output_cache VRAM double-counting


9 files changed, 3352 insertions(+), 3152 deletions(-)

crates/engine/src/eval/dispatch.rs created+428
...@@ -0,0 +1,428 @@
1//! GPU texture allocation, compute shader dispatch, readback, and viewer upload helpers.
2
3use std::cell::RefCell;
4use std::time::Instant;
5
6use bytemuck::{Pod, Zeroable};
7use model::BitDepth;
8
9use crate::cache::{CachedTexture, EvalStats};
10
11use super::registry::{ShaderOp, ShaderRegistry};
12use super::{DisplaySettings, Engine};
13
14#[repr(C)]
15#[derive(Clone, Copy, Pod, Zeroable)]
16pub(super) struct UniformParams {
17 pub(super) p: [[f32; 4]; 16],
18}
19
20impl Default for UniformParams {
21 fn default() -> Self {
22 Self { p: [[0.0; 4]; 16] }
23 }
24}
25
26impl Engine {
27 pub(super) fn alloc_tex(&self, size: [u32; 2], depth: BitDepth, content_hash: u64) -> CachedTexture {
28 self.alloc_tex_dod(size, [0, 0], size, depth, content_hash)
29 }
30
31 pub(super) fn alloc_tex_like(
32 &self,
33 src: &CachedTexture,
34 depth: BitDepth,
35 content_hash: u64,
36 ) -> CachedTexture {
37 let mut t = self.alloc_tex_dod(src.size, src.origin, src.canvas_size, depth, content_hash);
38 t.tex_scale = src.tex_scale;
39 t
40 }
41
42 pub(super) fn crop_to_canvas(&self, enc: &mut wgpu::CommandEncoder, tex: CachedTexture) -> CachedTexture {
43 if !tex.has_dod() {
44 return tex;
45 }
46 let mut cropped = self.alloc_tex(tex.canvas_size, tex.depth, tex.content_hash ^ 0xD0D0);
47 cropped.tex_scale = tex.tex_scale;
48 let mut params = UniformParams::default();
49 params.p[0] = [1.0, 1.0, 0.0, 0.0];
50 params.p[4] = [
51 tex.origin[0] as f32,
52 tex.origin[1] as f32,
53 tex.canvas_size[0] as f32,
54 tex.canvas_size[1] as f32,
55 ];
56 self.dispatch_op(
57 enc,
58 ShaderOp::DisplayBlit,
59 &tex.view,
60 &self.dummy.view,
61 &self.dummy.view,
62 &cropped,
63 &params,
64 );
65 cropped
66 }
67
68 pub(super) fn alloc_tex_dod(
69 &self,
70 size: [u32; 2],
71 origin: [i32; 2],
72 canvas_size: [u32; 2],
73 depth: BitDepth,
74 content_hash: u64,
75 ) -> CachedTexture {
76 let d = self.effective_depth(depth);
77 let fmt = self.texture_format_for(d);
78 self.cache
79 .acquire_texture_dod_fmt(&self.device, size, origin, canvas_size, d, fmt, content_hash)
80 }
81
82 pub(super) fn pipelines_for(&self, depth: BitDepth) -> &RefCell<ShaderRegistry> {
83 match depth {
84 BitDepth::Int8 => &self.pipelines,
85 BitDepth::Int16 => self.pipelines_int16.get_or_init(|| {
86 RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba16Float, false))
87 }),
88 BitDepth::Float16 => self.pipelines_f16.get_or_init(|| {
89 RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba16Float, true))
90 }),
91 BitDepth::Float32 => {
92 if self.supports_f32_filter {
93 self.pipelines_f32.get_or_init(|| {
94 RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba32Float, true))
95 })
96 } else {
97 self.pipelines_f16.get_or_init(|| {
98 RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba16Float, true))
99 })
100 }
101 }
102 }
103 }
104
105 /// Uploads a cached `RamFrame` directly into a viewer `wgpu::Texture` with full
106 /// `DisplaySettings` (exposure, gamma, channel isolate, zoom/pan) without evaluating the DAG.
107 pub fn render_ram_frame_into_viewer(
108 &self,
109 frame: &crate::ram_cache::RamFrame,
110 dst_texture: &wgpu::Texture,
111 display: DisplaySettings,
112 ) -> EvalStats {
113 let t0 = Instant::now();
114 let mut upload_slot = self.ram_upload_tex.borrow_mut();
115 let needs_alloc = upload_slot
116 .as_ref()
117 .is_none_or(|t| t.size != frame.size);
118 if needs_alloc {
119 let max_dim = self.device.limits().max_texture_dimension_2d.max(1);
120 let (clamped, _) = crate::cache::clamp_dims_to_limit(frame.size[0], frame.size[1], max_dim);
121 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
122 label: Some("ram-viewer-upload"),
123 size: wgpu::Extent3d {
124 width: clamped[0],
125 height: clamped[1],
126 depth_or_array_layers: 1,
127 },
128 mip_level_count: 1,
129 sample_count: 1,
130 dimension: wgpu::TextureDimension::D2,
131 format: wgpu::TextureFormat::Rgba8Unorm,
132 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
133 view_formats: &[],
134 });
135 *upload_slot = Some(CachedTexture::from_texture(tex, clamped, 0));
136 }
137 let src = upload_slot.as_ref().expect("ram upload texture initialized");
138 if src.size == frame.size {
139 self.queue.write_texture(
140 src.texture.as_image_copy(),
141 &frame.rgba,
142 wgpu::TexelCopyBufferLayout {
143 offset: 0,
144 bytes_per_row: Some(frame.size[0] * 4),
145 rows_per_image: Some(frame.size[1]),
146 },
147 wgpu::Extent3d {
148 width: frame.size[0],
149 height: frame.size[1],
150 depth_or_array_layers: 1,
151 },
152 );
153 }
154 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
155 label: Some("comp-ram-viewer-blit"),
156 });
157 let dst_size = [dst_texture.width(), dst_texture.height()];
158 let dst_view = dst_texture.create_view(&wgpu::TextureViewDescriptor::default());
159 let mut params = UniformParams::default();
160 params.p[0] = [
161 2.0_f32.powf(display.exposure),
162 display.gamma,
163 display.channel as f32,
164 if display.checker_bg { 1.0 } else { 0.0 },
165 ];
166 params.p[1] = display.uv_rect;
167 params.p[2] = [if display.smooth_resize { 0.0 } else { 1.0 }, 0.0, 0.0, 0.0];
168 self.dispatch_to_view(
169 &mut encoder,
170 ShaderOp::DisplayBlit,
171 &src.view,
172 &self.dummy.view,
173 &self.dummy.view,
174 &dst_view,
175 dst_size,
176 &params,
177 );
178 self.queue.submit(Some(encoder.finish()));
179
180 EvalStats {
181 eval_ms: t0.elapsed().as_secs_f64() * 1000.0,
182 cache_hits: 1,
183 cached_entries: self.cache.entry_count(),
184 cached_vram_mb: self.vram_mb(),
185 media_entries: self.media.entry_count(),
186 media_mb: self.media.total_mb(),
187 ..EvalStats::default()
188 }
189 }
190
191 /// Reads back a `CachedTexture` to CPU RGBA8 bytes (for CLI `render-check` / PNG export).
192 /// Automatically converts Float16 / Float32 working textures to clamped RGBA8 on GPU before readback.
193 pub fn readback_rgba(&self, tex: &CachedTexture) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
194 let [w, h] = tex.size;
195 let bpp = 4u32;
196 let unpadded_bpr = w * bpp;
197 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
198 let padded_bpr = unpadded_bpr.div_ceil(align) * align;
199 let buf = self.device.create_buffer(&wgpu::BufferDescriptor {
200 label: Some("readback"),
201 size: u64::from(padded_bpr) * u64::from(h),
202 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
203 mapped_at_creation: false,
204 });
205 let mut enc = self.device.create_command_encoder(&Default::default());
206 let converted;
207 let src_tex = if tex.format != wgpu::TextureFormat::Rgba8Unorm {
208 converted = create_texture(&self.device, tex.size, 0);
209 let mut params = UniformParams::default();
210 params.p[0] = [1.0, 1.0, 0.0, 0.0];
211 self.dispatch_to_view(
212 &mut enc,
213 ShaderOp::DisplayBlit,
214 &tex.view,
215 &self.dummy.view,
216 &self.dummy.view,
217 &converted.view,
218 converted.size,
219 &params,
220 );
221 &converted
222 } else {
223 tex
224 };
225 enc.copy_texture_to_buffer(
226 src_tex.texture.as_image_copy(),
227 wgpu::TexelCopyBufferInfo {
228 buffer: &buf,
229 layout: wgpu::TexelCopyBufferLayout {
230 offset: 0,
231 bytes_per_row: Some(padded_bpr),
232 rows_per_image: Some(h),
233 },
234 },
235 wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
236 );
237 self.queue.submit(Some(enc.finish()));
238
239 let slice = buf.slice(..);
240 let (tx, rx) = std::sync::mpsc::channel();
241 slice.map_async(wgpu::MapMode::Read, move |res| {
242 let _ = tx.send(res);
243 });
244 self.device.poll(wgpu::PollType::Wait {
245 submission_index: None,
246 timeout: Some(std::time::Duration::from_secs(10)),
247 })?;
248 rx.recv()??;
249 let data = slice.get_mapped_range()?;
250 let mut out = Vec::with_capacity((w * h * 4) as usize);
251 for row in 0..h as usize {
252 let start = row * padded_bpr as usize;
253 out.extend_from_slice(&data[start..start + unpadded_bpr as usize]);
254 }
255 drop(data);
256 buf.unmap();
257 Ok(out)
258 }
259
260 #[allow(clippy::too_many_arguments)]
261 pub(super) fn dispatch_op(
262 &self,
263 enc: &mut wgpu::CommandEncoder,
264 op: ShaderOp,
265 src_a: &wgpu::TextureView,
266 src_b: &wgpu::TextureView,
267 mask: &wgpu::TextureView,
268 dst: &CachedTexture,
269 params: &UniformParams,
270 ) {
271 let reg_cell = self.pipelines_for(dst.depth);
272 reg_cell.borrow_mut().ensure_pipeline(&self.device, op);
273 let reg = reg_cell.borrow();
274 let ubuf = self.device.create_buffer(&wgpu::BufferDescriptor {
275 label: Some("op-params"),
276 size: std::mem::size_of::<UniformParams>() as u64,
277 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
278 mapped_at_creation: false,
279 });
280 self.queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(params));
281
282 let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
283 label: Some("op-bg"),
284 layout: &reg.bgl,
285 entries: &[
286 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) },
287 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) },
288 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) },
289 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&reg.sampler) },
290 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst.view) },
291 wgpu::BindGroupEntry { binding: 5, resource: ubuf.as_entire_binding() },
292 ],
293 });
294
295 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
296 label: Some("comp-op"),
297 timestamp_writes: None,
298 });
299 pass.set_pipeline(&reg.pipelines[&op]);
300 pass.set_bind_group(0, &bg, &[]);
301 pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1);
302 }
303
304 #[allow(clippy::too_many_arguments)]
305 pub(super) fn dispatch_to_view(
306 &self,
307 enc: &mut wgpu::CommandEncoder,
308 op: ShaderOp,
309 src_a: &wgpu::TextureView,
310 src_b: &wgpu::TextureView,
311 mask: &wgpu::TextureView,
312 dst_view: &wgpu::TextureView,
313 dst_size: [u32; 2],
314 params: &UniformParams,
315 ) {
316 self.pipelines.borrow_mut().ensure_pipeline(&self.device, op);
317 let reg = self.pipelines.borrow();
318 let ubuf = self.device.create_buffer(&wgpu::BufferDescriptor {
319 label: Some("op-params"),
320 size: std::mem::size_of::<UniformParams>() as u64,
321 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
322 mapped_at_creation: false,
323 });
324 self.queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(params));
325
326 let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
327 label: Some("op-bg"),
328 layout: &reg.bgl,
329 entries: &[
330 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) },
331 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) },
332 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) },
333 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&reg.sampler) },
334 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(dst_view) },
335 wgpu::BindGroupEntry { binding: 5, resource: ubuf.as_entire_binding() },
336 ],
337 });
338
339 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
340 label: Some("comp-op"),
341 timestamp_writes: None,
342 });
343 pass.set_pipeline(&reg.pipelines[&op]);
344 pass.set_bind_group(0, &bg, &[]);
345 pass.dispatch_workgroups(dst_size[0].div_ceil(8), dst_size[1].div_ceil(8), 1);
346 }
347}
348
349pub fn create_texture(device: &wgpu::Device, size: [u32; 2], content_hash: u64) -> CachedTexture {
350 create_texture_dod(device, size, [0, 0], size, content_hash)
351}
352
353pub fn create_texture_dod(
354 device: &wgpu::Device,
355 size: [u32; 2],
356 origin: [i32; 2],
357 canvas_size: [u32; 2],
358 content_hash: u64,
359) -> CachedTexture {
360 create_texture_dod_fmt(
361 device,
362 size,
363 origin,
364 canvas_size,
365 BitDepth::Int8,
366 wgpu::TextureFormat::Rgba8Unorm,
367 content_hash,
368 )
369}
370
371pub fn create_texture_dod_fmt(
372 device: &wgpu::Device,
373 size: [u32; 2],
374 origin: [i32; 2],
375 canvas_size: [u32; 2],
376 depth: BitDepth,
377 format: wgpu::TextureFormat,
378 content_hash: u64,
379) -> CachedTexture {
380 let max_dim = device.limits().max_texture_dimension_2d.max(1);
381 let (clamped, tex_scale) = crate::cache::clamp_dims_to_limit(size[0], size[1], max_dim);
382 let eff_origin = if tex_scale < 1.0 {
383 [
384 (origin[0] as f32 * tex_scale).round() as i32,
385 (origin[1] as f32 * tex_scale).round() as i32,
386 ]
387 } else {
388 origin
389 };
390 let eff_canvas = if size == canvas_size {
391 clamped
392 } else if tex_scale < 1.0 {
393 [
394 ((canvas_size[0].max(1) as f32 * tex_scale).round() as u32).max(1),
395 ((canvas_size[1].max(1) as f32 * tex_scale).round() as u32).max(1),
396 ]
397 } else {
398 [canvas_size[0].max(1), canvas_size[1].max(1)]
399 };
400 let tex = device.create_texture(&wgpu::TextureDescriptor {
401 label: Some("comp-tex"),
402 size: wgpu::Extent3d {
403 width: clamped[0],
404 height: clamped[1],
405 depth_or_array_layers: 1,
406 },
407 mip_level_count: 1,
408 sample_count: 1,
409 dimension: wgpu::TextureDimension::D2,
410 format,
411 usage: wgpu::TextureUsages::TEXTURE_BINDING
412 | wgpu::TextureUsages::STORAGE_BINDING
413 | wgpu::TextureUsages::COPY_SRC
414 | wgpu::TextureUsages::COPY_DST
415 | wgpu::TextureUsages::RENDER_ATTACHMENT,
416 view_formats: &[],
417 });
418 let mut cached = CachedTexture::from_texture_dod_depth(
419 tex,
420 clamped,
421 eff_origin,
422 eff_canvas,
423 depth,
424 content_hash,
425 );
426 cached.tex_scale = tex_scale;
427 cached
428}
crates/engine/src/eval/mod.rs+56-830
...@@ -3,7 +3,6 @@...@@ -3,7 +3,6 @@
33
4use crate::cache::{CacheMode, CachedTexture, EvalStats, NodeCache};4use crate::cache::{CacheMode, CachedTexture, EvalStats, NodeCache};
5use crate::media::{MediaCache, TextPlusParams, rasterize_polyline_mask, rasterize_text_plus};5use crate::media::{MediaCache, TextPlusParams, rasterize_polyline_mask, rasterize_text_plus};
6use bytemuck::{Pod, Zeroable};
7use model::{BitDepth, Comp, ExprEngine, Node, NodeId, default_main_input_port};6use model::{BitDepth, Comp, ExprEngine, Node, NodeId, default_main_input_port};
8use std::cell::{OnceCell, RefCell};7use std::cell::{OnceCell, RefCell};
9use std::collections::{HashMap, HashSet};8use std::collections::{HashMap, HashSet};
...@@ -22,19 +21,14 @@ mod paint;...@@ -22,19 +21,14 @@ mod paint;
22mod shapes;21mod shapes;
23mod warps;22mod warps;
24mod text_3d;23mod text_3d;
24mod registry;
25mod dispatch;
26mod output_cache;
2527
2628use dispatch::UniformParams;
27#[repr(C)]29pub use dispatch::{create_texture, create_texture_dod, create_texture_dod_fmt};
28#[derive(Clone, Copy, Pod, Zeroable)]30use output_cache::OutputCache;
29struct UniformParams {31use registry::{ShaderOp, ShaderRegistry};
30 p: [[f32; 4]; 16],
31}
32
33impl Default for UniformParams {
34 fn default() -> Self {
35 Self { p: [[0.0; 4]; 16] }
36 }
37}
3832
39#[derive(Clone, Copy, Debug, PartialEq)]33#[derive(Clone, Copy, Debug, PartialEq)]
40pub struct DisplaySettings {34pub struct DisplaySettings {
...@@ -62,340 +56,6 @@ impl Default for DisplaySettings {...@@ -62,340 +56,6 @@ impl Default for DisplaySettings {
62 }56 }
63}57}
6458
65#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
66enum ShaderDomain {
67 Composite,
68 Color,
69 BlurGlow,
70 Transform,
71 Masks,
72 KeyersGen,
73 ArchiveFx,
74}
75
76impl ShaderDomain {
77 fn source(self) -> &'static str {
78 match self {
79 Self::Composite => include_str!("../shaders/composite.wgsl"),
80 Self::Color => include_str!("../shaders/color.wgsl"),
81 Self::BlurGlow => include_str!("../shaders/blur_glow.wgsl"),
82 Self::Transform => include_str!("../shaders/transform.wgsl"),
83 Self::Masks => include_str!("../shaders/masks.wgsl"),
84 Self::KeyersGen => include_str!("../shaders/keyers_gen.wgsl"),
85 Self::ArchiveFx => include_str!("../shaders/archive_fx.wgsl"),
86 }
87 }
88
89 fn label(self) -> &'static str {
90 match self {
91 Self::Composite => "compositor-shaders-composite",
92 Self::Color => "compositor-shaders-color",
93 Self::BlurGlow => "compositor-shaders-blur-glow",
94 Self::Transform => "compositor-shaders-transform",
95 Self::Masks => "compositor-shaders-masks",
96 Self::KeyersGen => "compositor-shaders-keyers-gen",
97 Self::ArchiveFx => "compositor-shaders-archive-fx",
98 }
99 }
100}
101
102#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
103enum ShaderOp {
104 Bg,
105 Merge,
106 Transform,
107 Bc,
108 Cc,
109 ColorGain,
110 LumaKey,
111 Blur,
112 DirBlur,
113 FastNoise,
114 Displace,
115 MaskShape,
116 MaskCombine,
117 MaskApply,
118 BitmapMask,
119 Colorize,
120 ColorCurves,
121 XfChroma,
122 GamutConvert,
123 VariBlur,
124 OutlineTint,
125 OutlineComposite,
126 #[allow(dead_code)]
127 CustomWave,
128 Crop,
129 GlowAdd,
130 XGlowPrep,
131 XGlowAccum,
132 DisplayBlit,
133 Invert,
134 ChannelBoolean,
135 Filter,
136 HueCurves,
137 UltraKeyer,
138 Dissolve,
139 Homography,
140 ShadowComp,
141 Plasma,
142 FilmGrain,
143 SetDomain,
144 ChangeDepth,
145 Vortex,
146 KScope,
147 Drip,
148 Dent,
149 PerspectivePos,
150 DaySky,
151 GridWarp,
152}
153
154impl ShaderOp {
155 fn domain(self) -> ShaderDomain {
156 match self {
157 Self::Bg
158 | Self::Merge
159 | Self::DisplayBlit
160 | Self::ChannelBoolean
161 | Self::Dissolve
162 | Self::ShadowComp
163 | Self::SetDomain
164 | Self::ChangeDepth => ShaderDomain::Composite,
165
166 Self::Bc
167 | Self::Cc
168 | Self::ColorGain
169 | Self::Colorize
170 | Self::ColorCurves
171 | Self::GamutConvert
172 | Self::Invert
173 | Self::HueCurves => ShaderDomain::Color,
174
175 Self::Blur
176 | Self::DirBlur
177 | Self::VariBlur
178 | Self::GlowAdd
179 | Self::XGlowPrep
180 | Self::XGlowAccum
181 | Self::Filter
182 | Self::FilmGrain => ShaderDomain::BlurGlow,
183
184 Self::Transform
185 | Self::Displace
186 | Self::XfChroma
187 | Self::Crop
188 | Self::Homography
189 | Self::Vortex
190 | Self::KScope => ShaderDomain::Transform,
191
192 Self::MaskShape
193 | Self::MaskCombine
194 | Self::MaskApply
195 | Self::BitmapMask => ShaderDomain::Masks,
196
197 Self::LumaKey
198 | Self::FastNoise
199 | Self::OutlineTint
200 | Self::OutlineComposite
201 | Self::CustomWave
202 | Self::UltraKeyer
203 | Self::Plasma => ShaderDomain::KeyersGen,
204
205 Self::Drip | Self::Dent | Self::PerspectivePos | Self::DaySky | Self::GridWarp => {
206 ShaderDomain::ArchiveFx
207 }
208 }
209 }
210
211 fn entry_point(self) -> &'static str {
212 match self {
213 Self::Bg => "bg_op",
214 Self::Merge => "merge_op",
215 Self::Transform => "transform_op",
216 Self::Bc => "bc_op",
217 Self::Cc => "cc_op",
218 Self::ColorGain => "color_gain_op",
219 Self::LumaKey => "luma_key_op",
220 Self::Blur => "blur_op",
221 Self::DirBlur => "dir_blur_op",
222 Self::FastNoise => "fast_noise_op",
223 Self::Displace => "displace_op",
224 Self::MaskShape => "mask_shape_op",
225 Self::MaskCombine => "mask_combine_op",
226 Self::MaskApply => "mask_apply_op",
227 Self::BitmapMask => "bitmap_mask_op",
228 Self::Colorize => "colorize_op",
229 Self::ColorCurves => "color_curves_op",
230 Self::XfChroma => "xf_chroma_op",
231 Self::GamutConvert => "gamut_convert_op",
232 Self::VariBlur => "vari_blur_op",
233 Self::OutlineTint => "outline_tint",
234 Self::OutlineComposite => "outline_composite",
235 Self::CustomWave => "custom_wave_op",
236 Self::Crop => "crop_op",
237 Self::GlowAdd => "glow_add_op",
238 Self::XGlowPrep => "xglow_prep_op",
239 Self::XGlowAccum => "xglow_accum_op",
240 Self::DisplayBlit => "display_blit_op",
241 Self::Invert => "invert_op",
242 Self::ChannelBoolean => "channel_boolean_op",
243 Self::Filter => "filter_op",
244 Self::HueCurves => "hue_curves_op",
245 Self::UltraKeyer => "ultra_keyer_op",
246 Self::Dissolve => "dissolve_op",
247 Self::Homography => "homography_op",
248 Self::ShadowComp => "shadow_comp_op",
249 Self::Plasma => "plasma_op",
250 Self::FilmGrain => "film_grain_op",
251 Self::SetDomain => "set_domain_op",
252 Self::ChangeDepth => "change_depth_op",
253 Self::Vortex => "vortex_op",
254 Self::KScope => "kscope_op",
255 Self::Drip => "drip_op",
256 Self::Dent => "dent_op",
257 Self::PerspectivePos => "perspective_pos_op",
258 Self::DaySky => "day_sky_op",
259 Self::GridWarp => "grid_warp_op",
260 }
261 }
262}
263
264const COMMON_WGSL: &str = include_str!("../shaders/common.wgsl");
265
266struct ShaderRegistry {
267 format: wgpu::TextureFormat,
268 hdr_float: bool,
269 bgl: wgpu::BindGroupLayout,
270 pl: wgpu::PipelineLayout,
271 sampler: wgpu::Sampler,
272 modules: HashMap<ShaderDomain, wgpu::ShaderModule>,
273 pipelines: HashMap<ShaderOp, wgpu::ComputePipeline>,
274}
275
276impl ShaderRegistry {
277 fn new(device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) -> Self {
278 let tex_entry = |binding| wgpu::BindGroupLayoutEntry {
279 binding,
280 visibility: wgpu::ShaderStages::COMPUTE,
281 ty: wgpu::BindingType::Texture {
282 sample_type: wgpu::TextureSampleType::Float { filterable: true },
283 view_dimension: wgpu::TextureViewDimension::D2,
284 multisampled: false,
285 },
286 count: None,
287 };
288 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
289 label: Some("compositor-bgl"),
290 entries: &[
291 tex_entry(0),
292 tex_entry(1),
293 tex_entry(2),
294 wgpu::BindGroupLayoutEntry {
295 binding: 3,
296 visibility: wgpu::ShaderStages::COMPUTE,
297 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
298 count: None,
299 },
300 wgpu::BindGroupLayoutEntry {
301 binding: 4,
302 visibility: wgpu::ShaderStages::COMPUTE,
303 ty: wgpu::BindingType::StorageTexture {
304 access: wgpu::StorageTextureAccess::WriteOnly,
305 format,
306 view_dimension: wgpu::TextureViewDimension::D2,
307 },
308 count: None,
309 },
310 wgpu::BindGroupLayoutEntry {
311 binding: 5,
312 visibility: wgpu::ShaderStages::COMPUTE,
313 ty: wgpu::BindingType::Buffer {
314 ty: wgpu::BufferBindingType::Uniform,
315 has_dynamic_offset: false,
316 min_binding_size: None,
317 },
318 count: None,
319 },
320 ],
321 });
322
323 let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
324 label: Some("compositor-pl"),
325 bind_group_layouts: &[Some(&bgl)],
326 immediate_size: 0,
327 });
328
329 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
330 label: Some("compositor-linear"),
331 address_mode_u: wgpu::AddressMode::ClampToEdge,
332 address_mode_v: wgpu::AddressMode::ClampToEdge,
333 mag_filter: wgpu::FilterMode::Linear,
334 min_filter: wgpu::FilterMode::Linear,
335 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
336 ..Default::default()
337 });
338
339 Self {
340 format,
341 hdr_float,
342 bgl,
343 pl,
344 sampler,
345 modules: HashMap::new(),
346 pipelines: HashMap::new(),
347 }
348 }
349
350 fn ensure_pipeline(&mut self, device: &wgpu::Device, op: ShaderOp) {
351 if self.pipelines.contains_key(&op) {
352 return;
353 }
354 let domain = op.domain();
355 let format = self.format;
356 let hdr_float = self.hdr_float;
357 let module = self.modules.entry(domain).or_insert_with(|| {
358 let domain_src = domain.source();
359 let mut src = String::with_capacity(COMMON_WGSL.len() + domain_src.len() + 1);
360 src.push_str(COMMON_WGSL);
361 src.push('\n');
362 src.push_str(domain_src);
363 let storage_fmt = match format {
364 wgpu::TextureFormat::Rgba16Float => "rgba16float",
365 wgpu::TextureFormat::Rgba32Float => "rgba32float",
366 _ => "rgba8unorm",
367 };
368 if storage_fmt != "rgba8unorm" {
369 src = src.replace(
370 "texture_storage_2d<rgba8unorm, write>",
371 &format!("texture_storage_2d<{storage_fmt}, write>"),
372 );
373 }
374 if hdr_float {
375 src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;");
376 }
377 device.create_shader_module(wgpu::ShaderModuleDescriptor {
378 label: Some(domain.label()),
379 source: wgpu::ShaderSource::Wgsl(src.into()),
380 })
381 });
382
383 let entry = op.entry_point();
384 let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
385 label: Some(entry),
386 layout: Some(&self.pl),
387 module,
388 entry_point: Some(entry),
389 compilation_options: Default::default(),
390 cache: None,
391 });
392 self.pipelines.insert(op, pipeline);
393 }
394}
395
396const MAX_OUTPUT_CACHE_BYTES: u64 = 128 * 1024 * 1024;
397const MAX_OUTPUT_CACHE_ENTRIES: usize = 64;
398
399pub struct Engine {59pub struct Engine {
400 device: wgpu::Device,60 device: wgpu::Device,
401 queue: wgpu::Queue,61 queue: wgpu::Queue,
...@@ -417,9 +77,7 @@ pub struct Engine {...@@ -417,9 +77,7 @@ pub struct Engine {
417 pub expr: ExprEngine,77 pub expr: ExprEngine,
418 /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame.78 /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame.
419 frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>,79 frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>,
420 /// Bounded LRU of recent final output textures capped by byte budget (`min(vram_budget / 4, 128 MiB)`),80 output_cache: OutputCache,
421 /// always keeping at least the most recent frame for `<0.1ms` warm hits during pan/zoom/exposure/scrubbing.
422 output_cache: std::collections::VecDeque<(u64, CachedTexture, Vec<String>)>,
423 /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default81 /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default
424 /// to matching the dimensions & aspect ratio of the node they mask!).82 /// to matching the dimensions & aspect ratio of the node they mask!).
425 mask_target_size: Option<[u32; 2]>,83 mask_target_size: Option<[u32; 2]>,
...@@ -468,7 +126,7 @@ impl Engine {...@@ -468,7 +126,7 @@ impl Engine {
468 media: MediaCache::new(512),126 media: MediaCache::new(512),
469 expr: ExprEngine::new(),127 expr: ExprEngine::new(),
470 frame_memo: HashMap::new(),128 frame_memo: HashMap::new(),
471 output_cache: std::collections::VecDeque::new(),129 output_cache: OutputCache::new(),
472 mask_target_size: None,130 mask_target_size: None,
473 proxy_scale: 1,131 proxy_scale: 1,
474 use_proxy_clips: false,132 use_proxy_clips: false,
...@@ -541,70 +199,6 @@ impl Engine {...@@ -541,70 +199,6 @@ impl Engine {
541 }199 }
542 }200 }
543201
544 fn alloc_tex(&self, size: [u32; 2], depth: BitDepth, content_hash: u64) -> CachedTexture {
545 self.alloc_tex_dod(size, [0, 0], size, depth, content_hash)
546 }
547
548 fn alloc_tex_like(&self, src: &CachedTexture, depth: BitDepth, content_hash: u64) -> CachedTexture {
549 let mut t = self.alloc_tex_dod(src.size, src.origin, src.canvas_size, depth, content_hash);
550 t.tex_scale = src.tex_scale;
551 t
552 }
553
554 fn crop_to_canvas(&self, enc: &mut wgpu::CommandEncoder, tex: CachedTexture) -> CachedTexture {
555 if !tex.has_dod() {
556 return tex;
557 }
558 let mut cropped = self.alloc_tex(tex.canvas_size, tex.depth, tex.content_hash ^ 0xD0D0);
559 cropped.tex_scale = tex.tex_scale;
560 let mut params = UniformParams::default();
561 params.p[0] = [1.0, 1.0, 0.0, 0.0];
562 params.p[4] = [
563 tex.origin[0] as f32,
564 tex.origin[1] as f32,
565 tex.canvas_size[0] as f32,
566 tex.canvas_size[1] as f32,
567 ];
568 self.dispatch_op(enc, ShaderOp::DisplayBlit, &tex.view, &self.dummy.view, &self.dummy.view, &cropped, &params);
569 cropped
570 }
571
572 fn alloc_tex_dod(
573 &self,
574 size: [u32; 2],
575 origin: [i32; 2],
576 canvas_size: [u32; 2],
577 depth: BitDepth,
578 content_hash: u64,
579 ) -> CachedTexture {
580 let d = self.effective_depth(depth);
581 let fmt = self.texture_format_for(d);
582 self.cache.acquire_texture_dod_fmt(&self.device, size, origin, canvas_size, d, fmt, content_hash)
583 }
584
585 fn pipelines_for(&self, depth: BitDepth) -> &RefCell<ShaderRegistry> {
586 match depth {
587 BitDepth::Int8 => &self.pipelines,
588 BitDepth::Int16 => self.pipelines_int16.get_or_init(|| {
589 RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba16Float, false))
590 }),
591 BitDepth::Float16 => self.pipelines_f16.get_or_init(|| {
592 RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba16Float, true))
593 }),
594 BitDepth::Float32 => {
595 if self.supports_f32_filter {
596 self.pipelines_f32.get_or_init(|| {
597 RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba32Float, true))
598 })
599 } else {
600 self.pipelines_f16.get_or_init(|| {
601 RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba16Float, true))
602 })
603 }
604 }
605 }
606 }
607
608 pub fn device(&self) -> &wgpu::Device {202 pub fn device(&self) -> &wgpu::Device {
609 &self.device203 &self.device
610 }204 }
...@@ -625,143 +219,10 @@ impl Engine {...@@ -625,143 +219,10 @@ impl Engine {
625 self.cache.mode = mode;219 self.cache.mode = mode;
626 }220 }
627221
628 fn output_cache_budget_bytes(&self) -> u64 {
629 if self.vram_budget_bytes < 64 * 1024 * 1024 {
630 0
631 } else {
632 (self.vram_budget_bytes / 4).min(MAX_OUTPUT_CACHE_BYTES)
633 }
634 }
635
636 /// Total GPU bytes held by `output_cache`.
637 pub fn output_cache_bytes(&self) -> u64 {
638 self.output_cache.iter().map(|(_, tex, _)| tex.bytes).sum()
639 }
640
641 /// Total resident GPU VRAM bytes across `NodeCache` (live + pooled) and `output_cache`.
642 pub fn vram_bytes(&self) -> u64 {
643 self.cache.total_vram_bytes().saturating_add(self.output_cache_bytes())
644 }
645
646 pub fn vram_mb(&self) -> f64 {
647 self.vram_bytes() as f64 / (1024.0 * 1024.0)
648 }
649
650 fn sync_node_cache_budget(&mut self) {
651 let remaining_bytes = self.vram_budget_bytes.saturating_sub(self.output_cache_bytes());
652 let remaining_mb = remaining_bytes / (1024 * 1024);
653 if self.cache.budget_bytes != remaining_mb.saturating_mul(1024 * 1024) {
654 self.cache.set_budget_mb(remaining_mb);
655 }
656 }
657
658 pub fn set_vram_budget_mb(&mut self, budget_mb: u64) {
659 self.vram_budget_bytes = budget_mb.saturating_mul(1024 * 1024);
660 let cap = self.output_cache_budget_bytes();
661 if cap == 0 {
662 self.output_cache.clear();
663 } else {
664 while self.output_cache.len() > 1 && self.output_cache_bytes() > cap {
665 self.output_cache.pop_front();
666 }
667 }
668 self.sync_node_cache_budget();
669 }
670
671 pub fn vram_budget_mb(&self) -> u64 {
672 self.vram_budget_bytes / (1024 * 1024)
673 }
674
675 pub fn set_media_budget_mb(&mut self, budget_mb: u64) {222 pub fn set_media_budget_mb(&mut self, budget_mb: u64) {
676 self.media.set_budget_mb(budget_mb);223 self.media.set_budget_mb(budget_mb);
677 }224 }
678225
679 /// Uploads a cached `RamFrame` directly into a viewer `wgpu::Texture` with full
680 /// `DisplaySettings` (exposure, gamma, channel isolate, zoom/pan) without evaluating the DAG.
681 pub fn render_ram_frame_into_viewer(
682 &self,
683 frame: &crate::ram_cache::RamFrame,
684 dst_texture: &wgpu::Texture,
685 display: DisplaySettings,
686 ) -> EvalStats {
687 let t0 = Instant::now();
688 let mut upload_slot = self.ram_upload_tex.borrow_mut();
689 let needs_alloc = upload_slot
690 .as_ref()
691 .is_none_or(|t| t.size != frame.size);
692 if needs_alloc {
693 let max_dim = self.device.limits().max_texture_dimension_2d.max(1);
694 let (clamped, _) = crate::cache::clamp_dims_to_limit(frame.size[0], frame.size[1], max_dim);
695 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
696 label: Some("ram-viewer-upload"),
697 size: wgpu::Extent3d {
698 width: clamped[0],
699 height: clamped[1],
700 depth_or_array_layers: 1,
701 },
702 mip_level_count: 1,
703 sample_count: 1,
704 dimension: wgpu::TextureDimension::D2,
705 format: wgpu::TextureFormat::Rgba8Unorm,
706 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
707 view_formats: &[],
708 });
709 *upload_slot = Some(CachedTexture::from_texture(tex, clamped, 0));
710 }
711 let src = upload_slot.as_ref().expect("ram upload texture initialized");
712 if src.size == frame.size {
713 self.queue.write_texture(
714 src.texture.as_image_copy(),
715 &frame.rgba,
716 wgpu::TexelCopyBufferLayout {
717 offset: 0,
718 bytes_per_row: Some(frame.size[0] * 4),
719 rows_per_image: Some(frame.size[1]),
720 },
721 wgpu::Extent3d {
722 width: frame.size[0],
723 height: frame.size[1],
724 depth_or_array_layers: 1,
725 },
726 );
727 }
728 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
729 label: Some("comp-ram-viewer-blit"),
730 });
731 let dst_size = [dst_texture.width(), dst_texture.height()];
732 let dst_view = dst_texture.create_view(&wgpu::TextureViewDescriptor::default());
733 let mut params = UniformParams::default();
734 params.p[0] = [
735 2.0_f32.powf(display.exposure),
736 display.gamma,
737 display.channel as f32,
738 if display.checker_bg { 1.0 } else { 0.0 },
739 ];
740 params.p[1] = display.uv_rect;
741 params.p[2] = [if display.smooth_resize { 0.0 } else { 1.0 }, 0.0, 0.0, 0.0];
742 self.dispatch_to_view(
743 &mut encoder,
744 ShaderOp::DisplayBlit,
745 &src.view,
746 &self.dummy.view,
747 &self.dummy.view,
748 &dst_view,
749 dst_size,
750 &params,
751 );
752 self.queue.submit(Some(encoder.finish()));
753
754 EvalStats {
755 eval_ms: t0.elapsed().as_secs_f64() * 1000.0,
756 cache_hits: 1,
757 cached_entries: self.cache.entry_count(),
758 cached_vram_mb: self.vram_mb(),
759 media_entries: self.media.entry_count(),
760 media_mb: self.media.total_mb(),
761 ..EvalStats::default()
762 }
763 }
764
765 pub fn bust_all_caches(&mut self) {226 pub fn bust_all_caches(&mut self) {
766 self.output_cache.clear();227 self.output_cache.clear();
767 self.sync_node_cache_budget();228 self.sync_node_cache_budget();
...@@ -793,49 +254,6 @@ impl Engine {...@@ -793,49 +254,6 @@ impl Engine {
793 self.cache.bust_subtree(node)254 self.cache.bust_subtree(node)
794 }255 }
795256
796 fn output_cache_key(&self, comp: &Comp, target: NodeId, time: f64) -> u64 {
797 let mut h = DefaultHasher::new();
798 self.cache.gpu_salt.hash(&mut h);
799 comp.name.hash(&mut h);
800 comp.path.hash(&mut h);
801 comp.nodes.len().hash(&mut h);
802 comp.revision.hash(&mut h);
803 target.hash(&mut h);
804 time.to_bits().hash(&mut h);
805 self.proxy_scale.hash(&mut h);
806 self.hiq.hash(&mut h);
807 self.use_proxy_clips.hash(&mut h);
808 h.finish()
809 }
810
811 fn output_cache_get(&mut self, key: u64) -> Option<(CachedTexture, Vec<String>)> {
812 if self.cache.mode == CacheMode::Bypass {
813 return None;
814 }
815 let pos = self.output_cache.iter().position(|(k, _, _)| *k == key)?;
816 let entry = self.output_cache.remove(pos)?;
817 let res = (entry.1.clone(), entry.2.clone());
818 self.output_cache.push_back(entry);
819 Some(res)
820 }
821
822 fn output_cache_insert(&mut self, key: u64, tex: CachedTexture, unsupported: Vec<String>) {
823 let cap = self.output_cache_budget_bytes();
824 if self.cache.mode == CacheMode::Bypass || cap == 0 {
825 return;
826 }
827 if let Some(pos) = self.output_cache.iter().position(|(k, _, _)| *k == key) {
828 self.output_cache.remove(pos);
829 }
830 self.output_cache.push_back((key, tex, unsupported));
831 while self.output_cache.len() > 1
832 && (self.output_cache_bytes() > cap || self.output_cache.len() > MAX_OUTPUT_CACHE_ENTRIES)
833 {
834 self.output_cache.pop_front();
835 }
836 self.sync_node_cache_budget();
837 }
838
839 /// Evaluates `target` node at `time` and returns its GPU texture + telemetry.257 /// Evaluates `target` node at `time` and returns its GPU texture + telemetry.
840 pub fn evaluate(258 pub fn evaluate(
841 &mut self,259 &mut self,
...@@ -954,75 +372,6 @@ impl Engine {...@@ -954,75 +372,6 @@ impl Engine {
954 stats372 stats
955 }373 }
956374
957 /// Reads back a `CachedTexture` to CPU RGBA8 bytes (for CLI `render-check` / PNG export).
958 /// Automatically converts Float16 / Float32 working textures to clamped RGBA8 on GPU before readback.
959 pub fn readback_rgba(&self, tex: &CachedTexture) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
960 let [w, h] = tex.size;
961 let bpp = 4u32;
962 let unpadded_bpr = w * bpp;
963 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
964 let padded_bpr = unpadded_bpr.div_ceil(align) * align;
965 let buf = self.device.create_buffer(&wgpu::BufferDescriptor {
966 label: Some("readback"),
967 size: u64::from(padded_bpr) * u64::from(h),
968 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
969 mapped_at_creation: false,
970 });
971 let mut enc = self.device.create_command_encoder(&Default::default());
972 let converted;
973 let src_tex = if tex.format != wgpu::TextureFormat::Rgba8Unorm {
974 converted = create_texture(&self.device, tex.size, 0);
975 let mut params = UniformParams::default();
976 params.p[0] = [1.0, 1.0, 0.0, 0.0];
977 self.dispatch_to_view(
978 &mut enc,
979 ShaderOp::DisplayBlit,
980 &tex.view,
981 &self.dummy.view,
982 &self.dummy.view,
983 &converted.view,
984 converted.size,
985 &params,
986 );
987 &converted
988 } else {
989 tex
990 };
991 enc.copy_texture_to_buffer(
992 src_tex.texture.as_image_copy(),
993 wgpu::TexelCopyBufferInfo {
994 buffer: &buf,
995 layout: wgpu::TexelCopyBufferLayout {
996 offset: 0,
997 bytes_per_row: Some(padded_bpr),
998 rows_per_image: Some(h),
999 },
1000 },
1001 wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
1002 );
1003 self.queue.submit(Some(enc.finish()));
1004
1005 let slice = buf.slice(..);
1006 let (tx, rx) = std::sync::mpsc::channel();
1007 slice.map_async(wgpu::MapMode::Read, move |res| {
1008 let _ = tx.send(res);
1009 });
1010 self.device.poll(wgpu::PollType::Wait {
1011 submission_index: None,
1012 timeout: Some(std::time::Duration::from_secs(10)),
1013 })?;
1014 rx.recv()??;
1015 let data = slice.get_mapped_range()?;
1016 let mut out = Vec::with_capacity((w * h * 4) as usize);
1017 for row in 0..h as usize {
1018 let start = row * padded_bpr as usize;
1019 out.extend_from_slice(&data[start..start + unpadded_bpr as usize]);
1020 }
1021 drop(data);
1022 buf.unmap();
1023 Ok(out)
1024 }
1025
1026 fn scaled_dims(&self, w: u32, h: u32) -> [u32; 2] {375 fn scaled_dims(&self, w: u32, h: u32) -> [u32; 2] {
1027 let s = self.proxy_scale.max(1);376 let s = self.proxy_scale.max(1);
1028 [(w / s).max(1), (h / s).max(1)]377 [(w / s).max(1), (h / s).max(1)]
...@@ -1338,176 +687,6 @@ impl Engine {...@@ -1338,176 +687,6 @@ impl Engine {
1338 }687 }
1339 h.finish()688 h.finish()
1340 }689 }
1341
1342 #[allow(clippy::too_many_arguments)]
1343 fn dispatch_op(
1344 &self,
1345 enc: &mut wgpu::CommandEncoder,
1346 op: ShaderOp,
1347 src_a: &wgpu::TextureView,
1348 src_b: &wgpu::TextureView,
1349 mask: &wgpu::TextureView,
1350 dst: &CachedTexture,
1351 params: &UniformParams,
1352 ) {
1353 let reg_cell = self.pipelines_for(dst.depth);
1354 reg_cell.borrow_mut().ensure_pipeline(&self.device, op);
1355 let reg = reg_cell.borrow();
1356 let ubuf = self.device.create_buffer(&wgpu::BufferDescriptor {
1357 label: Some("op-params"),
1358 size: std::mem::size_of::<UniformParams>() as u64,
1359 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
1360 mapped_at_creation: false,
1361 });
1362 self.queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(params));
1363
1364 let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
1365 label: Some("op-bg"),
1366 layout: &reg.bgl,
1367 entries: &[
1368 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) },
1369 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) },
1370 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) },
1371 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&reg.sampler) },
1372 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst.view) },
1373 wgpu::BindGroupEntry { binding: 5, resource: ubuf.as_entire_binding() },
1374 ],
1375 });
1376
1377 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
1378 label: Some("comp-op"),
1379 timestamp_writes: None,
1380 });
1381 pass.set_pipeline(&reg.pipelines[&op]);
1382 pass.set_bind_group(0, &bg, &[]);
1383 pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1);
1384 }
1385
1386 #[allow(clippy::too_many_arguments)]
1387 fn dispatch_to_view(
1388 &self,
1389 enc: &mut wgpu::CommandEncoder,
1390 op: ShaderOp,
1391 src_a: &wgpu::TextureView,
1392 src_b: &wgpu::TextureView,
1393 mask: &wgpu::TextureView,
1394 dst_view: &wgpu::TextureView,
1395 dst_size: [u32; 2],
1396 params: &UniformParams,
1397 ) {
1398 self.pipelines.borrow_mut().ensure_pipeline(&self.device, op);
1399 let reg = self.pipelines.borrow();
1400 let ubuf = self.device.create_buffer(&wgpu::BufferDescriptor {
1401 label: Some("op-params"),
1402 size: std::mem::size_of::<UniformParams>() as u64,
1403 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
1404 mapped_at_creation: false,
1405 });
1406 self.queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(params));
1407
1408 let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
1409 label: Some("op-bg"),
1410 layout: &reg.bgl,
1411 entries: &[
1412 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) },
1413 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) },
1414 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) },
1415 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&reg.sampler) },
1416 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(dst_view) },
1417 wgpu::BindGroupEntry { binding: 5, resource: ubuf.as_entire_binding() },
1418 ],
1419 });
1420
1421 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
1422 label: Some("comp-op"),
1423 timestamp_writes: None,
1424 });
1425 pass.set_pipeline(&reg.pipelines[&op]);
1426 pass.set_bind_group(0, &bg, &[]);
1427 pass.dispatch_workgroups(dst_size[0].div_ceil(8), dst_size[1].div_ceil(8), 1);
1428 }
1429
1430}
1431
1432pub fn create_texture(device: &wgpu::Device, size: [u32; 2], content_hash: u64) -> CachedTexture {
1433 create_texture_dod(device, size, [0, 0], size, content_hash)
1434}
1435
1436pub fn create_texture_dod(
1437 device: &wgpu::Device,
1438 size: [u32; 2],
1439 origin: [i32; 2],
1440 canvas_size: [u32; 2],
1441 content_hash: u64,
1442) -> CachedTexture {
1443 create_texture_dod_fmt(
1444 device,
1445 size,
1446 origin,
1447 canvas_size,
1448 BitDepth::Int8,
1449 wgpu::TextureFormat::Rgba8Unorm,
1450 content_hash,
1451 )
1452}
1453
1454pub fn create_texture_dod_fmt(
1455 device: &wgpu::Device,
1456 size: [u32; 2],
1457 origin: [i32; 2],
1458 canvas_size: [u32; 2],
1459 depth: BitDepth,
1460 format: wgpu::TextureFormat,
1461 content_hash: u64,
1462) -> CachedTexture {
1463 let max_dim = device.limits().max_texture_dimension_2d.max(1);
1464 let (clamped, tex_scale) = crate::cache::clamp_dims_to_limit(size[0], size[1], max_dim);
1465 let eff_origin = if tex_scale < 1.0 {
1466 [
1467 (origin[0] as f32 * tex_scale).round() as i32,
1468 (origin[1] as f32 * tex_scale).round() as i32,
1469 ]
1470 } else {
1471 origin
1472 };
1473 let eff_canvas = if size == canvas_size {
1474 clamped
1475 } else if tex_scale < 1.0 {
1476 [
1477 ((canvas_size[0].max(1) as f32 * tex_scale).round() as u32).max(1),
1478 ((canvas_size[1].max(1) as f32 * tex_scale).round() as u32).max(1),
1479 ]
1480 } else {
1481 [canvas_size[0].max(1), canvas_size[1].max(1)]
1482 };
1483 let tex = device.create_texture(&wgpu::TextureDescriptor {
1484 label: Some("comp-tex"),
1485 size: wgpu::Extent3d {
1486 width: clamped[0],
1487 height: clamped[1],
1488 depth_or_array_layers: 1,
1489 },
1490 mip_level_count: 1,
1491 sample_count: 1,
1492 dimension: wgpu::TextureDimension::D2,
1493 format,
1494 usage: wgpu::TextureUsages::TEXTURE_BINDING
1495 | wgpu::TextureUsages::STORAGE_BINDING
1496 | wgpu::TextureUsages::COPY_SRC
1497 | wgpu::TextureUsages::COPY_DST
1498 | wgpu::TextureUsages::RENDER_ATTACHMENT,
1499 view_formats: &[],
1500 });
1501 let mut cached = CachedTexture::from_texture_dod_depth(
1502 tex,
1503 clamped,
1504 eff_origin,
1505 eff_canvas,
1506 depth,
1507 content_hash,
1508 );
1509 cached.tex_scale = tex_scale;
1510 cached
1511}690}
1512691
1513#[cfg(test)]692#[cfg(test)]
...@@ -1935,4 +1114,51 @@ Composition {...@@ -1935,4 +1114,51 @@ Composition {
1935 assert_eq!(eng.output_cache.len(), 1);1114 assert_eq!(eng.output_cache.len(), 1);
1936 assert_eq!(eng.output_cache_bytes(), 32 * 1024 * 1024);1115 assert_eq!(eng.output_cache_bytes(), 32 * 1024 * 1024);
1937 }1116 }
1117
1118 #[test]
1119 fn output_cache_does_not_double_count_shared_node_cache_textures() {
1120 let mut eng = Engine::new_headless().expect("gpu");
1121 eng.set_vram_budget_mb(64);
1122
1123 let src = r#"
1124Composition {
1125 CurrentTime = 0,
1126 RenderRange = { 0, 1 },
1127 GlobalRange = { 0, 1 },
1128 Tools = ordered() {
1129 BG = Background {
1130 Inputs = {
1131 Width = Input { Value = 2048, },
1132 Height = Input { Value = 1024, },
1133 TopLeftRed = Input { Value = 0.5, },
1134 TopLeftAlpha = Input { Value = 1.0, },
1135 },
1136 },
1137 },
1138}
1139"#;
1140 let comp = Comp::from_fusion_str(src).expect("parse shared vram comp");
1141 let bg = comp.find_node("BG").unwrap();
1142
1143 let (tex, _) = eng.evaluate(&comp, bg, 0.0);
1144 assert_eq!(tex.bytes, 8 * 1024 * 1024);
1145 drop(tex);
1146
1147 // Texture is held in both NodeCache and output_cache (Arc::strong_count >= 2).
1148 // vram_bytes() must count the 8 MiB allocation once, not 16 MiB, and NodeCache's
1149 // budget must remain at the full 64 MiB.
1150 assert_eq!(eng.output_cache.unshared_bytes(), 0);
1151 assert_eq!(eng.vram_bytes(), eng.cache.total_vram_bytes());
1152 assert_eq!(eng.vram_bytes(), 8 * 1024 * 1024);
1153 assert_eq!(eng.cache.budget_bytes, 64 * 1024 * 1024);
1154
1155 // If an unshared texture (strong_count == 1) is in output_cache, it IS counted
1156 // in vram_bytes() and subtracted from NodeCache's budget.
1157 let unshared = create_texture(&eng.device, [2048, 1024], 42);
1158 assert_eq!(std::sync::Arc::strong_count(&unshared.texture), 1);
1159 eng.output_cache_insert(123_456, unshared, Vec::new());
1160 assert_eq!(eng.output_cache.unshared_bytes(), 8 * 1024 * 1024);
1161 assert_eq!(eng.vram_bytes(), 16 * 1024 * 1024);
1162 assert_eq!(eng.cache.budget_bytes, 56 * 1024 * 1024);
1163 }
1938}1164}
crates/engine/src/eval/output_cache.rs created+175
...@@ -0,0 +1,175 @@
1//! Bounded LRU cache for recent final evaluation outputs and VRAM budget accounting.
2
3use std::collections::VecDeque;
4use std::collections::hash_map::DefaultHasher;
5use std::hash::{Hash, Hasher};
6use std::sync::Arc;
7
8use model::{Comp, NodeId};
9
10use crate::cache::{CacheMode, CachedTexture};
11
12use super::Engine;
13
14const MAX_OUTPUT_CACHE_BYTES: u64 = 128 * 1024 * 1024;
15const MAX_OUTPUT_CACHE_ENTRIES: usize = 64;
16
17/// Bounded LRU of recent final output textures capped by byte budget (`min(vram_budget / 4, 128 MiB)`),
18/// always keeping at least the most recent frame for `<0.1ms` warm hits during pan/zoom/exposure/scrubbing.
19pub(super) struct OutputCache {
20 entries: VecDeque<(u64, CachedTexture, Vec<String>)>,
21}
22
23impl OutputCache {
24 pub(super) fn new() -> Self {
25 Self {
26 entries: VecDeque::new(),
27 }
28 }
29
30 #[cfg(test)]
31 pub(super) fn len(&self) -> usize {
32 self.entries.len()
33 }
34
35 pub(super) fn clear(&mut self) {
36 self.entries.clear();
37 }
38
39 pub(super) fn budget_bytes(vram_budget_bytes: u64) -> u64 {
40 if vram_budget_bytes < 64 * 1024 * 1024 {
41 0
42 } else {
43 (vram_budget_bytes / 4).min(MAX_OUTPUT_CACHE_BYTES)
44 }
45 }
46
47 /// Total GPU bytes referenced by `output_cache` entries (including textures shared with `NodeCache`).
48 pub(super) fn total_bytes(&self) -> u64 {
49 self.entries.iter().map(|(_, tex, _)| tex.bytes).sum()
50 }
51
52 /// GPU bytes held *exclusively* by `output_cache` (`Arc::strong_count(&tex.texture) == 1`).
53 ///
54 /// Textures still resident in `NodeCache` have `strong_count >= 2` and are already counted in
55 /// `NodeCache::total_vram_bytes()`, so skipping them prevents double-counting against the VRAM budget.
56 pub(super) fn unshared_bytes(&self) -> u64 {
57 self.entries
58 .iter()
59 .filter(|(_, tex, _)| Arc::strong_count(&tex.texture) == 1)
60 .map(|(_, tex, _)| tex.bytes)
61 .sum()
62 }
63
64 pub(super) fn get(&mut self, key: u64, mode: CacheMode) -> Option<(CachedTexture, Vec<String>)> {
65 if mode == CacheMode::Bypass {
66 return None;
67 }
68 let pos = self.entries.iter().position(|(k, _, _)| *k == key)?;
69 let entry = self.entries.remove(pos)?;
70 let res = (entry.1.clone(), entry.2.clone());
71 self.entries.push_back(entry);
72 Some(res)
73 }
74
75 pub(super) fn insert(
76 &mut self,
77 key: u64,
78 tex: CachedTexture,
79 unsupported: Vec<String>,
80 mode: CacheMode,
81 cap: u64,
82 ) {
83 if mode == CacheMode::Bypass || cap == 0 {
84 return;
85 }
86 if let Some(pos) = self.entries.iter().position(|(k, _, _)| *k == key) {
87 self.entries.remove(pos);
88 }
89 self.entries.push_back((key, tex, unsupported));
90 while self.entries.len() > 1
91 && (self.total_bytes() > cap || self.entries.len() > MAX_OUTPUT_CACHE_ENTRIES)
92 {
93 self.entries.pop_front();
94 }
95 }
96
97 pub(super) fn trim_to_cap(&mut self, cap: u64) {
98 if cap == 0 {
99 self.entries.clear();
100 } else {
101 while self.entries.len() > 1 && self.total_bytes() > cap {
102 self.entries.pop_front();
103 }
104 }
105 }
106}
107
108impl Engine {
109 pub(super) fn output_cache_budget_bytes(&self) -> u64 {
110 OutputCache::budget_bytes(self.vram_budget_bytes)
111 }
112
113 /// Total GPU bytes held by `output_cache`.
114 pub fn output_cache_bytes(&self) -> u64 {
115 self.output_cache.total_bytes()
116 }
117
118 /// Total resident GPU VRAM bytes across `NodeCache` (live + pooled) and unshared `output_cache` entries.
119 pub fn vram_bytes(&self) -> u64 {
120 self.cache
121 .total_vram_bytes()
122 .saturating_add(self.output_cache.unshared_bytes())
123 }
124
125 pub fn vram_mb(&self) -> f64 {
126 self.vram_bytes() as f64 / (1024.0 * 1024.0)
127 }
128
129 pub(super) fn sync_node_cache_budget(&mut self) {
130 let remaining_bytes = self
131 .vram_budget_bytes
132 .saturating_sub(self.output_cache.unshared_bytes());
133 let remaining_mb = remaining_bytes / (1024 * 1024);
134 if self.cache.budget_bytes != remaining_mb.saturating_mul(1024 * 1024) {
135 self.cache.set_budget_mb(remaining_mb);
136 }
137 }
138
139 pub fn set_vram_budget_mb(&mut self, budget_mb: u64) {
140 self.vram_budget_bytes = budget_mb.saturating_mul(1024 * 1024);
141 let cap = self.output_cache_budget_bytes();
142 self.output_cache.trim_to_cap(cap);
143 self.sync_node_cache_budget();
144 }
145
146 pub fn vram_budget_mb(&self) -> u64 {
147 self.vram_budget_bytes / (1024 * 1024)
148 }
149
150 pub(super) fn output_cache_key(&self, comp: &Comp, target: NodeId, time: f64) -> u64 {
151 let mut h = DefaultHasher::new();
152 self.cache.gpu_salt.hash(&mut h);
153 comp.name.hash(&mut h);
154 comp.path.hash(&mut h);
155 comp.nodes.len().hash(&mut h);
156 comp.revision.hash(&mut h);
157 target.hash(&mut h);
158 time.to_bits().hash(&mut h);
159 self.proxy_scale.hash(&mut h);
160 self.hiq.hash(&mut h);
161 self.use_proxy_clips.hash(&mut h);
162 h.finish()
163 }
164
165 pub(super) fn output_cache_get(&mut self, key: u64) -> Option<(CachedTexture, Vec<String>)> {
166 self.output_cache.get(key, self.cache.mode)
167 }
168
169 pub(super) fn output_cache_insert(&mut self, key: u64, tex: CachedTexture, unsupported: Vec<String>) {
170 let cap = self.output_cache_budget_bytes();
171 self.output_cache
172 .insert(key, tex, unsupported, self.cache.mode, cap);
173 self.sync_node_cache_budget();
174 }
175}
crates/engine/src/eval/registry.rs created+334
...@@ -0,0 +1,334 @@
1//! Shader domains, GPU op enum, and lazy WGSL pipeline compilation cache.
2
3use std::collections::HashMap;
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
6pub(super) enum ShaderDomain {
7 Composite,
8 Color,
9 BlurGlow,
10 Transform,
11 Masks,
12 KeyersGen,
13 ArchiveFx,
14}
15
16impl ShaderDomain {
17 pub(super) fn source(self) -> &'static str {
18 match self {
19 Self::Composite => include_str!("../shaders/composite.wgsl"),
20 Self::Color => include_str!("../shaders/color.wgsl"),
21 Self::BlurGlow => include_str!("../shaders/blur_glow.wgsl"),
22 Self::Transform => include_str!("../shaders/transform.wgsl"),
23 Self::Masks => include_str!("../shaders/masks.wgsl"),
24 Self::KeyersGen => include_str!("../shaders/keyers_gen.wgsl"),
25 Self::ArchiveFx => include_str!("../shaders/archive_fx.wgsl"),
26 }
27 }
28
29 pub(super) fn label(self) -> &'static str {
30 match self {
31 Self::Composite => "compositor-shaders-composite",
32 Self::Color => "compositor-shaders-color",
33 Self::BlurGlow => "compositor-shaders-blur-glow",
34 Self::Transform => "compositor-shaders-transform",
35 Self::Masks => "compositor-shaders-masks",
36 Self::KeyersGen => "compositor-shaders-keyers-gen",
37 Self::ArchiveFx => "compositor-shaders-archive-fx",
38 }
39 }
40}
41
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
43pub(super) enum ShaderOp {
44 Bg,
45 Merge,
46 Transform,
47 Bc,
48 Cc,
49 ColorGain,
50 LumaKey,
51 Blur,
52 DirBlur,
53 FastNoise,
54 Displace,
55 MaskShape,
56 MaskCombine,
57 MaskApply,
58 BitmapMask,
59 Colorize,
60 ColorCurves,
61 XfChroma,
62 GamutConvert,
63 VariBlur,
64 OutlineTint,
65 OutlineComposite,
66 #[allow(dead_code)]
67 CustomWave,
68 Crop,
69 GlowAdd,
70 XGlowPrep,
71 XGlowAccum,
72 DisplayBlit,
73 Invert,
74 ChannelBoolean,
75 Filter,
76 HueCurves,
77 UltraKeyer,
78 Dissolve,
79 Homography,
80 ShadowComp,
81 Plasma,
82 FilmGrain,
83 SetDomain,
84 ChangeDepth,
85 Vortex,
86 KScope,
87 Drip,
88 Dent,
89 PerspectivePos,
90 DaySky,
91 GridWarp,
92}
93
94impl ShaderOp {
95 pub(super) fn domain(self) -> ShaderDomain {
96 match self {
97 Self::Bg
98 | Self::Merge
99 | Self::DisplayBlit
100 | Self::ChannelBoolean
101 | Self::Dissolve
102 | Self::ShadowComp
103 | Self::SetDomain
104 | Self::ChangeDepth => ShaderDomain::Composite,
105
106 Self::Bc
107 | Self::Cc
108 | Self::ColorGain
109 | Self::Colorize
110 | Self::ColorCurves
111 | Self::GamutConvert
112 | Self::Invert
113 | Self::HueCurves => ShaderDomain::Color,
114
115 Self::Blur
116 | Self::DirBlur
117 | Self::VariBlur
118 | Self::GlowAdd
119 | Self::XGlowPrep
120 | Self::XGlowAccum
121 | Self::Filter
122 | Self::FilmGrain => ShaderDomain::BlurGlow,
123
124 Self::Transform
125 | Self::Displace
126 | Self::XfChroma
127 | Self::Crop
128 | Self::Homography
129 | Self::Vortex
130 | Self::KScope => ShaderDomain::Transform,
131
132 Self::MaskShape
133 | Self::MaskCombine
134 | Self::MaskApply
135 | Self::BitmapMask => ShaderDomain::Masks,
136
137 Self::LumaKey
138 | Self::FastNoise
139 | Self::OutlineTint
140 | Self::OutlineComposite
141 | Self::CustomWave
142 | Self::UltraKeyer
143 | Self::Plasma => ShaderDomain::KeyersGen,
144
145 Self::Drip | Self::Dent | Self::PerspectivePos | Self::DaySky | Self::GridWarp => {
146 ShaderDomain::ArchiveFx
147 }
148 }
149 }
150
151 pub(super) fn entry_point(self) -> &'static str {
152 match self {
153 Self::Bg => "bg_op",
154 Self::Merge => "merge_op",
155 Self::Transform => "transform_op",
156 Self::Bc => "bc_op",
157 Self::Cc => "cc_op",
158 Self::ColorGain => "color_gain_op",
159 Self::LumaKey => "luma_key_op",
160 Self::Blur => "blur_op",
161 Self::DirBlur => "dir_blur_op",
162 Self::FastNoise => "fast_noise_op",
163 Self::Displace => "displace_op",
164 Self::MaskShape => "mask_shape_op",
165 Self::MaskCombine => "mask_combine_op",
166 Self::MaskApply => "mask_apply_op",
167 Self::BitmapMask => "bitmap_mask_op",
168 Self::Colorize => "colorize_op",
169 Self::ColorCurves => "color_curves_op",
170 Self::XfChroma => "xf_chroma_op",
171 Self::GamutConvert => "gamut_convert_op",
172 Self::VariBlur => "vari_blur_op",
173 Self::OutlineTint => "outline_tint",
174 Self::OutlineComposite => "outline_composite",
175 Self::CustomWave => "custom_wave_op",
176 Self::Crop => "crop_op",
177 Self::GlowAdd => "glow_add_op",
178 Self::XGlowPrep => "xglow_prep_op",
179 Self::XGlowAccum => "xglow_accum_op",
180 Self::DisplayBlit => "display_blit_op",
181 Self::Invert => "invert_op",
182 Self::ChannelBoolean => "channel_boolean_op",
183 Self::Filter => "filter_op",
184 Self::HueCurves => "hue_curves_op",
185 Self::UltraKeyer => "ultra_keyer_op",
186 Self::Dissolve => "dissolve_op",
187 Self::Homography => "homography_op",
188 Self::ShadowComp => "shadow_comp_op",
189 Self::Plasma => "plasma_op",
190 Self::FilmGrain => "film_grain_op",
191 Self::SetDomain => "set_domain_op",
192 Self::ChangeDepth => "change_depth_op",
193 Self::Vortex => "vortex_op",
194 Self::KScope => "kscope_op",
195 Self::Drip => "drip_op",
196 Self::Dent => "dent_op",
197 Self::PerspectivePos => "perspective_pos_op",
198 Self::DaySky => "day_sky_op",
199 Self::GridWarp => "grid_warp_op",
200 }
201 }
202}
203
204const COMMON_WGSL: &str = include_str!("../shaders/common.wgsl");
205
206pub(super) struct ShaderRegistry {
207 format: wgpu::TextureFormat,
208 hdr_float: bool,
209 pub(super) bgl: wgpu::BindGroupLayout,
210 pl: wgpu::PipelineLayout,
211 pub(super) sampler: wgpu::Sampler,
212 pub(super) modules: HashMap<ShaderDomain, wgpu::ShaderModule>,
213 pub(super) pipelines: HashMap<ShaderOp, wgpu::ComputePipeline>,
214}
215
216impl ShaderRegistry {
217 pub(super) fn new(device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) -> Self {
218 let tex_entry = |binding| wgpu::BindGroupLayoutEntry {
219 binding,
220 visibility: wgpu::ShaderStages::COMPUTE,
221 ty: wgpu::BindingType::Texture {
222 sample_type: wgpu::TextureSampleType::Float { filterable: true },
223 view_dimension: wgpu::TextureViewDimension::D2,
224 multisampled: false,
225 },
226 count: None,
227 };
228 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
229 label: Some("compositor-bgl"),
230 entries: &[
231 tex_entry(0),
232 tex_entry(1),
233 tex_entry(2),
234 wgpu::BindGroupLayoutEntry {
235 binding: 3,
236 visibility: wgpu::ShaderStages::COMPUTE,
237 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
238 count: None,
239 },
240 wgpu::BindGroupLayoutEntry {
241 binding: 4,
242 visibility: wgpu::ShaderStages::COMPUTE,
243 ty: wgpu::BindingType::StorageTexture {
244 access: wgpu::StorageTextureAccess::WriteOnly,
245 format,
246 view_dimension: wgpu::TextureViewDimension::D2,
247 },
248 count: None,
249 },
250 wgpu::BindGroupLayoutEntry {
251 binding: 5,
252 visibility: wgpu::ShaderStages::COMPUTE,
253 ty: wgpu::BindingType::Buffer {
254 ty: wgpu::BufferBindingType::Uniform,
255 has_dynamic_offset: false,
256 min_binding_size: None,
257 },
258 count: None,
259 },
260 ],
261 });
262
263 let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
264 label: Some("compositor-pl"),
265 bind_group_layouts: &[Some(&bgl)],
266 immediate_size: 0,
267 });
268
269 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
270 label: Some("compositor-linear"),
271 address_mode_u: wgpu::AddressMode::ClampToEdge,
272 address_mode_v: wgpu::AddressMode::ClampToEdge,
273 mag_filter: wgpu::FilterMode::Linear,
274 min_filter: wgpu::FilterMode::Linear,
275 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
276 ..Default::default()
277 });
278
279 Self {
280 format,
281 hdr_float,
282 bgl,
283 pl,
284 sampler,
285 modules: HashMap::new(),
286 pipelines: HashMap::new(),
287 }
288 }
289
290 pub(super) fn ensure_pipeline(&mut self, device: &wgpu::Device, op: ShaderOp) {
291 if self.pipelines.contains_key(&op) {
292 return;
293 }
294 let domain = op.domain();
295 let format = self.format;
296 let hdr_float = self.hdr_float;
297 let module = self.modules.entry(domain).or_insert_with(|| {
298 let domain_src = domain.source();
299 let mut src = String::with_capacity(COMMON_WGSL.len() + domain_src.len() + 1);
300 src.push_str(COMMON_WGSL);
301 src.push('\n');
302 src.push_str(domain_src);
303 let storage_fmt = match format {
304 wgpu::TextureFormat::Rgba16Float => "rgba16float",
305 wgpu::TextureFormat::Rgba32Float => "rgba32float",
306 _ => "rgba8unorm",
307 };
308 if storage_fmt != "rgba8unorm" {
309 src = src.replace(
310 "texture_storage_2d<rgba8unorm, write>",
311 &format!("texture_storage_2d<{storage_fmt}, write>"),
312 );
313 }
314 if hdr_float {
315 src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;");
316 }
317 device.create_shader_module(wgpu::ShaderModuleDescriptor {
318 label: Some(domain.label()),
319 source: wgpu::ShaderSource::Wgsl(src.into()),
320 })
321 });
322
323 let entry = op.entry_point();
324 let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
325 label: Some(entry),
326 layout: Some(&self.pl),
327 module,
328 entry_point: Some(entry),
329 compilation_options: Default::default(),
330 cache: None,
331 });
332 self.pipelines.insert(op, pipeline);
333 }
334}
crates/engine/src/particles.rs+14-2322
...@@ -3,11 +3,21 @@...@@ -3,11 +3,21 @@
3//! Supports `pEmitter`, `pPointForce`, `pDirectionalForce`, `pTurbulence`,3//! Supports `pEmitter`, `pPointForce`, `pDirectionalForce`, `pTurbulence`,
4//! `pDrag` / `pFriction`, `pKill`, `pBounce`, `pMerge`, and `pRender` (2D mode).4//! `pDrag` / `pFriction`, `pKill`, `pBounce`, `pMerge`, and `pRender` (2D mode).
55
6use std::collections::hash_map::DefaultHasher;6mod plan;
7use std::collections::{BTreeMap, HashMap, HashSet};7mod raster;
8use std::hash::{Hash, Hasher};8mod sim;
9#[cfg(test)]
10mod tests;
11
12pub use plan::collect_bitmap_sources;
13
14use std::collections::{BTreeMap, HashMap};
15
16use model::{Comp, ExprEngine, NodeId};
917
10use model::{BezierSpline, Comp, ExprEngine, Gradient, InputBinding, Node, NodeId, ParamValue};18use plan::{build_particle_plan, particle_subgraph_hash};
19use raster::rasterize_particles;
20use sim::step_simulation;
1121
12/// Maximum simultaneous live particles kept in a single simulation to prevent22/// Maximum simultaneous live particles kept in a single simulation to prevent
13/// pathological comps from hanging or exhausting memory.23/// pathological comps from hanging or exhausting memory.
...@@ -153,392 +163,6 @@ impl SplitMix64 {...@@ -153,392 +163,6 @@ impl SplitMix64 {
153 }163 }
154}164}
155165
156/// Returns true if `kind` is a Fusion particle stream operator.
157fn is_particle_node_kind(kind: &str) -> bool {
158 matches!(
159 kind,
160 "pRender"
161 | "pEmitter"
162 | "pPointForce"
163 | "pDirectionalForce"
164 | "pTurbulence"
165 | "pDrag"
166 | "pFriction"
167 | "pKill"
168 | "pMerge"
169 | "pBounce"
170 | "pVortex"
171 | "pFlock"
172 | "pAvoid"
173 | "pSpawn"
174 | "pChangeStyle"
175 | "pCustom"
176 | "pCustomForce"
177 | "pGradientForce"
178 | "pImageEmitter"
179 ) || (kind.starts_with('p')
180 && kind
181 .as_bytes()
182 .get(1)
183 .is_some_and(|b| b.is_ascii_uppercase()))
184}
185
186/// Returns the particle stream input node IDs of `node` in deterministic order.
187fn particle_stream_inputs(comp: &Comp, node: &Node) -> Vec<NodeId> {
188 let mut ports: Vec<&str> = Vec::new();
189 for key in node.inputs.keys() {
190 if key == "Input"
191 || key
192 .strip_prefix("Input")
193 .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))
194 {
195 ports.push(key.as_str());
196 }
197 }
198 ports.sort_unstable();
199
200 let mut out = Vec::with_capacity(ports.len());
201 for port in ports {
202 if let Some(src_name) = node.connected_node(port) {
203 if let Some(&src_id) = comp.node_by_name.get(src_name) {
204 out.push(src_id);
205 }
206 }
207 }
208 out
209}
210
211/// Walks upstream from `render_node` through particle operators and returns every
212/// `(emitter_node_id, sprite_source_node_id)` pair for `pEmitter` nodes whose
213/// `ParticleStyleBitmap.DropToolsHere` input is connected.
214pub fn collect_bitmap_sources(comp: &Comp, render_node: NodeId) -> Vec<(NodeId, NodeId)> {
215 let mut visited = HashSet::new();
216 let mut out = Vec::new();
217 collect_bitmap_sources_dfs(comp, render_node, &mut visited, &mut out);
218 out
219}
220
221fn collect_bitmap_sources_dfs(
222 comp: &Comp,
223 node_id: NodeId,
224 visited: &mut HashSet<NodeId>,
225 out: &mut Vec<(NodeId, NodeId)>,
226) {
227 if !visited.insert(node_id) {
228 return;
229 }
230 let Some(node) = comp.nodes.get(node_id.0) else {
231 return;
232 };
233 if !is_particle_node_kind(&node.kind) {
234 return;
235 }
236
237 if node.kind == "pEmitter" {
238 if let Some(src_name) = node.connected_node("ParticleStyleBitmap.DropToolsHere") {
239 if let Some(&src_id) = comp.node_by_name.get(src_name) {
240 out.push((node_id, src_id));
241 }
242 }
243 }
244
245 for up_id in particle_stream_inputs(comp, node) {
246 collect_bitmap_sources_dfs(comp, up_id, visited, out);
247 }
248}
249
250/// Flattened, topologically-ordered particle graph upstream of a `pRender` node.
251struct ParticlePlan {
252 emitters: Vec<(NodeId, u64)>,
253 /// Forces/modifiers in topological order along with the set of upstream
254 /// emitter name hashes whose particles flow through each modifier.
255 modifiers: Vec<(NodeId, HashSet<u64>)>,
256 emitter_nodes: HashMap<u64, NodeId>,
257}
258
259fn build_particle_plan(comp: &Comp, render_node: NodeId) -> ParticlePlan {
260 let mut visited = HashSet::new();
261 let mut emitters = Vec::new();
262 let mut modifiers = Vec::new();
263 let mut upstream_emitters: HashMap<NodeId, HashSet<u64>> = HashMap::new();
264 let mut emitter_nodes = HashMap::new();
265
266 build_plan_dfs(
267 comp,
268 render_node,
269 &mut visited,
270 &mut emitters,
271 &mut modifiers,
272 &mut upstream_emitters,
273 &mut emitter_nodes,
274 );
275
276 ParticlePlan {
277 emitters,
278 modifiers,
279 emitter_nodes,
280 }
281}
282
283fn build_plan_dfs(
284 comp: &Comp,
285 node_id: NodeId,
286 visited: &mut HashSet<NodeId>,
287 emitters: &mut Vec<(NodeId, u64)>,
288 modifiers: &mut Vec<(NodeId, HashSet<u64>)>,
289 upstream_emitters: &mut HashMap<NodeId, HashSet<u64>>,
290 emitter_nodes: &mut HashMap<u64, NodeId>,
291) -> HashSet<u64> {
292 if let Some(cached) = upstream_emitters.get(&node_id) {
293 return cached.clone();
294 }
295 if !visited.insert(node_id) {
296 return HashSet::new();
297 }
298
299 let Some(node) = comp.nodes.get(node_id.0) else {
300 return HashSet::new();
301 };
302 if !is_particle_node_kind(&node.kind) {
303 return HashSet::new();
304 }
305
306 let mut scope = HashSet::new();
307 for up_id in particle_stream_inputs(comp, node) {
308 let up_set = build_plan_dfs(
309 comp,
310 up_id,
311 visited,
312 emitters,
313 modifiers,
314 upstream_emitters,
315 emitter_nodes,
316 );
317 scope.extend(up_set);
318 }
319
320 if node.kind == "pEmitter" {
321 if !node.bypassed {
322 let emitter_hash = stable_name_hash(&node.name);
323 emitters.push((node_id, emitter_hash));
324 emitter_nodes.insert(emitter_hash, node_id);
325 scope.insert(emitter_hash);
326 }
327 } else if !node.bypassed
328 && matches!(
329 node.kind.as_str(),
330 "pPointForce"
331 | "pDirectionalForce"
332 | "pTurbulence"
333 | "pDrag"
334 | "pFriction"
335 | "pKill"
336 | "pBounce"
337 )
338 {
339 modifiers.push((node_id, scope.clone()));
340 }
341
342 upstream_emitters.insert(node_id, scope.clone());
343 scope
344}
345
346fn hash_spline(spline: &BezierSpline, h: &mut DefaultHasher) {
347 spline.name.hash(h);
348 spline.keyframes.len().hash(h);
349 for kf in &spline.keyframes {
350 kf.time.to_bits().hash(h);
351 kf.value.to_bits().hash(h);
352 if let Some([lx, ly]) = kf.lh {
353 1u8.hash(h);
354 lx.to_bits().hash(h);
355 ly.to_bits().hash(h);
356 } else {
357 0u8.hash(h);
358 }
359 if let Some([rx, ry]) = kf.rh {
360 1u8.hash(h);
361 rx.to_bits().hash(h);
362 ry.to_bits().hash(h);
363 } else {
364 0u8.hash(h);
365 }
366 [
367 kf.flags.linear,
368 kf.flags.step_in,
369 kf.flags.step_out,
370 kf.flags.loop_after,
371 kf.flags.loop_rel,
372 kf.flags.ping_pong,
373 kf.flags.locked_y,
374 ]
375 .hash(h);
376 (kf.handle_mode as u8).hash(h);
377 }
378}
379
380fn hash_gradient(grad: &Gradient, h: &mut DefaultHasher) {
381 grad.stops.len().hash(h);
382 for stop in &grad.stops {
383 stop.pos.to_bits().hash(h);
384 for c in stop.rgba {
385 c.to_bits().hash(h);
386 }
387 }
388}
389
390fn hash_input_binding(
391 comp: &Comp,
392 binding: &InputBinding,
393 visited_mods: &mut HashSet<String>,
394 h: &mut DefaultHasher,
395) {
396 binding.source_output.hash(h);
397 binding.expression.hash(h);
398 match &binding.value {
399 None => 0u8.hash(h),
400 Some(ParamValue::Number(v)) => {
401 1u8.hash(h);
402 v.to_bits().hash(h);
403 }
404 Some(ParamValue::Point([x, y])) => {
405 2u8.hash(h);
406 x.to_bits().hash(h);
407 y.to_bits().hash(h);
408 }
409 Some(ParamValue::Text(s)) => {
410 3u8.hash(h);
411 s.hash(h);
412 }
413 Some(ParamValue::FuId(s)) => {
414 4u8.hash(h);
415 s.hash(h);
416 }
417 Some(ParamValue::Gradient(g)) => {
418 5u8.hash(h);
419 hash_gradient(g, h);
420 }
421 Some(ParamValue::Raw(raw)) => {
422 6u8.hash(h);
423 format!("{raw:?}").hash(h);
424 }
425 }
426 binding.source_op.hash(h);
427 if let Some(op) = &binding.source_op {
428 if let Some(sp) = comp.splines.get(op) {
429 hash_spline(sp, h);
430 }
431 if let Some(pp) = comp.poly_paths.get(op) {
432 pp.name.hash(h);
433 pp.displacement_op.hash(h);
434 pp.displacement_value.to_bits().hash(h);
435 pp.closed.hash(h);
436 pp.points.len().hash(h);
437 for pt in &pp.points {
438 pt.x.to_bits().hash(h);
439 pt.y.to_bits().hash(h);
440 pt.lx.to_bits().hash(h);
441 pt.ly.to_bits().hash(h);
442 pt.rx.to_bits().hash(h);
443 pt.ry.to_bits().hash(h);
444 pt.linear.hash(h);
445 }
446 if let Some(disp_op) = &pp.displacement_op {
447 if let Some(sp) = comp.splines.get(disp_op) {
448 hash_spline(sp, h);
449 }
450 }
451 }
452 if let Some(sh) = comp.shakes.get(op) {
453 if visited_mods.insert(op.clone()) {
454 hash_sorted_inputs(comp, &sh.inputs, visited_mods, h);
455 visited_mods.remove(op);
456 } else {
457 0xC1C1_u16.hash(h);
458 op.hash(h);
459 }
460 }
461 if let Some(ex) = comp.expression_modifiers.get(op) {
462 if visited_mods.insert(op.clone()) {
463 hash_sorted_inputs(comp, &ex.inputs, visited_mods, h);
464 visited_mods.remove(op);
465 } else {
466 0xC1C2_u16.hash(h);
467 op.hash(h);
468 }
469 }
470 if let Some(gm) = comp.gradient_modifiers.get(op) {
471 gm.len().hash(h);
472 for (t, g) in gm {
473 t.to_bits().hash(h);
474 hash_gradient(g, h);
475 }
476 }
477 }
478}
479
480fn hash_sorted_inputs(
481 comp: &Comp,
482 inputs: &HashMap<String, InputBinding>,
483 visited_mods: &mut HashSet<String>,
484 h: &mut DefaultHasher,
485) {
486 let mut keys: Vec<&String> = inputs.keys().collect();
487 keys.sort_unstable();
488 keys.len().hash(h);
489 for k in keys {
490 k.hash(h);
491 hash_input_binding(comp, &inputs[k], visited_mods, h);
492 }
493}
494
495/// Content hash of the particle simulation subgraph upstream of `render_node`.
496/// Unrelated edits outside the particle branch leave this hash unchanged.
497fn particle_subgraph_hash(comp: &Comp, render_node: NodeId, base_start: i64) -> u64 {
498 fn dfs(
499 comp: &Comp,
500 node_id: NodeId,
501 is_root: bool,
502 visited: &mut HashSet<NodeId>,
503 visited_mods: &mut HashSet<String>,
504 h: &mut DefaultHasher,
505 ) {
506 if !visited.insert(node_id) {
507 return;
508 }
509 let Some(node) = comp.nodes.get(node_id.0) else {
510 return;
511 };
512 if !is_particle_node_kind(&node.kind) {
513 return;
514 }
515 node.name.hash(h);
516 node.kind.hash(h);
517 node.bypassed.hash(h);
518
519 let mut keys: Vec<&String> = node.inputs.keys().collect();
520 keys.sort_unstable();
521 for k in keys {
522 // `pRender.Width` and bitmap drop target only affect rasterization, not simulation state.
523 if (is_root && k == "Width") || k == "ParticleStyleBitmap.DropToolsHere" {
524 continue;
525 }
526 k.hash(h);
527 hash_input_binding(comp, &node.inputs[k], visited_mods, h);
528 }
529 for up_id in particle_stream_inputs(comp, node) {
530 dfs(comp, up_id, false, visited, visited_mods, h);
531 }
532 }
533
534 let mut h = DefaultHasher::new();
535 base_start.hash(&mut h);
536 let mut visited = HashSet::new();
537 let mut visited_mods = HashSet::new();
538 dfs(comp, render_node, true, &mut visited, &mut visited_mods, &mut h);
539 h.finish()
540}
541
542fn maybe_record_snapshot(cached: &mut CachedSim, frame: i64) {166fn maybe_record_snapshot(cached: &mut CachedSim, frame: i64) {
543 if (frame - cached.base_start).rem_euclid(SNAPSHOT_INTERVAL) == 0 {167 if (frame - cached.base_start).rem_euclid(SNAPSHOT_INTERVAL) == 0 {
544 cached.snapshots.insert(frame, cached.state.clone());168 cached.snapshots.insert(frame, cached.state.clone());
...@@ -665,1935 +289,3 @@ pub fn render_particles_2d(...@@ -665,1935 +289,3 @@ pub fn render_particles_2d(
665 );289 );
666 out290 out
667}291}
668
669/// Advances the particle simulation by a single integer frame `frame`.
670fn step_simulation(
671 state: &mut SimState,
672 comp: &Comp,
673 plan: &ParticlePlan,
674 frame: i64,
675 expr: &ExprEngine,
676) {
677 let t = frame as f64;
678
679 // 1. Apply forces & kills to existing live particles, then integrate motion and age.
680 if !state.particles.is_empty() {
681 for (mod_id, scope) in &plan.modifiers {
682 let Some(node) = comp.nodes.get(mod_id.0) else {
683 continue;
684 };
685 apply_modifier(&mut state.particles, comp, node, scope, t, expr);
686 }
687
688 for p in &mut state.particles {
689 if !p.alive {
690 continue;
691 }
692 p.pos[0] += p.vel[0];
693 p.pos[1] += p.vel[1];
694 p.pos[2] += p.vel[2];
695 p.rot_z += p.spin_z;
696 p.age += 1.0;
697 if p.age >= p.lifespan {
698 p.alive = false;
699 }
700 }
701 state.particles.retain(|p| p.alive);
702 }
703
704 // 2. Emit new particles for `frame` (born with `age = 0.0` at their spawn region).
705 let first_new = state.particles.len();
706 for &(emitter_id, emitter_hash) in &plan.emitters {
707 if state.particles.len() >= MAX_PARTICLES {
708 break;
709 }
710 let Some(node) = comp.nodes.get(emitter_id.0) else {
711 continue;
712 };
713 emit_particles(state, comp, node, emitter_hash, frame, t, expr);
714 }
715
716 // A newborn is damped by friction and then integrated once on its birth frame; other forces
717 // only start acting next frame.
718 for (mod_id, scope) in &plan.modifiers {
719 let Some(node) = comp.nodes.get(mod_id.0) else {
720 continue;
721 };
722 if matches!(node.kind.as_str(), "pDrag" | "pFriction") {
723 apply_modifier(&mut state.particles[first_new..], comp, node, scope, t, expr);
724 }
725 }
726 for p in &mut state.particles[first_new..] {
727 for axis in 0..3 {
728 p.pos[axis] += p.vel[axis];
729 }
730 p.rot_z += p.spin_z;
731 }
732}
733
734fn emit_particles(
735 state: &mut SimState,
736 comp: &Comp,
737 node: &Node,
738 emitter_hash: u64,
739 frame: i64,
740 t: f64,
741 expr: &ExprEngine,
742) {
743 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64;
744 let mut rng = SplitMix64::from_parts(seed, frame, &node.name);
745
746 let number = comp.eval_number(node, "Number", t, 10.0, expr).max(0.0);
747 let number_var = comp
748 .eval_number(node, "NumberVariance", t, 0.0, expr)
749 .max(0.0);
750
751 let rate = (number + rng.signed() * number_var).max(0.0);
752 let accum = state.emit_accum.entry(emitter_hash).or_insert(0.0);
753 *accum += rate;
754 let mut emit_count = accum.floor() as usize;
755 *accum -= emit_count as f64;
756
757 if emit_count == 0 {
758 return;
759 }
760 let remaining_cap = MAX_PARTICLES.saturating_sub(state.particles.len());
761 if emit_count > remaining_cap {
762 emit_count = remaining_cap;
763 }
764
765 let lifespan_base = comp.eval_number(node, "Lifespan", t, 100.0, expr).max(1.0);
766 let lifespan_var = comp
767 .eval_number(node, "LifespanVariance", t, 0.0, expr)
768 .max(0.0);
769 let pos_var = comp
770 .eval_number(node, "PositionVariance", t, 0.0, expr)
771 .max(0.0);
772
773 let vel_base = comp.eval_number(node, "Velocity", t, 0.0, expr);
774 let vel_var = comp
775 .eval_number(node, "VelocityVariance", t, 0.0, expr)
776 .max(0.0);
777 let angle_base = comp.eval_number(node, "Angle", t, 0.0, expr);
778 let angle_var = comp
779 .eval_number(node, "AngleVariance", t, 0.0, expr)
780 .max(0.0);
781 let angle_z_base = comp.eval_number(node, "AngleZ", t, 0.0, expr);
782 let angle_z_var = comp
783 .eval_number(node, "AngleZVariance", t, 0.0, expr)
784 .max(0.0);
785
786 let rot_z_base = comp.eval_number(node, "RotationZ", t, 0.0, expr);
787 let rot_z_var = comp
788 .eval_number(node, "RotationZVariance", t, 0.0, expr)
789 .max(0.0);
790 let spin_z_base = comp.eval_number(node, "SpinZ", t, 0.0, expr);
791 let spin_z_var = comp
792 .eval_number(node, "SpinZVariance", t, 0.0, expr)
793 .max(0.0);
794
795 let base_r = comp.eval_number(node, "ParticleStyle.Red", t, 1.0, expr);
796 let base_g = comp.eval_number(node, "ParticleStyle.Green", t, 1.0, expr);
797 let base_b = comp.eval_number(node, "ParticleStyle.Blue", t, 1.0, expr);
798 let base_a = comp.eval_number(node, "ParticleStyle.Alpha", t, 1.0, expr);
799
800 let color_var = comp.eval_number(node, "ParticleStyle.ColorVariance", t, 0.0, expr) > 0.5;
801 let r_lo = (base_r + comp.eval_number(node, "ParticleStyle.RedLow", t, 0.0, expr)).clamp(0.0, 1.0);
802 let r_hi = (base_r + comp.eval_number(node, "ParticleStyle.RedHigh", t, 0.0, expr)).clamp(0.0, 1.0);
803 let g_lo = (base_g + comp.eval_number(node, "ParticleStyle.GreenLow", t, 0.0, expr)).clamp(0.0, 1.0);
804 let g_hi = (base_g + comp.eval_number(node, "ParticleStyle.GreenHigh", t, 0.0, expr)).clamp(0.0, 1.0);
805 let b_lo = (base_b + comp.eval_number(node, "ParticleStyle.BlueLow", t, 0.0, expr)).clamp(0.0, 1.0);
806 let b_hi = (base_b + comp.eval_number(node, "ParticleStyle.BlueHigh", t, 0.0, expr)).clamp(0.0, 1.0);
807 let a_lo = (base_a + comp.eval_number(node, "ParticleStyle.AlphaLow", t, 0.0, expr)).clamp(0.0, 1.0);
808 let a_hi = (base_a + comp.eval_number(node, "ParticleStyle.AlphaHigh", t, 0.0, expr)).clamp(0.0, 1.0);
809
810 let size_base = comp
811 .eval_number(node, "ParticleStyle.Size", t, 1.0, expr)
812 .max(0.0);
813 let size_var = comp
814 .eval_number(node, "ParticleStyle.SizeVariance", t, 0.0, expr)
815 .max(0.0);
816
817 let region = RegionSpec::from_node(comp, node, t, expr);
818
819 for _ in 0..emit_count {
820 let mut pos = region.sample(&mut rng);
821 if pos_var > 0.0 {
822 pos[0] += rng.signed() * pos_var;
823 pos[1] += rng.signed() * pos_var;
824 pos[2] += rng.signed() * pos_var;
825 }
826
827 let speed = (vel_base + rng.signed() * vel_var) * VELOCITY_SCALE;
828 let ang = (angle_base + rng.signed() * angle_var).to_radians();
829 let ang_z = (angle_z_base + rng.signed() * angle_z_var).to_radians();
830 let cos_z = ang_z.cos();
831 let vel = [
832 speed * ang.cos() * cos_z,
833 speed * ang.sin() * cos_z,
834 speed * ang_z.sin(),
835 ];
836
837 let rot_z = rot_z_base + rng.signed() * rot_z_var;
838 let spin_z = spin_z_base + rng.signed() * spin_z_var;
839 let lifespan = (lifespan_base + rng.signed() * lifespan_var).max(1.0);
840 let size = (size_base + rng.signed() * size_var).max(0.0);
841
842 let color = if color_var {
843 [
844 rng.range(r_lo, r_hi) as f32,
845 rng.range(g_lo, g_hi) as f32,
846 rng.range(b_lo, b_hi) as f32,
847 rng.range(a_lo, a_hi) as f32,
848 ]
849 } else {
850 [
851 base_r.clamp(0.0, 1.0) as f32,
852 base_g.clamp(0.0, 1.0) as f32,
853 base_b.clamp(0.0, 1.0) as f32,
854 base_a.clamp(0.0, 1.0) as f32,
855 ]
856 };
857
858 state.particles.push(Particle {
859 emitter_hash,
860 pos,
861 vel,
862 rot_z,
863 spin_z,
864 age: 0.0,
865 lifespan,
866 size,
867 color,
868 alive: true,
869 });
870 }
871}
872
873#[derive(Clone, Copy)]
874enum RegionSpec {
875 Point {
876 center: [f64; 3],
877 },
878 Rect {
879 center: [f64; 3],
880 width: f64,
881 height: f64,
882 },
883 Sphere {
884 center: [f64; 3],
885 radius: f64,
886 },
887 Cube {
888 center: [f64; 3],
889 width: f64,
890 height: f64,
891 depth: f64,
892 },
893 Line {
894 start: [f64; 3],
895 end: [f64; 3],
896 },
897 All,
898}
899
900impl RegionSpec {
901 fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self {
902 let region_name = node.static_str("Region").unwrap_or("SphereRgn");
903 match region_name {
904 "RectRgn" => Self::Rect {
905 center: [
906 comp.eval_number(node, "RectRgn.Translate.X", t, 0.0, expr),
907 comp.eval_number(node, "RectRgn.Translate.Y", t, 0.0, expr),
908 comp.eval_number(node, "RectRgn.Translate.Z", t, 0.0, expr),
909 ],
910 width: comp.eval_number(node, "RectRgn.Width", t, 0.1, expr).abs(),
911 height: comp.eval_number(node, "RectRgn.Height", t, 0.1, expr).abs(),
912 },
913 "SphereRgn" => Self::Sphere {
914 center: [
915 comp.eval_number(node, "SphereRgn.Translate.X", t, 0.0, expr),
916 comp.eval_number(node, "SphereRgn.Translate.Y", t, 0.0, expr),
917 comp.eval_number(node, "SphereRgn.Translate.Z", t, 0.0, expr),
918 ],
919 radius: comp.eval_number(node, "SphereRgn.Size", t, 0.1, expr).abs() * 0.5,
920 },
921 "CubeRgn" => Self::Cube {
922 center: [
923 comp.eval_number(node, "CubeRgn.Translate.X", t, 0.0, expr),
924 comp.eval_number(node, "CubeRgn.Translate.Y", t, 0.0, expr),
925 comp.eval_number(node, "CubeRgn.Translate.Z", t, 0.0, expr),
926 ],
927 width: comp.eval_number(node, "CubeRgn.Width", t, 0.1, expr).abs(),
928 height: comp.eval_number(node, "CubeRgn.Height", t, 0.1, expr).abs(),
929 depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.1, expr).abs(),
930 },
931 "LineRgn" => {
932 let tx = comp.eval_number(node, "LineRgn.Translate.X", t, 0.0, expr);
933 let ty = comp.eval_number(node, "LineRgn.Translate.Y", t, 0.0, expr);
934 let tz = comp.eval_number(node, "LineRgn.Translate.Z", t, 0.0, expr);
935 Self::Line {
936 start: [
937 tx + comp.eval_number(node, "LineRgn.Start.X", t, -0.5, expr),
938 ty + comp.eval_number(node, "LineRgn.Start.Y", t, 0.0, expr),
939 tz + comp.eval_number(node, "LineRgn.Start.Z", t, 0.0, expr),
940 ],
941 end: [
942 tx + comp.eval_number(node, "LineRgn.End.X", t, 0.5, expr),
943 ty + comp.eval_number(node, "LineRgn.End.Y", t, 0.0, expr),
944 tz + comp.eval_number(node, "LineRgn.End.Z", t, 0.0, expr),
945 ],
946 }
947 }
948 "AllRgn" | "All" => Self::All,
949 _ => Self::Point {
950 center: [
951 comp.eval_number(node, "Point.Translate.X", t, 0.0, expr),
952 comp.eval_number(node, "Point.Translate.Y", t, 0.0, expr),
953 comp.eval_number(node, "Point.Translate.Z", t, 0.0, expr),
954 ],
955 },
956 }
957 }
958
959 fn sample(&self, rng: &mut SplitMix64) -> [f64; 3] {
960 match *self {
961 Self::Point { center } => center,
962 Self::Rect {
963 center,
964 width,
965 height,
966 } => [
967 center[0] + (rng.next_f64() - 0.5) * width,
968 center[1] + (rng.next_f64() - 0.5) * height,
969 center[2],
970 ],
971 Self::Sphere { center, radius } => {
972 let u = rng.next_f64();
973 let v = rng.next_f64();
974 let w = rng.next_f64();
975 let theta = u * std::f64::consts::TAU;
976 let cos_phi = 2.0 * v - 1.0;
977 let sin_phi = (1.0 - cos_phi * cos_phi).max(0.0).sqrt();
978 let r = radius * w.cbrt();
979 [
980 center[0] + r * sin_phi * theta.cos(),
981 center[1] + r * sin_phi * theta.sin(),
982 center[2] + r * cos_phi,
983 ]
984 }
985 Self::Cube {
986 center,
987 width,
988 height,
989 depth,
990 } => [
991 center[0] + (rng.next_f64() - 0.5) * width,
992 center[1] + (rng.next_f64() - 0.5) * height,
993 center[2] + (rng.next_f64() - 0.5) * depth,
994 ],
995 Self::Line { start, end } => {
996 let u = rng.next_f64();
997 [
998 start[0] + (end[0] - start[0]) * u,
999 start[1] + (end[1] - start[1]) * u,
1000 start[2] + (end[2] - start[2]) * u,
1001 ]
1002 }
1003 Self::All => [0.0, 0.0, 0.0],
1004 }
1005 }
1006
1007 fn contains(&self, p: [f64; 3]) -> bool {
1008 match *self {
1009 Self::All => true,
1010 Self::Point { center } => {
1011 let dx = p[0] - center[0];
1012 let dy = p[1] - center[1];
1013 let dz = p[2] - center[2];
1014 dx * dx + dy * dy + dz * dz <= 1e-4
1015 }
1016 Self::Rect {
1017 center,
1018 width,
1019 height,
1020 } => {
1021 (p[0] - center[0]).abs() <= width * 0.5
1022 && (p[1] - center[1]).abs() <= height * 0.5
1023 }
1024 Self::Sphere { center, radius } => {
1025 let dx = p[0] - center[0];
1026 let dy = p[1] - center[1];
1027 let dz = p[2] - center[2];
1028 dx * dx + dy * dy + dz * dz <= radius * radius
1029 }
1030 Self::Cube {
1031 center,
1032 width,
1033 height,
1034 depth,
1035 } => {
1036 (p[0] - center[0]).abs() <= width * 0.5
1037 && (p[1] - center[1]).abs() <= height * 0.5
1038 && (p[2] - center[2]).abs() <= depth * 0.5
1039 }
1040 Self::Line { start, end } => {
1041 let vx = end[0] - start[0];
1042 let vy = end[1] - start[1];
1043 let vz = end[2] - start[2];
1044 let len_sq = vx * vx + vy * vy + vz * vz;
1045 let u = if len_sq > 1e-9 {
1046 (((p[0] - start[0]) * vx + (p[1] - start[1]) * vy + (p[2] - start[2]) * vz)
1047 / len_sq)
1048 .clamp(0.0, 1.0)
1049 } else {
1050 0.0
1051 };
1052 let cx = start[0] + vx * u;
1053 let cy = start[1] + vy * u;
1054 let cz = start[2] + vz * u;
1055 let dx = p[0] - cx;
1056 let dy = p[1] - cy;
1057 let dz = p[2] - cz;
1058 dx * dx + dy * dy + dz * dz <= 1e-3
1059 }
1060 }
1061 }
1062
1063 /// Parses a `pBounce` region (supports `LineRgn`, `RectRgn`, `CubeRgn`, `SphereRgn`,
1064 /// `MeshRegion`, and `Transform3DOp.Translate` fallback).
1065 fn from_bounce_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self {
1066 let tx = comp.eval_number(node, "Transform3DOp.Translate.X", t, 0.0, expr);
1067 let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", t, 0.0, expr);
1068 let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", t, 0.0, expr);
1069 match node.static_str("Region") {
1070 Some("RectRgn") => Self::Rect {
1071 center: [
1072 comp.eval_number(node, "RectRgn.Translate.X", t, tx, expr),
1073 comp.eval_number(node, "RectRgn.Translate.Y", t, ty, expr),
1074 comp.eval_number(node, "RectRgn.Translate.Z", t, tz, expr),
1075 ],
1076 width: comp.eval_number(node, "RectRgn.Width", t, 0.1, expr).abs(),
1077 height: comp.eval_number(node, "RectRgn.Height", t, 0.1, expr).abs(),
1078 },
1079 Some("SphereRgn") => Self::Sphere {
1080 center: [
1081 comp.eval_number(node, "SphereRgn.Translate.X", t, tx, expr),
1082 comp.eval_number(node, "SphereRgn.Translate.Y", t, ty, expr),
1083 comp.eval_number(node, "SphereRgn.Translate.Z", t, tz, expr),
1084 ],
1085 radius: comp.eval_number(node, "SphereRgn.Size", t, 0.5, expr).abs() * 0.5,
1086 },
1087 Some("CubeRgn") => Self::Cube {
1088 center: [
1089 comp.eval_number(node, "CubeRgn.Translate.X", t, tx, expr),
1090 comp.eval_number(node, "CubeRgn.Translate.Y", t, ty, expr),
1091 comp.eval_number(node, "CubeRgn.Translate.Z", t, tz, expr),
1092 ],
1093 width: comp.eval_number(node, "CubeRgn.Width", t, 0.1, expr).abs(),
1094 height: comp.eval_number(node, "CubeRgn.Height", t, 0.1, expr).abs(),
1095 depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.1, expr).abs(),
1096 },
1097 Some("LineRgn") => {
1098 let lx = comp.eval_number(node, "LineRgn.Translate.X", t, tx, expr);
1099 let ly = comp.eval_number(node, "LineRgn.Translate.Y", t, ty, expr);
1100 let lz = comp.eval_number(node, "LineRgn.Translate.Z", t, tz, expr);
1101 Self::Line {
1102 start: [
1103 lx + comp.eval_number(node, "LineRgn.Start.X", t, -0.5, expr),
1104 ly + comp.eval_number(node, "LineRgn.Start.Y", t, 0.0, expr),
1105 lz + comp.eval_number(node, "LineRgn.Start.Z", t, 0.0, expr),
1106 ],
1107 end: [
1108 lx + comp.eval_number(node, "LineRgn.End.X", t, 0.5, expr),
1109 ly + comp.eval_number(node, "LineRgn.End.Y", t, 0.0, expr),
1110 lz + comp.eval_number(node, "LineRgn.End.Z", t, 0.0, expr),
1111 ],
1112 }
1113 }
1114 Some("MeshRegion") | None => Self::Point { center: [tx, ty, tz] },
1115 _ => Self::from_node(comp, node, t, expr),
1116 }
1117 }
1118
1119 /// Checks whether a particle stepping `pos -> pos + vel` collides with this bounce region.
1120 /// Returns `(contact_pos, outward_unit_normal)` when a reflection should occur.
1121 fn bounce_collision(&self, pos: [f64; 3], vel: [f64; 3]) -> Option<([f64; 3], [f64; 3])> {
1122 let next = [pos[0] + vel[0], pos[1] + vel[1], pos[2] + vel[2]];
1123 match *self {
1124 Self::Line { start, end } => {
1125 let sx = end[0] - start[0];
1126 let sy = end[1] - start[1];
1127 let len_sq = sx * sx + sy * sy;
1128 let len = len_sq.sqrt();
1129 if len < 1e-9 {
1130 return None;
1131 }
1132 let mut n = [-sy / len, sx / len, 0.0];
1133 let d0 = (pos[0] - start[0]) * n[0] + (pos[1] - start[1]) * n[1];
1134 let d1 = (next[0] - start[0]) * n[0] + (next[1] - start[1]) * n[1];
1135 let crosses = (d0 * d1 <= 0.0 && (d0.abs() > 1e-12 || d1.abs() > 1e-12))
1136 || d1.abs() <= 1e-4;
1137 if !crosses {
1138 return None;
1139 }
1140 let alpha = if (d0 - d1).abs() > 1e-12 {
1141 (d0 / (d0 - d1)).clamp(0.0, 1.0)
1142 } else {
1143 1.0
1144 };
1145 let hit = [
1146 pos[0] + vel[0] * alpha,
1147 pos[1] + vel[1] * alpha,
1148 pos[2] + vel[2] * alpha,
1149 ];
1150 let u = ((hit[0] - start[0]) * sx + (hit[1] - start[1]) * sy) / len_sq;
1151 if !(-1e-4..=1.0 + 1e-4).contains(&u) {
1152 return None;
1153 }
1154 let vn = vel[0] * n[0] + vel[1] * n[1];
1155 if vn > 0.0 {
1156 n[0] = -n[0];
1157 n[1] = -n[1];
1158 }
1159 if vel[0] * n[0] + vel[1] * n[1] >= -1e-12 {
1160 return None;
1161 }
1162 Some(([hit[0] + n[0] * 1e-5, hit[1] + n[1] * 1e-5, hit[2]], n))
1163 }
1164 Self::Sphere { center, radius } => {
1165 if radius < 1e-6 {
1166 return None;
1167 }
1168 let dp = [pos[0] - center[0], pos[1] - center[1], pos[2] - center[2]];
1169 let dn = [next[0] - center[0], next[1] - center[1], next[2] - center[2]];
1170 let r_pos = (dp[0] * dp[0] + dp[1] * dp[1] + dp[2] * dp[2]).sqrt();
1171 let r_next = (dn[0] * dn[0] + dn[1] * dn[1] + dn[2] * dn[2]).sqrt();
1172 if r_pos > radius && r_next > radius {
1173 return None;
1174 }
1175 let ref_v = if r_pos > 1e-9 { dp } else if r_next > 1e-9 { dn } else { [0.0, 1.0, 0.0] };
1176 let r_len = (ref_v[0] * ref_v[0] + ref_v[1] * ref_v[1] + ref_v[2] * ref_v[2]).sqrt().max(1e-9);
1177 let mut n = [ref_v[0] / r_len, ref_v[1] / r_len, ref_v[2] / r_len];
1178 if r_pos < radius && r_next >= radius {
1179 // Particle hitting sphere wall from inside
1180 n = [-n[0], -n[1], -n[2]];
1181 let pushed = [
1182 center[0] - n[0] * (radius - 1e-5).max(0.0),
1183 center[1] - n[1] * (radius - 1e-5).max(0.0),
1184 center[2] - n[2] * (radius - 1e-5).max(0.0),
1185 ];
1186 return Some((pushed, n));
1187 }
1188 let pushed = [
1189 center[0] + n[0] * (radius + 1e-5),
1190 center[1] + n[1] * (radius + 1e-5),
1191 center[2] + n[2] * (radius + 1e-5),
1192 ];
1193 Some((pushed, n))
1194 }
1195 Self::Rect { center, width, height } => {
1196 let hx = width * 0.5;
1197 let hy = height * 0.5;
1198 if hy < 1e-6 {
1199 let line = Self::Line {
1200 start: [center[0] - hx, center[1], center[2]],
1201 end: [center[0] + hx, center[1], center[2]],
1202 };
1203 return line.bounce_collision(pos, vel);
1204 }
1205 if hx < 1e-6 {
1206 let line = Self::Line {
1207 start: [center[0], center[1] - hy, center[2]],
1208 end: [center[0], center[1] + hy, center[2]],
1209 };
1210 return line.bounce_collision(pos, vel);
1211 }
1212 bounce_aabb(pos, vel, center, [hx, hy, 1e6], false)
1213 }
1214 Self::Cube { center, width, height, depth } => {
1215 bounce_aabb(pos, vel, center, [width * 0.5, height * 0.5, depth * 0.5], true)
1216 }
1217 Self::Point { center } => {
1218 let cy = center[1];
1219 let d0 = pos[1] - cy;
1220 let d1 = next[1] - cy;
1221 if d0 * d1 <= 0.0 || d1.abs() <= 1e-5 {
1222 let ny = if vel[1] < 0.0 { 1.0 } else if vel[1] > 0.0 { -1.0 } else { return None };
1223 let alpha = if (d0 - d1).abs() > 1e-12 {
1224 (d0 / (d0 - d1)).clamp(0.0, 1.0)
1225 } else {
1226 1.0
1227 };
1228 let hit = [
1229 pos[0] + vel[0] * alpha,
1230 cy + ny * 1e-5,
1231 pos[2] + vel[2] * alpha,
1232 ];
1233 return Some((hit, [0.0, ny, 0.0]));
1234 }
1235 None
1236 }
1237 Self::All => None,
1238 }
1239 }
1240}
1241
1242/// Slab-method segment-vs-AABB bounce helper (2D when `check_z == false`, 3D when `check_z == true`).
1243fn bounce_aabb(
1244 pos: [f64; 3],
1245 vel: [f64; 3],
1246 center: [f64; 3],
1247 half: [f64; 3],
1248 check_z: bool,
1249) -> Option<([f64; 3], [f64; 3])> {
1250 let axes = if check_z { 3 } else { 2 };
1251 let mut inside_pos = true;
1252 for a in 0..axes {
1253 if (pos[a] - center[a]).abs() > half[a] {
1254 inside_pos = false;
1255 break;
1256 }
1257 }
1258
1259 if inside_pos {
1260 // Already inside: push out through the closest face
1261 let mut best_axis = 0usize;
1262 let mut best_pen = f64::INFINITY;
1263 let mut best_sign = 1.0f64;
1264 for a in 0..axes {
1265 let delta = pos[a] - center[a];
1266 let pen = half[a] - delta.abs();
1267 if pen < best_pen {
1268 best_pen = pen;
1269 best_axis = a;
1270 best_sign = if delta >= 0.0 { 1.0 } else { -1.0 };
1271 }
1272 }
1273 let mut n = [0.0; 3];
1274 n[best_axis] = best_sign;
1275 let mut pushed = pos;
1276 pushed[best_axis] = center[best_axis] + best_sign * (half[best_axis] + 1e-5);
1277 return Some((pushed, n));
1278 }
1279
1280 let mut t_min = 0.0_f64;
1281 let mut t_max = 1.0_f64;
1282 let mut hit_axis = 0usize;
1283 let mut hit_sign = 1.0_f64;
1284
1285 for a in 0..axes {
1286 let min_b = center[a] - half[a];
1287 let max_b = center[a] + half[a];
1288 if vel[a].abs() < 1e-12 {
1289 if pos[a] < min_b || pos[a] > max_b {
1290 return None;
1291 }
1292 } else {
1293 let inv = 1.0 / vel[a];
1294 let mut t1 = (min_b - pos[a]) * inv;
1295 let mut t2 = (max_b - pos[a]) * inv;
1296 let mut s = -1.0;
1297 if t1 > t2 {
1298 std::mem::swap(&mut t1, &mut t2);
1299 s = 1.0;
1300 }
1301 if t1 > t_min {
1302 t_min = t1;
1303 hit_axis = a;
1304 hit_sign = s;
1305 }
1306 t_max = t_max.min(t2);
1307 if t_min > t_max {
1308 return None;
1309 }
1310 }
1311 }
1312
1313 let mut n = [0.0; 3];
1314 n[hit_axis] = hit_sign;
1315 let hit = [
1316 pos[0] + vel[0] * t_min + n[0] * 1e-5,
1317 pos[1] + vel[1] * t_min + n[1] * 1e-5,
1318 pos[2] + vel[2] * t_min + n[2] * 1e-5,
1319 ];
1320 Some((hit, n))
1321}
1322
1323fn apply_modifier(
1324 particles: &mut [Particle],
1325 comp: &Comp,
1326 node: &Node,
1327 scope: &HashSet<u64>,
1328 t: f64,
1329 expr: &ExprEngine,
1330) {
1331 match node.kind.as_str() {
1332 "pPointForce" => {
1333 let strength = comp.eval_number(node, "Strength", t, 0.0, expr);
1334 if strength.abs() < 1e-12 {
1335 return;
1336 }
1337 let power = comp.eval_number(node, "Power", t, 2.0, expr);
1338 let tx = comp.eval_number(node, "Translate.X", t, 0.0, expr);
1339 let ty = comp.eval_number(node, "Translate.Y", t, 0.0, expr);
1340 let tz = comp.eval_number(node, "Translate.Z", t, 0.0, expr);
1341
1342 for p in particles.iter_mut() {
1343 if !p.alive || !scope.contains(&p.emitter_hash) {
1344 continue;
1345 }
1346 let dx = tx - p.pos[0];
1347 let dy = ty - p.pos[1];
1348 let dz = tz - p.pos[2];
1349 let dist = (dx * dx + dy * dy + dz * dz).sqrt();
1350 if dist < 1e-7 {
1351 continue;
1352 }
1353 let falloff = dist.max(0.005).powf(power);
1354 let mag = (strength * POINT_FORCE_SCALE / falloff).clamp(-0.25, 0.25);
1355 let inv_d = 1.0 / dist;
1356 p.vel[0] += dx * inv_d * mag;
1357 p.vel[1] += dy * inv_d * mag;
1358 p.vel[2] += dz * inv_d * mag;
1359 }
1360 }
1361 "pDirectionalForce" => {
1362 let strength = comp.eval_number(node, "Strength", t, 0.1, expr);
1363 if strength.abs() < 1e-12 {
1364 return;
1365 }
1366 let dir = comp
1367 .eval_number(node, "Direction", t, -90.0, expr)
1368 .to_radians();
1369 let dir_z = comp
1370 .eval_number(node, "DirectionZ", t, 0.0, expr)
1371 .to_radians();
1372 let mag = strength * VELOCITY_SCALE * VELOCITY_SCALE;
1373 let ax = mag * dir.cos() * dir_z.cos();
1374 let ay = mag * dir.sin() * dir_z.cos();
1375 let az = mag * dir_z.sin();
1376
1377 for p in particles.iter_mut() {
1378 if !p.alive || !scope.contains(&p.emitter_hash) {
1379 continue;
1380 }
1381 p.vel[0] += ax;
1382 p.vel[1] += ay;
1383 p.vel[2] += az;
1384 }
1385 }
1386 "pDrag" | "pFriction" => {
1387 let damp = if node.kind == "pFriction" {
1388 1.0 - comp.eval_number(node, "VelocityFriction", t, 0.05, expr)
1389 } else {
1390 1.0 - comp.eval_number(node, "Drag", t, 0.05, expr)
1391 }
1392 .clamp(0.0, 1.0);
1393 let spin_damp = if node.kind == "pFriction" {
1394 1.0 - comp.eval_number(node, "SpinFriction", t, 0.05, expr).clamp(0.0, 1.0)
1395 } else {
1396 1.0
1397 };
1398 for p in particles.iter_mut() {
1399 if !p.alive || !scope.contains(&p.emitter_hash) {
1400 continue;
1401 }
1402 p.vel[0] *= damp;
1403 p.vel[1] *= damp;
1404 p.vel[2] *= damp;
1405 p.spin_z *= spin_damp;
1406 }
1407 }
1408 "pTurbulence" => {
1409 let sx = comp.eval_number(node, "XStrength", t, 0.1, expr);
1410 let sy = comp.eval_number(node, "YStrength", t, 0.1, expr);
1411 let sz = comp.eval_number(node, "ZStrength", t, 0.0, expr);
1412 if sx.abs() < 1e-12 && sy.abs() < 1e-12 && sz.abs() < 1e-12 {
1413 return;
1414 }
1415 let density = comp.eval_number(node, "Density", t, 1.0, expr).max(0.01);
1416 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as u64;
1417 let time_shift = t * 0.03;
1418
1419 for p in particles.iter_mut() {
1420 if !p.alive || !scope.contains(&p.emitter_hash) {
1421 continue;
1422 }
1423 let qx = p.pos[0] * density + time_shift;
1424 let qy = p.pos[1] * density - time_shift * 0.7;
1425 let qz = p.pos[2] * density;
1426 let nx = value_noise_3d(qx, qy, qz, seed);
1427 let ny = value_noise_3d(qx + 31.7, qy + 17.3, qz + 47.1, seed ^ 0x517C_C1B7_2722_0A95);
1428 let nz = value_noise_3d(qx - 19.4, qy + 53.9, qz - 11.2, seed ^ 0x9E37_79B9_7F4A_7C15);
1429 p.vel[0] += nx * sx * TURBULENCE_SCALE;
1430 p.vel[1] += ny * sy * TURBULENCE_SCALE;
1431 p.vel[2] += nz * sz * TURBULENCE_SCALE;
1432 }
1433 }
1434 "pKill" => {
1435 let region = if node.static_str("Region").is_some() {
1436 RegionSpec::from_node(comp, node, t, expr)
1437 } else {
1438 RegionSpec::All
1439 };
1440 let kill_outside = matches!(
1441 node.static_str("RegionMode"),
1442 Some("Outside") | Some("Leaving")
1443 );
1444 for p in particles.iter_mut() {
1445 if !p.alive || !scope.contains(&p.emitter_hash) {
1446 continue;
1447 }
1448 let inside = region.contains(p.pos);
1449 if (!kill_outside && inside) || (kill_outside && !inside) {
1450 p.alive = false;
1451 }
1452 }
1453 }
1454 "pBounce" => {
1455 let region = RegionSpec::from_bounce_node(comp, node, t, expr);
1456 let elasticity = comp.eval_number(node, "Elasticity", t, 1.0, expr).clamp(0.0, 2.0);
1457 let variance = comp.eval_number(node, "Variance", t, 0.0, expr).max(0.0);
1458 let friction = comp.eval_number(node, "Friction", t, 0.0, expr).clamp(0.0, 1.0);
1459 let roughness = comp.eval_number(node, "Roughness", t, 0.0, expr).max(0.0);
1460 let spin = comp.eval_number(node, "Spin", t, 0.0, expr);
1461 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64;
1462 let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name);
1463
1464 for p in particles.iter_mut() {
1465 if !p.alive || !scope.contains(&p.emitter_hash) {
1466 continue;
1467 }
1468 let Some((pushed_pos, n)) = region.bounce_collision(p.pos, p.vel) else {
1469 continue;
1470 };
1471 let vn = p.vel[0] * n[0] + p.vel[1] * n[1] + p.vel[2] * n[2];
1472 if vn < 0.0 {
1473 let e = (elasticity * (1.0 + rng.signed() * variance)).clamp(0.0, 2.0);
1474 let t_damp = (1.0 - friction).clamp(0.0, 1.0);
1475 let vnx = vn * n[0];
1476 let vny = vn * n[1];
1477 let vnz = vn * n[2];
1478 let vtx = p.vel[0] - vnx;
1479 let vty = p.vel[1] - vny;
1480 let vtz = p.vel[2] - vnz;
1481 p.vel[0] = vtx * t_damp - vnx * e;
1482 p.vel[1] = vty * t_damp - vny * e;
1483 p.vel[2] = vtz * t_damp - vnz * e;
1484 if roughness > 1e-6 {
1485 let scatter = roughness * 0.01 * vn.abs();
1486 p.vel[0] += rng.signed() * scatter;
1487 p.vel[1] += rng.signed() * scatter;
1488 p.vel[2] += rng.signed() * scatter;
1489 }
1490 if spin.abs() > 1e-9 {
1491 p.spin_z += spin * (1.0 + 0.5 * rng.signed());
1492 }
1493 p.pos = pushed_pos;
1494 }
1495 }
1496 }
1497 _ => {}
1498 }
1499}
1500
1501/// Smooth deterministic 3D value noise in `[-1.0, 1.0]`.
1502fn value_noise_3d(x: f64, y: f64, z: f64, seed: u64) -> f64 {
1503 let xi = x.floor() as i64;
1504 let yi = y.floor() as i64;
1505 let zi = z.floor() as i64;
1506 let xf = x - xi as f64;
1507 let yf = y - yi as f64;
1508 let zf = z - zi as f64;
1509
1510 let u = xf * xf * (3.0 - 2.0 * xf);
1511 let v = yf * yf * (3.0 - 2.0 * yf);
1512 let w = zf * zf * (3.0 - 2.0 * zf);
1513
1514 let n000 = lattice_hash(xi, yi, zi, seed);
1515 let n100 = lattice_hash(xi + 1, yi, zi, seed);
1516 let n010 = lattice_hash(xi, yi + 1, zi, seed);
1517 let n110 = lattice_hash(xi + 1, yi + 1, zi, seed);
1518 let n001 = lattice_hash(xi, yi, zi + 1, seed);
1519 let n101 = lattice_hash(xi + 1, yi, zi + 1, seed);
1520 let n011 = lattice_hash(xi, yi + 1, zi + 1, seed);
1521 let n111 = lattice_hash(xi + 1, yi + 1, zi + 1, seed);
1522
1523 let nx00 = n000 + (n100 - n000) * u;
1524 let nx10 = n010 + (n110 - n010) * u;
1525 let nx01 = n001 + (n101 - n001) * u;
1526 let nx11 = n011 + (n111 - n011) * u;
1527
1528 let nxy0 = nx00 + (nx10 - nx00) * v;
1529 let nxy1 = nx01 + (nx11 - nx01) * v;
1530
1531 nxy0 + (nxy1 - nxy0) * w
1532}
1533
1534#[inline]
1535fn lattice_hash(x: i64, y: i64, z: i64, seed: u64) -> f64 {
1536 let mut h = seed
1537 ^ (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
1538 ^ (y as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9)
1539 ^ (z as u64).wrapping_mul(0x94D0_49BB_1331_11EB);
1540 h = (h ^ (h >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
1541 h = (h ^ (h >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
1542 h ^= h >> 31;
1543 let unit = (h >> 11) as f64 * (1.0 / ((1u64 << 53) as f64));
1544 unit * 2.0 - 1.0
1545}
1546
1547struct EmitterRenderProps<'a> {
1548 emitter_id: NodeId,
1549 style: ParticleStyleKind,
1550 tiny_sprite: Option<([f64; 2], SpriteImage)>,
1551 ngon_sides: f64,
1552 size_over_life: Option<&'a model::BezierSpline>,
1553 fade_in: f64,
1554 fade_out: f64,
1555 color_over_life: Option<Gradient>,
1556}
1557
1558fn collect_emitter_render_props<'a>(
1559 comp: &'a Comp,
1560 emitter_nodes: &HashMap<u64, NodeId>,
1561 particles: &[Particle],
1562 time: f64,
1563 expr: &ExprEngine,
1564) -> HashMap<u64, EmitterRenderProps<'a>> {
1565 let mut map = HashMap::new();
1566 for p in particles {
1567 if map.contains_key(&p.emitter_hash) {
1568 continue;
1569 }
1570 let Some(&emitter_id) = emitter_nodes.get(&p.emitter_hash) else {
1571 continue;
1572 };
1573 let Some(node) = comp.nodes.get(emitter_id.0) else {
1574 continue;
1575 };
1576 let style = match node.static_str("Style") {
1577 Some("ParticleStyleBitmap") => ParticleStyleKind::Bitmap,
1578 Some("ParticleStyleBlob") => ParticleStyleKind::Blob,
1579 Some("ParticleStyleNGon") => ParticleStyleKind::NGon,
1580 Some("ParticleStyleBrush") => ParticleStyleKind::Brush,
1581 _ => ParticleStyleKind::Point,
1582 };
1583 let size_over_life = node
1584 .inputs
1585 .get("ParticleStyle.SizeOverLife")
1586 .and_then(|b| b.source_op.as_deref())
1587 .and_then(|src| comp.splines.get(src));
1588 let fade_in = comp
1589 .eval_number(node, "ParticleStyle.FadeIn", time, 0.0, expr)
1590 .clamp(0.0, 1.0);
1591 let fade_out = comp
1592 .eval_number(node, "ParticleStyle.FadeOut", time, 1.0, expr)
1593 .clamp(0.0, 1.0);
1594 let color_over_life_on =
1595 comp.eval_number(node, "ParticleStyle.ColorOverLifeControls", time, 0.0, expr) > 0.5;
1596 let color_over_life = if color_over_life_on {
1597 comp.eval_gradient(node, "ParticleStyle.ColorOverLife", time)
1598 } else {
1599 None
1600 };
1601 map.insert(
1602 p.emitter_hash,
1603 EmitterRenderProps {
1604 emitter_id,
1605 style,
1606 tiny_sprite: tiny_background_sprite(comp, node, time, expr),
1607 ngon_sides: comp.eval_number(node, "ParticleStyleNGon.NGonSides", time, 5.0, expr).round().max(3.0),
1608 size_over_life,
1609 fade_in,
1610 fade_out,
1611 color_over_life,
1612 },
1613 );
1614 }
1615 map
1616}
1617
1618/// Solid sprite for a `Background` tool narrower than 16 px.
1619///
1620/// The engine evaluates such tools at comp size, so the particle uses the tool's nominal
1621/// `Width`/`Height` and its flat color directly.
1622fn tiny_background_sprite(
1623 comp: &Comp,
1624 emitter: &Node,
1625 t: f64,
1626 expr: &ExprEngine,
1627) -> Option<([f64; 2], SpriteImage)> {
1628 let src = emitter
1629 .connected_node("ParticleStyleBitmap.DropToolsHere")
1630 .and_then(|name| comp.find_node(name))
1631 .map(|id| &comp.nodes[id.0])
1632 .filter(|n| n.kind == "Background")?;
1633 let w = comp.eval_number(src, "Width", t, 0.0, expr);
1634 let h = comp.eval_number(src, "Height", t, 0.0, expr);
1635 if !(w >= 1.0 && h >= 1.0 && (w < 16.0 || h < 16.0)) {
1636 return None;
1637 }
1638 let channel = |name: &str, default: f64| comp.eval_number(src, name, t, default, expr).clamp(0.0, 1.0);
1639 let a = channel("TopLeftAlpha", 1.0);
1640 let px = |c: f64| (c * a * 255.0 + 0.5) as u8;
1641 let rgba = vec![
1642 px(channel("TopLeftRed", 0.0)),
1643 px(channel("TopLeftGreen", 0.0)),
1644 px(channel("TopLeftBlue", 0.0)),
1645 (a * 255.0 + 0.5) as u8,
1646 ];
1647 Some(([w, h], SpriteImage { size: [1, 1], rgba }))
1648}
1649
1650#[allow(clippy::too_many_arguments)]
1651fn rasterize_particles(
1652 out: &mut [u8],
1653 dims: [u32; 2],
1654 px_scale: f64,
1655 comp: &Comp,
1656 emitter_nodes: &HashMap<u64, NodeId>,
1657 particles: &[Particle],
1658 time: f64,
1659 expr: &ExprEngine,
1660 sprites: &HashMap<NodeId, SpriteImage>,
1661) {
1662 if particles.is_empty() {
1663 return;
1664 }
1665
1666 let props_map = collect_emitter_render_props(comp, emitter_nodes, particles, time, expr);
1667 let w = dims[0] as usize;
1668 let h = dims[1] as usize;
1669 let w_f = w as f64;
1670 let h_f = h as f64;
1671
1672 // Accumulate in linear-ish float premultiplied RGBA for clean blending, then pack to u8.
1673 let mut accum = vec![0.0f32; w * h * 4];
1674
1675 for p in particles {
1676 if !p.alive {
1677 continue;
1678 }
1679 let Some(props) = props_map.get(&p.emitter_hash) else {
1680 continue;
1681 };
1682
1683 let life_frac = (p.age / p.lifespan.max(1.0)).clamp(0.0, 1.0);
1684 // Fusion's SizeOverLife LUT maps 0.5 -> 1.0x (0.0 -> 0x, 1.0 -> 2x).
1685 let size_mult = props
1686 .size_over_life
1687 .map(|sp| (2.0 * sp.eval(life_frac)).max(0.0))
1688 .unwrap_or(1.0);
1689 let depth_scale = CAMERA_DISTANCE / (CAMERA_DISTANCE + p.pos[2]);
1690 if !(depth_scale > 0.0) {
1691 continue;
1692 }
1693 let size_world = p.size * size_mult * depth_scale;
1694 if size_world <= 1e-6 {
1695 continue;
1696 }
1697
1698 let mut fade = 1.0f64;
1699 if props.fade_in > 1e-6 && life_frac < props.fade_in {
1700 fade *= life_frac / props.fade_in;
1701 }
1702 if props.fade_out < 1.0 - 1e-6 && life_frac > props.fade_out {
1703 fade *= ((1.0 - life_frac) / (1.0 - props.fade_out)).max(0.0);
1704 }
1705
1706 let mut cr = p.color[0];
1707 let mut cg = p.color[1];
1708 let mut cb = p.color[2];
1709 let mut ca = p.color[3] * fade as f32;
1710 if let Some(grad) = &props.color_over_life {
1711 let g = grad.sample(life_frac);
1712 cr *= g[0];
1713 cg *= g[1];
1714 cb *= g[2];
1715 ca *= g[3];
1716 }
1717 ca = ca.clamp(0.0, 1.0);
1718 if ca <= 1e-4 {
1719 continue;
1720 }
1721
1722 // Fusion 2D particle coordinates: X in [-0.5, +0.5], Y-up with same unit scale as X.
1723 let cx = (p.pos[0] * depth_scale + 0.5) * w_f;
1724 let cy = h_f * 0.5 - p.pos[1] * depth_scale * w_f;
1725
1726 if props.style == ParticleStyleKind::Bitmap {
1727 let (sprite, nominal) = match &props.tiny_sprite {
1728 Some((nominal, sprite)) => (Some(sprite), *nominal),
1729 None => {
1730 let sprite = sprites.get(&props.emitter_id);
1731 (sprite, sprite.map_or([0.0; 2], |s| [s.size[0] as f64, s.size[1] as f64]))
1732 }
1733 };
1734 if let Some(sprite) = sprite.filter(|s| {
1735 s.size[0] > 0
1736 && s.size[1] > 0
1737 && s.rgba.len() >= (s.size[0] as usize).saturating_mul(s.size[1] as usize).saturating_mul(4)
1738 }) {
1739 draw_bitmap_particle(
1740 &mut accum,
1741 w,
1742 h,
1743 cx,
1744 cy,
1745 size_world * nominal[0] * px_scale,
1746 size_world * nominal[1] * px_scale,
1747 p.rot_z,
1748 [cr, cg, cb, ca],
1749 sprite,
1750 );
1751 continue;
1752 }
1753 }
1754
1755 match props.style {
1756 ParticleStyleKind::Point => {
1757 blend_pixel(&mut accum, w, h, cx.floor(), cy.floor(), [cr, cg, cb, ca]);
1758 }
1759 ParticleStyleKind::Blob | ParticleStyleKind::Bitmap => {
1760 let sigma = BLOB_SIGMA_PER_SIZE * size_world * px_scale;
1761 draw_soft_particle(&mut accum, w, h, cx, cy, sigma, [cr, cg, cb, ca], |_, _| 1.0);
1762 }
1763 ParticleStyleKind::NGon => {
1764 let sigma = BLOB_SIGMA_PER_SIZE * size_world * px_scale;
1765 let sides = props.ngon_sides;
1766 let spike_period = std::f64::consts::TAU / sides;
1767 let phase = std::f64::consts::FRAC_PI_2 + p.rot_z.to_radians();
1768 // Spike sharpness fitted to Fusion 21.1: alpha mass is 0.18/0.48/0.78 of a blob for 3/5/8 sides.
1769 let sharpness = 4.5 * (3.0 / sides).powf(2.8);
1770 draw_soft_particle(&mut accum, w, h, cx, cy, sigma, [cr, cg, cb, ca], |dx, dy| {
1771 // Distance to the nearest spike, as a fraction of half the spike period.
1772 let angle = (-dy).atan2(dx) - phase;
1773 let off = angle.rem_euclid(spike_period);
1774 let to_spike = off.min(spike_period - off);
1775 (1.0 - to_spike / (0.5 * spike_period)).powf(sharpness)
1776 });
1777 }
1778 ParticleStyleKind::Brush => {}
1779 }
1780 }
1781
1782 for (dst, &src) in out.iter_mut().zip(accum.iter()) {
1783 *dst = (src.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
1784 }
1785}
1786
1787#[allow(clippy::too_many_arguments)]
1788fn draw_bitmap_particle(
1789 accum: &mut [f32],
1790 w: usize,
1791 h: usize,
1792 cx: f64,
1793 cy: f64,
1794 draw_w: f64,
1795 draw_h: f64,
1796 rot_z_deg: f64,
1797 tint: [f32; 4],
1798 sprite: &SpriteImage,
1799) {
1800 if draw_w < 0.5 || draw_h < 0.5 {
1801 return;
1802 }
1803
1804 let hw = draw_w * 0.5;
1805 let hh = draw_h * 0.5;
1806 let theta = rot_z_deg.to_radians();
1807 let cos_t = theta.cos();
1808 let sin_t = theta.sin();
1809
1810 let rx = hw * cos_t.abs() + hh * sin_t.abs() + 1.0;
1811 let ry = hw * sin_t.abs() + hh * cos_t.abs() + 1.0;
1812
1813 let min_x = ((cx - rx).floor() as isize).max(0) as usize;
1814 let max_x = ((cx + rx).ceil() as isize).min(w as isize - 1);
1815 let min_y = ((cy - ry).floor() as isize).max(0) as usize;
1816 let max_y = ((cy + ry).ceil() as isize).min(h as isize - 1);
1817 if max_x < min_x as isize || max_y < min_y as isize {
1818 return;
1819 }
1820
1821 let inv_dw = 1.0 / draw_w;
1822 let inv_dh = 1.0 / draw_h;
1823 let edge_u = inv_dw * 0.5;
1824 let edge_v = inv_dh * 0.5;
1825 let sw_i = sprite.size[0] as usize;
1826 let sh_i = sprite.size[1] as usize;
1827
1828 for py in min_y..=(max_y as usize) {
1829 let dy = (py as f64 + 0.5) - cy;
1830 let row_off = py * w * 4;
1831 for px in min_x..=(max_x as usize) {
1832 let dx = (px as f64 + 0.5) - cx;
1833 // Inverse rotate into sprite local space (CCW in Y-up).
1834 let lx = dx * cos_t - dy * sin_t;
1835 let ly = dx * sin_t + dy * cos_t;
1836
1837 let u = lx * inv_dw + 0.5;
1838 let v = ly * inv_dh + 0.5;
1839 if u <= -edge_u || u >= 1.0 + edge_u || v <= -edge_v || v >= 1.0 + edge_v {
1840 continue;
1841 }
1842
1843 // Anti-aliased border coverage (0.5px feather at edges).
1844 let cov_u = ((u + edge_u) / (2.0 * edge_u))
1845 .min((1.0 + edge_u - u) / (2.0 * edge_u))
1846 .clamp(0.0, 1.0);
1847 let cov_v = ((v + edge_v) / (2.0 * edge_v))
1848 .min((1.0 + edge_v - v) / (2.0 * edge_v))
1849 .clamp(0.0, 1.0);
1850 let cov = (cov_u * cov_v) as f32;
1851 if cov <= 1e-4 {
1852 continue;
1853 }
1854
1855 let sample = sample_sprite_bilinear(
1856 &sprite.rgba,
1857 sw_i,
1858 sh_i,
1859 u.clamp(0.0, 1.0),
1860 v.clamp(0.0, 1.0),
1861 );
1862 let alpha_scale = tint[3] * cov;
1863 let pa = sample[3] * alpha_scale;
1864 if pa <= 1e-5 {
1865 continue;
1866 }
1867 let pr = sample[0] * tint[0] * alpha_scale;
1868 let pg = sample[1] * tint[1] * alpha_scale;
1869 let pb = sample[2] * tint[2] * alpha_scale;
1870
1871 let idx = row_off + px * 4;
1872 let inv_a = 1.0 - pa;
1873 accum[idx] = pr + accum[idx] * inv_a;
1874 accum[idx + 1] = pg + accum[idx + 1] * inv_a;
1875 accum[idx + 2] = pb + accum[idx + 2] * inv_a;
1876 accum[idx + 3] = pa + accum[idx + 3] * inv_a;
1877 }
1878 }
1879}
1880
1881#[inline]
1882fn sample_sprite_bilinear(rgba: &[u8], w: usize, h: usize, u: f64, v: f64) -> [f32; 4] {
1883 let fx = (u * w as f64 - 0.5).clamp(0.0, (w - 1) as f64);
1884 let fy = (v * h as f64 - 0.5).clamp(0.0, (h - 1) as f64);
1885 let x0 = fx.floor() as usize;
1886 let y0 = fy.floor() as usize;
1887 let x1 = (x0 + 1).min(w - 1);
1888 let y1 = (y0 + 1).min(h - 1);
1889 let tx = (fx - x0 as f64) as f32;
1890 let ty = (fy - y0 as f64) as f32;
1891
1892 let i00 = (y0 * w + x0) * 4;
1893 let i10 = (y0 * w + x1) * 4;
1894 let i01 = (y1 * w + x0) * 4;
1895 let i11 = (y1 * w + x1) * 4;
1896
1897 let w00 = (1.0 - tx) * (1.0 - ty) * (1.0 / 255.0);
1898 let w10 = tx * (1.0 - ty) * (1.0 / 255.0);
1899 let w01 = (1.0 - tx) * ty * (1.0 / 255.0);
1900 let w11 = tx * ty * (1.0 / 255.0);
1901
1902 [
1903 rgba[i00] as f32 * w00
1904 + rgba[i10] as f32 * w10
1905 + rgba[i01] as f32 * w01
1906 + rgba[i11] as f32 * w11,
1907 rgba[i00 + 1] as f32 * w00
1908 + rgba[i10 + 1] as f32 * w10
1909 + rgba[i01 + 1] as f32 * w01
1910 + rgba[i11 + 1] as f32 * w11,
1911 rgba[i00 + 2] as f32 * w00
1912 + rgba[i10 + 2] as f32 * w10
1913 + rgba[i01 + 2] as f32 * w01
1914 + rgba[i11 + 2] as f32 * w11,
1915 rgba[i00 + 3] as f32 * w00
1916 + rgba[i10 + 3] as f32 * w10
1917 + rgba[i01 + 3] as f32 * w01
1918 + rgba[i11 + 3] as f32 * w11,
1919 ]
1920}
1921
1922/// Source-over blends one premultiplied-accumulator pixel; out-of-bounds coordinates are ignored.
1923#[inline]
1924fn blend_pixel(accum: &mut [f32], w: usize, h: usize, x: f64, y: f64, color: [f32; 4]) {
1925 if x < 0.0 || y < 0.0 || x >= w as f64 || y >= h as f64 {
1926 return;
1927 }
1928 let pa = color[3].clamp(0.0, 1.0);
1929 if pa <= 1e-5 {
1930 return;
1931 }
1932 let idx = (y as usize * w + x as usize) * 4;
1933 let inv_a = 1.0 - pa;
1934 accum[idx] = color[0] * pa + accum[idx] * inv_a;
1935 accum[idx + 1] = color[1] * pa + accum[idx + 1] * inv_a;
1936 accum[idx + 2] = color[2] * pa + accum[idx + 2] * inv_a;
1937 accum[idx + 3] = pa + accum[idx + 3] * inv_a;
1938}
1939
1940/// Gaussian falloff sampled at pixel centers out to `4 sigma`, scaled by `shape(dx, dy)`.
1941#[allow(clippy::too_many_arguments)]
1942fn draw_soft_particle(
1943 accum: &mut [f32],
1944 w: usize,
1945 h: usize,
1946 cx: f64,
1947 cy: f64,
1948 sigma: f64,
1949 color: [f32; 4],
1950 shape: impl Fn(f64, f64) -> f64,
1951) {
1952 let bound = 4.0 * sigma;
1953 let min_x = ((cx - bound).floor() as isize).max(0);
1954 let max_x = ((cx + bound).ceil() as isize).min(w as isize - 1);
1955 let min_y = ((cy - bound).floor() as isize).max(0);
1956 let max_y = ((cy + bound).ceil() as isize).min(h as isize - 1);
1957 let inv_two_sigma_sq = 0.5 / (sigma * sigma);
1958 for py in min_y..=max_y {
1959 let dy = (py as f64 + 0.5) - cy;
1960 for px in min_x..=max_x {
1961 let dx = (px as f64 + 0.5) - cx;
1962 let cov = ((-(dx * dx + dy * dy) * inv_two_sigma_sq).exp() * shape(dx, dy)) as f32;
1963 blend_pixel(accum, w, h, px as f64, py as f64, [color[0], color[1], color[2], color[3] * cov]);
1964 }
1965 }
1966}
1967
1968#[cfg(test)]
1969mod tests {
1970 use super::*;
1971 use std::path::Path;
1972 use std::time::Instant;
1973
1974 fn make_white_sprite(size: u32) -> SpriteImage {
1975 SpriteImage {
1976 size: [size, size],
1977 rgba: vec![255u8; (size as usize) * (size as usize) * 4],
1978 }
1979 }
1980
1981 fn count_nonzero_alpha(buf: &[u8]) -> usize {
1982 buf.chunks_exact(4).filter(|px| px[3] > 0).count()
1983 }
1984
1985 #[test]
1986 fn test_particle_emitter_and_point_force_deterministic() {
1987 let comp_src = r#"
1988Composition {
1989 GlobalRange = { 0, 100 },
1990 RenderRange = { 0, 100 },
1991 Tools = {
1992 SpriteSrc = Background {
1993 Inputs = {
1994 Width = Input { Value = 32, },
1995 Height = Input { Value = 32, },
1996 },
1997 },
1998 pEmitter1SizeOverLife = LUTBezier {
1999 KeyColorSplines = {
2000 [0] = {
2001 [0] = { 0.5, RH = { 0.333, 0.5 }, Flags = { Linear = true } },
2002 [1] = { 0.25, LH = { 0.667, 0.25 }, Flags = { Linear = true } }
2003 }
2004 },
2005 },
2006 pEmitter1 = pEmitter {
2007 Inputs = {
2008 RandomSeed = Input { Value = 42, },
2009 Number = Input { Value = 15, },
2010 Lifespan = Input { Value = 60, },
2011 Region = Input { Value = FuID { "RectRgn" }, },
2012 ["RectRgn.Width"] = Input { Value = 0.6, },
2013 ["RectRgn.Height"] = Input { Value = 0.4, },
2014 Style = Input { Value = FuID { "ParticleStyleBitmap" }, },
2015 ["ParticleStyleBitmap.DropToolsHere"] = Input {
2016 SourceOp = "SpriteSrc",
2017 Source = "Output",
2018 },
2019 ["ParticleStyle.Red"] = Input { Value = 1, },
2020 ["ParticleStyle.Green"] = Input { Value = 0, },
2021 ["ParticleStyle.Blue"] = Input { Value = 0, },
2022 ["ParticleStyle.ColorVariance"] = Input { Value = 1, },
2023 ["ParticleStyle.GreenHigh"] = Input { Value = 1, },
2024 ["ParticleStyle.Size"] = Input { Value = 0.12, },
2025 ["ParticleStyle.SizeOverLife"] = Input {
2026 SourceOp = "pEmitter1SizeOverLife",
2027 Source = "Value",
2028 },
2029 ["ParticleStyle.FadeIn"] = Input { Value = 0.1, },
2030 ["ParticleStyle.FadeOut"] = Input { Value = 0.1, },
2031 },
2032 },
2033 pPointForce1 = pPointForce {
2034 Inputs = {
2035 Strength = Input { Value = -3.0, },
2036 Power = Input { Value = 0.5, },
2037 ["Translate.X"] = Input { Value = 0.0, },
2038 ["Translate.Y"] = Input { Value = 0.0, },
2039 Input = Input {
2040 SourceOp = "pEmitter1",
2041 Source = "Output",
2042 },
2043 },
2044 },
2045 pRender1 = pRender {
2046 Inputs = {
2047 Input = Input {
2048 SourceOp = "pPointForce1",
2049 Source = "Output",
2050 },
2051 },
2052 },
2053 },
2054}
2055"#;
2056
2057 let comp = Comp::from_fusion_str(comp_src).expect("parse synthetic particle comp");
2058 let render_id = comp.node_by_name["pRender1"];
2059 let emitter_id = comp.node_by_name["pEmitter1"];
2060 let sprite_id = comp.node_by_name["SpriteSrc"];
2061 let force_id = comp.node_by_name["pPointForce1"];
2062
2063 // Verify bitmap source discovery.
2064 let sources = collect_bitmap_sources(&comp, render_id);
2065 assert_eq!(sources, vec![(emitter_id, sprite_id)]);
2066
2067 let expr = ExprEngine::new();
2068 let mut sprites = HashMap::new();
2069 sprites.insert(emitter_id, make_white_sprite(16));
2070
2071 let dims = [160, 90];
2072
2073 // 1. Determinism: two fresh caches produce bit-identical buffers.
2074 let mut cache_a = ParticleCache::default();
2075 let mut cache_b = ParticleCache::default();
2076 let img_a = render_particles_2d(&mut cache_a, &comp, render_id, 25.0, dims, &expr, &sprites);
2077 let img_b = render_particles_2d(&mut cache_b, &comp, render_id, 25.0, dims, &expr, &sprites);
2078 assert_eq!(img_a, img_b, "particle render must be bit-identical across runs");
2079 assert!(
2080 count_nonzero_alpha(&img_a) > 50,
2081 "expected non-empty rendered particles"
2082 );
2083
2084 // 2. Force affects particle trajectories: bypassing pPointForce1 changes output.
2085 let mut comp_no_force = comp.clone();
2086 comp_no_force.nodes[force_id.0].bypassed = true;
2087 comp_no_force.revision += 1;
2088 let mut cache_no_force = ParticleCache::default();
2089 let img_no_force = render_particles_2d(
2090 &mut cache_no_force,
2091 &comp_no_force,
2092 render_id,
2093 25.0,
2094 dims,
2095 &expr,
2096 &sprites,
2097 );
2098 assert_ne!(
2099 img_a, img_no_force,
2100 "pPointForce must visibly change particle trajectories"
2101 );
2102
2103 // 3. Cache consistency & sequential speedup: stepping 25 -> 26 matches fresh 0 -> 26.
2104 let t_seq_start = Instant::now();
2105 let img_26_cached =
2106 render_particles_2d(&mut cache_a, &comp, render_id, 26.0, dims, &expr, &sprites);
2107 let seq_elapsed = t_seq_start.elapsed();
2108
2109 let mut fresh_cache = ParticleCache::default();
2110 let t_fresh_start = Instant::now();
2111 let img_26_fresh = render_particles_2d(
2112 &mut fresh_cache,
2113 &comp,
2114 render_id,
2115 26.0,
2116 dims,
2117 &expr,
2118 &sprites,
2119 );
2120 let fresh_elapsed = t_fresh_start.elapsed();
2121 assert_eq!(
2122 img_26_cached, img_26_fresh,
2123 "cached sequential step must match fresh simulation"
2124 );
2125 assert!(
2126 seq_elapsed <= fresh_elapsed * 2 + std::time::Duration::from_millis(5),
2127 "cached sequential step should be fast (seq={seq_elapsed:?}, fresh={fresh_elapsed:?})"
2128 );
2129
2130 cache_a.clear();
2131 assert!(cache_a.entries.is_empty());
2132 }
2133
2134 #[test]
2135 fn test_01_intro_particles_if_present() {
2136 let path = Path::new("/Volumes/Project/trees/fusion/01_intro.comp");
2137 if !path.exists() {
2138 return;
2139 }
2140
2141 let comp = Comp::from_fusion_file(path).expect("parse 01_intro.comp");
2142 let render_id = comp.node_by_name["pRender1"];
2143 let emitter_id = comp.node_by_name["pEmitter1"];
2144 let bc4_id = comp.node_by_name["BrightnessContrast4"];
2145
2146 let sources = collect_bitmap_sources(&comp, render_id);
2147 assert_eq!(
2148 sources,
2149 vec![(emitter_id, bc4_id)],
2150 "01_intro.comp pEmitter1 bitmap source should be BrightnessContrast4"
2151 );
2152
2153 let expr = ExprEngine::new();
2154 let mut sprites = HashMap::new();
2155 sprites.insert(emitter_id, make_white_sprite(32));
2156
2157 // In 01_intro.comp, TimeStretcher1 evaluates pRender1 at SourceTime = time / 25
2158 // (so comp f600 -> t=24, comp f1600 -> t=64).
2159 let ts_node = &comp.nodes[comp.node_by_name["TimeStretcher1"].0];
2160 let t_f600 = comp.eval_number(ts_node, "SourceTime", 600.0, 24.0, &expr);
2161 let t_f1600 = comp.eval_number(ts_node, "SourceTime", 1600.0, 64.0, &expr);
2162
2163 let dims = [320, 180];
2164 let mut cache = ParticleCache::default();
2165 let start = Instant::now();
2166 let buf_600 = render_particles_2d(&mut cache, &comp, render_id, t_f600, dims, &expr, &sprites);
2167 let buf_1600 =
2168 render_particles_2d(&mut cache, &comp, render_id, t_f1600, dims, &expr, &sprites);
2169 let elapsed = start.elapsed();
2170
2171 let nz_600 = count_nonzero_alpha(&buf_600);
2172 assert!(
2173 nz_600 > 0,
2174 "expected non-zero alpha pixels at f600 (SourceTime={t_f600})"
2175 );
2176 assert_eq!(
2177 buf_1600.len(),
2178 dims[0] as usize * dims[1] as usize * 4,
2179 "f1600 SourceTime={t_f1600}"
2180 );
2181 assert!(
2182 elapsed.as_secs_f64() < 2.0,
2183 "01_intro particle render should be fast, took {elapsed:?}"
2184 );
2185 }
2186
2187 #[test]
2188 fn test_pbounce_reverses_velocity_and_applies_friction() {
2189 let comp_src = r#"
2190Composition {
2191 GlobalRange = { 0, 20 },
2192 RenderRange = { 0, 20 },
2193 Tools = {
2194 pEmitter1 = pEmitter {
2195 Inputs = {
2196 Number = Input { Value = 1, },
2197 Lifespan = Input { Value = 50, },
2198 Velocity = Input { Value = 1.0, },
2199 Angle = Input { Value = -60, },
2200 ["SphereRgn.Size"] = Input { Value = 0, },
2201 ["SphereRgn.Translate.Y"] = Input { Value = 0.2, },
2202 },
2203 },
2204 pBounce1 = pBounce {
2205 Inputs = {
2206 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
2207 Elasticity = Input { Value = 0.8, },
2208 Friction = Input { Value = 0.25, },
2209 Spin = Input { Value = 3.0, },
2210 Region = Input { Value = FuID { "CubeRgn" }, },
2211 ["CubeRgn.Translate.Y"] = Input { Value = -0.25, },
2212 ["CubeRgn.Width"] = Input { Value = 2.0, },
2213 ["CubeRgn.Height"] = Input { Value = 0.5, },
2214 ["CubeRgn.Depth"] = Input { Value = 2.0, },
2215 },
2216 },
2217 pRender1 = pRender {
2218 Inputs = {
2219 Input = Input { SourceOp = "pBounce1", Source = "Output", },
2220 },
2221 },
2222 },
2223}
2224"#;
2225 let comp = Comp::from_fusion_str(comp_src).expect("parse pBounce comp");
2226 let render_id = comp.node_by_name["pRender1"];
2227 let plan = build_particle_plan(&comp, render_id);
2228 let expr = ExprEngine::new();
2229 let mut state = SimState::default();
2230
2231 // Step until the first emitted particle (born at f=0 at y=0.2, vy≈-0.0866, vx=0.05)
2232 // crosses the floor at y=0.0 around frame 3.
2233 for f in 0..=4 {
2234 step_simulation(&mut state, &comp, &plan, f, &expr);
2235 }
2236 let first = state.particles.first().expect("particle emitted");
2237 let init_vx = 0.1 * (-60.0_f64).to_radians().cos();
2238 let init_vy = 0.1 * (-60.0_f64).to_radians().sin();
2239 assert!(
2240 first.vel[1] > 0.0,
2241 "pBounce should reverse downward Y velocity (got vy={})",
2242 first.vel[1]
2243 );
2244 assert!(
2245 (first.vel[1] - (-init_vy * 0.8)).abs() < 1e-4,
2246 "expected reflected vy={}, got {}",
2247 -init_vy * 0.8,
2248 first.vel[1]
2249 );
2250 assert!(
2251 (first.vel[0] - init_vx * 0.75).abs() < 1e-4,
2252 "expected friction-damped vx={}, got {}",
2253 init_vx * 0.75,
2254 first.vel[0]
2255 );
2256 assert!(first.spin_z.abs() > 0.5, "expected Spin impulse on bounce");
2257 assert!(first.pos[1] > 0.0, "bounced particle should be above floor y=0");
2258 }
2259
2260 /// Single-particle comp: `Number` is a spline that is 1 at frame 0 and 0 afterwards.
2261 fn single_particle_comp(emitter_inputs: &str, forces: &str, last_node: &str) -> Comp {
2262 let src = format!(
2263 r#"
2264Composition {{
2265 GlobalRange = {{ 0, 100 }},
2266 RenderRange = {{ 0, 100 }},
2267 Tools = {{
2268 EN = BezierSpline {{
2269 KeyFrames = {{
2270 [0] = {{ 1, Flags = {{ Linear = true }} }},
2271 [1] = {{ 0, Flags = {{ Linear = true }} }}
2272 }}
2273 }},
2274 pEmitter1 = pEmitter {{
2275 Inputs = {{
2276 Number = Input {{ SourceOp = "EN", Source = "Value", }},
2277 Lifespan = Input {{ Value = 100, }},
2278 ["SphereRgn.Size"] = Input {{ Value = 0, }},
2279 {emitter_inputs}
2280 }},
2281 }},
2282 {forces}
2283 pRender1 = pRender {{
2284 Inputs = {{
2285 Input = Input {{ SourceOp = "{last_node}", Source = "Output", }},
2286 }},
2287 }},
2288 }},
2289}}
2290"#
2291 );
2292 Comp::from_fusion_str(&src).expect("parse single-particle comp")
2293 }
2294
2295 fn render(comp: &Comp, time: f64, dims: [u32; 2], sprites: &HashMap<NodeId, SpriteImage>) -> Vec<u8> {
2296 let mut cache = ParticleCache::default();
2297 render_particles_2d(&mut cache, comp, comp.node_by_name["pRender1"], time, dims, &ExprEngine::new(), sprites)
2298 }
2299
2300 /// `(x, y, alpha)` of every pixel with non-zero alpha.
2301 fn lit(buf: &[u8], width: usize) -> Vec<(usize, usize, u8)> {
2302 buf.chunks_exact(4)
2303 .enumerate()
2304 .filter(|(_, px)| px[3] > 0)
2305 .map(|(i, px)| (i % width, i / width, px[3]))
2306 .collect()
2307 }
2308
2309 fn alpha_mass(buf: &[u8]) -> f64 {
2310 buf.chunks_exact(4).map(|px| px[3] as f64 / 255.0).sum()
2311 }
2312
2313 #[test]
2314 fn point_style_is_one_pixel_regardless_of_size() {
2315 let comp = single_particle_comp(r#"["ParticleStyle.Size"] = Input { Value = 5, },"#, "", "pEmitter1");
2316 let buf = render(&comp, 0.0, [200, 100], &HashMap::new());
2317 assert_eq!(lit(&buf, 200), vec![(100, 50, 255)]);
2318 }
2319
2320 #[test]
2321 fn blob_is_gaussian_with_sigma_per_size_unit() {
2322 let comp = single_particle_comp(
2323 r#"Style = Input { Value = FuID { "ParticleStyleBlob" }, }, ["ParticleStyle.Size"] = Input { Value = 2, },"#,
2324 "",
2325 "pEmitter1",
2326 );
2327 // Fusion 21.1: Size 2 blob has alpha mass ~276 (= 2*pi*(2*3.316)^2).
2328 let mass = alpha_mass(&render(&comp, 0.0, [256, 256], &HashMap::new()));
2329 assert!((mass - 276.0).abs() < 8.0, "blob mass {mass}");
2330 }
2331
2332 #[test]
2333 fn newborn_moves_once_at_tenth_width_velocity() {
2334 let comp = single_particle_comp(
2335 r#"VelocityControls = Input { Value = 1, }, Velocity = Input { Value = 1, }, Angle = Input { Value = 0, },"#,
2336 "",
2337 "pEmitter1",
2338 );
2339 let at = |t: f64| lit(&render(&comp, t, [200, 100], &HashMap::new()), 200)[0].0;
2340 assert_eq!(at(0.0), 120);
2341 assert_eq!(at(2.0), 160);
2342 }
2343
2344 #[test]
2345 fn directional_force_accelerates_down_by_strength_over_one_hundred() {
2346 let comp = single_particle_comp(
2347 "",
2348 r#"pDirectionalForce1 = pDirectionalForce {
2349 Inputs = {
2350 Strength = Input { Value = 1, },
2351 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
2352 },
2353 },"#,
2354 "pDirectionalForce1",
2355 );
2356 // y(f) = 0.01 * f(f+1)/2 widths below the spawn point.
2357 let buf = render(&comp, 4.0, [1000, 1000], &HashMap::new());
2358 assert_eq!(lit(&buf, 1000), vec![(500, 600, 255)]);
2359 }
2360
2361 #[test]
2362 fn particle_lives_while_age_is_below_lifespan() {
2363 let comp = single_particle_comp(r#"Lifespan = Input { Value = 3, },"#, "", "pEmitter1");
2364 let count = |t: f64| lit(&render(&comp, t, [64, 64], &HashMap::new()), 64).len();
2365 assert_eq!((count(0.0), count(2.0), count(3.0)), (1, 1, 0));
2366 }
2367
2368 #[test]
2369 fn fade_out_starts_at_fade_out_fraction_of_life() {
2370 let comp = single_particle_comp(
2371 r#"Lifespan = Input { Value = 20, }, Style = Input { Value = FuID { "ParticleStyleBlob" }, },
2372 ["ParticleStyle.Size"] = Input { Value = 2, }, ["ParticleStyle.FadeOut"] = Input { Value = 0.5, },"#,
2373 "",
2374 "pEmitter1",
2375 );
2376 let mass = |t: f64| alpha_mass(&render(&comp, t, [256, 256], &HashMap::new()));
2377 assert!((mass(15.0) / mass(10.0) - 0.5).abs() < 0.02);
2378 }
2379
2380 #[test]
2381 fn bitmap_width_is_size_times_sprite_pixels() {
2382 let comp = single_particle_comp(
2383 r#"Style = Input { Value = FuID { "ParticleStyleBitmap" }, }, ["ParticleStyle.Size"] = Input { Value = 2, },"#,
2384 "",
2385 "pEmitter1",
2386 );
2387 let mut sprites = HashMap::new();
2388 sprites.insert(comp.node_by_name["pEmitter1"], make_white_sprite(4));
2389 let pixels = lit(&render(&comp, 0.0, [200, 100], &sprites), 200);
2390 let (min_x, max_x) = pixels.iter().fold((usize::MAX, 0), |(lo, hi), &(x, _, _)| (lo.min(x), hi.max(x)));
2391 assert!((8..=9).contains(&(max_x - min_x + 1)), "bitmap width {}", max_x - min_x + 1);
2392 }
2393
2394 #[test]
2395 fn default_region_is_sphere_of_diameter_one_tenth_width() {
2396 let comp = Comp::from_fusion_str("Composition { Tools = { pEmitter1 = pEmitter { Inputs = { }, }, }, }")
2397 .expect("parse bare emitter");
2398 let node = &comp.nodes[comp.node_by_name["pEmitter1"].0];
2399 match RegionSpec::from_node(&comp, node, 0.0, &ExprEngine::new()) {
2400 RegionSpec::Sphere { radius, .. } => assert!((radius - 0.05).abs() < 1e-12),
2401 _ => panic!("default region must be a sphere"),
2402 }
2403 }
2404
2405 #[test]
2406 fn depth_scales_screen_position_by_camera_distance() {
2407 let comp = single_particle_comp(
2408 r#"["SphereRgn.Translate.X"] = Input { Value = 0.2, }, ["SphereRgn.Translate.Z"] = Input { Value = 0.9722222222222222, },"#,
2409 "",
2410 "pEmitter1",
2411 );
2412 // z equal to the camera distance halves the projected offset: x = (0.2 * 0.5 + 0.5) * 1000.
2413 let buf = render(&comp, 0.0, [1000, 1000], &HashMap::new());
2414 assert_eq!(lit(&buf, 1000), vec![(600, 500, 255)]);
2415 }
2416
2417 #[test]
2418 fn particle_cache_advances_past_600_incrementally_and_scrubs_with_snapshots() {
2419 let comp_src = r#"
2420Composition {
2421 GlobalRange = { 0, 800 },
2422 RenderRange = { 0, 800 },
2423 Tools = {
2424 pEmitter1 = pEmitter {
2425 Inputs = {
2426 RandomSeed = Input { Value = 7, },
2427 Number = Input { Value = 2, },
2428 Lifespan = Input { Value = 25, },
2429 Velocity = Input { Value = 0.2, },
2430 VelocityVariance = Input { Value = 0.1, },
2431 AngleVariance = Input { Value = 180, },
2432 },
2433 },
2434 pRender1 = pRender {
2435 Inputs = {
2436 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
2437 },
2438 },
2439 },
2440}
2441"#;
2442 let comp = Comp::from_fusion_str(comp_src).expect("parse particle comp");
2443 let render_id = comp.node_by_name["pRender1"];
2444 let expr = ExprEngine::new();
2445 let sprites = HashMap::new();
2446 let dims = [64, 64];
2447
2448 let mut cache = ParticleCache::default();
2449 let mut last_img = Vec::new();
2450 for f in 580..=625 {
2451 last_img = render_particles_2d(&mut cache, &comp, render_id, f as f64, dims, &expr, &sprites);
2452 }
2453
2454 let key = (
2455 "pRender1".to_owned(),
2456 particle_subgraph_hash(&comp, render_id, 0),
2457 );
2458 let cached = cache.entries.get(&key).expect("cached entry");
2459 assert_eq!(cached.base_start, 0);
2460 assert_eq!(cached.current_frame, 625);
2461 assert!(cached.snapshots.contains_key(&600), "expected snapshot at frame 600");
2462
2463 // Scrubbing back to frame 605 restores snapshot 600 and matches direct render at 605.
2464 let scrub_605 = render_particles_2d(&mut cache, &comp, render_id, 605.0, dims, &expr, &sprites);
2465 let mut fresh_cache = ParticleCache::default();
2466 let fresh_605 = render_particles_2d(&mut fresh_cache, &comp, render_id, 605.0, dims, &expr, &sprites);
2467 assert_eq!(scrub_605, fresh_605, "scrubbed frame 605 must match fresh simulation");
2468
2469 let mut fresh_625_cache = ParticleCache::default();
2470 let fresh_625 = render_particles_2d(&mut fresh_625_cache, &comp, render_id, 625.0, dims, &expr, &sprites);
2471 assert_eq!(last_img, fresh_625, "incremental advance past 600 must match fresh simulation");
2472 }
2473
2474 #[test]
2475 fn particle_cache_ignores_unrelated_comp_edits_and_node_id_shifts() {
2476 let with_unrelated = r#"
2477Composition {
2478 GlobalRange = { 0, 100 },
2479 RenderRange = { 0, 100 },
2480 Tools = {
2481 UnrelatedBg = Background {
2482 Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, },
2483 },
2484 pEmitter1 = pEmitter {
2485 Inputs = {
2486 RandomSeed = Input { Value = 19, },
2487 Number = Input { Value = 8, },
2488 Lifespan = Input { Value = 40, },
2489 Velocity = Input { Value = 0.5, },
2490 VelocityVariance = Input { Value = 0.25, },
2491 AngleVariance = Input { Value = 180, },
2492 },
2493 },
2494 pRender1 = pRender {
2495 Inputs = {
2496 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
2497 },
2498 },
2499 },
2500}
2501"#;
2502 let without_unrelated = r#"
2503Composition {
2504 GlobalRange = { 0, 100 },
2505 RenderRange = { 0, 100 },
2506 Tools = {
2507 pEmitter1 = pEmitter {
2508 Inputs = {
2509 RandomSeed = Input { Value = 19, },
2510 Number = Input { Value = 8, },
2511 Lifespan = Input { Value = 40, },
2512 Velocity = Input { Value = 0.5, },
2513 VelocityVariance = Input { Value = 0.25, },
2514 AngleVariance = Input { Value = 180, },
2515 },
2516 },
2517 pRender1 = pRender {
2518 Inputs = {
2519 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
2520 },
2521 },
2522 },
2523}
2524"#;
2525 let mut comp_a = Comp::from_fusion_str(with_unrelated).expect("parse comp_a");
2526 let comp_b = Comp::from_fusion_str(without_unrelated).expect("parse comp_b");
2527 let ra = comp_a.node_by_name["pRender1"];
2528 let rb = comp_b.node_by_name["pRender1"];
2529 assert_ne!(ra, rb, "deleting UnrelatedBg should shift NodeIds");
2530
2531 let expr = ExprEngine::new();
2532 let sprites = HashMap::new();
2533 let dims = [64, 64];
2534
2535 let mut cache_a = ParticleCache::default();
2536 let img_a_20 = render_particles_2d(&mut cache_a, &comp_a, ra, 20.0, dims, &expr, &sprites);
2537
2538 // Bumping comp.revision (simulating unrelated node edit) reuses cached simulation.
2539 comp_a.revision += 99;
2540 let hash_before = particle_subgraph_hash(&comp_a, ra, 0);
2541 let hash_after_del = particle_subgraph_hash(&comp_b, rb, 0);
2542 assert_eq!(hash_before, hash_after_del, "subgraph hash must ignore NodeId shifts and unrelated nodes");
2543
2544 let mut cache_b = ParticleCache::default();
2545 let img_b_20 = render_particles_2d(&mut cache_b, &comp_b, rb, 20.0, dims, &expr, &sprites);
2546 assert_eq!(img_a_20, img_b_20, "deleting an unrelated node must not re-randomize particles");
2547
2548 // Stepping comp_b using cache_a (which has old NodeIds!) must still match fresh comp_b at frame 21.
2549 let img_a_to_b_21 = render_particles_2d(&mut cache_a, &comp_b, rb, 21.0, dims, &expr, &sprites);
2550 let mut fresh_b = ParticleCache::default();
2551 let img_b_21 = render_particles_2d(&mut fresh_b, &comp_b, rb, 21.0, dims, &expr, &sprites);
2552 assert_eq!(img_a_to_b_21, img_b_21);
2553 }
2554
2555 #[test]
2556 fn cyclic_expression_modifier_does_not_stack_overflow() {
2557 let comp_src = r#"
2558Composition {
2559 GlobalRange = { 0, 20 },
2560 RenderRange = { 0, 20 },
2561 Tools = ordered() {
2562 Expr1 = Expression {
2563 Inputs = {
2564 n1 = Input { SourceOp = "Expr1", Source = "NumberResult", },
2565 NumberExpression = Input { Value = "n1 + 4", },
2566 },
2567 },
2568 pEmitter1 = pEmitter {
2569 Inputs = {
2570 RandomSeed = Input { Value = 7, },
2571 Number = Input { SourceOp = "Expr1", Source = "NumberResult", },
2572 Lifespan = Input { Value = 15, },
2573 Velocity = Input { Value = 0.2, },
2574 },
2575 },
2576 pRender1 = pRender {
2577 Inputs = {
2578 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
2579 },
2580 },
2581 },
2582}
2583"#;
2584 let comp = Comp::from_fusion_str(comp_src).expect("parse cyclic Expr1 comp");
2585 assert!(comp.expression_modifiers.contains_key("Expr1"));
2586 let pr = comp.find_node("pRender1").expect("find pRender1");
2587 let expr = ExprEngine::new();
2588 let sprites = HashMap::new();
2589 let mut cache = ParticleCache::default();
2590
2591 // Both subgraph hashing and particle evaluation must terminate cleanly without overflowing.
2592 let h1 = particle_subgraph_hash(&comp, pr, 0);
2593 let h2 = particle_subgraph_hash(&comp, pr, 0);
2594 assert_eq!(h1, h2);
2595
2596 let img = render_particles_2d(&mut cache, &comp, pr, 5.0, [64, 64], &expr, &sprites);
2597 assert_eq!(img.len(), 64 * 64 * 4);
2598 }
2599}
crates/engine/src/particles/plan.rs created+395
...@@ -0,0 +1,395 @@
1//! Particle graph traversal, bitmap source discovery, and deterministic subgraph hashing.
2
3use std::collections::hash_map::DefaultHasher;
4use std::collections::{HashMap, HashSet};
5use std::hash::{Hash, Hasher};
6
7use model::{BezierSpline, Comp, Gradient, InputBinding, Node, NodeId, ParamValue};
8
9use super::stable_name_hash;
10
11/// Returns true if `kind` is a Fusion particle stream operator.
12pub(super) fn is_particle_node_kind(kind: &str) -> bool {
13 matches!(
14 kind,
15 "pRender"
16 | "pEmitter"
17 | "pPointForce"
18 | "pDirectionalForce"
19 | "pTurbulence"
20 | "pDrag"
21 | "pFriction"
22 | "pKill"
23 | "pMerge"
24 | "pBounce"
25 | "pVortex"
26 | "pFlock"
27 | "pAvoid"
28 | "pSpawn"
29 | "pChangeStyle"
30 | "pCustom"
31 | "pCustomForce"
32 | "pGradientForce"
33 | "pImageEmitter"
34 ) || (kind.starts_with('p')
35 && kind
36 .as_bytes()
37 .get(1)
38 .is_some_and(|b| b.is_ascii_uppercase()))
39}
40
41/// Returns the particle stream input node IDs of `node` in deterministic order.
42pub(super) fn particle_stream_inputs(comp: &Comp, node: &Node) -> Vec<NodeId> {
43 let mut ports: Vec<&str> = Vec::new();
44 for key in node.inputs.keys() {
45 if key == "Input"
46 || key
47 .strip_prefix("Input")
48 .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))
49 {
50 ports.push(key.as_str());
51 }
52 }
53 ports.sort_unstable();
54
55 let mut out = Vec::with_capacity(ports.len());
56 for port in ports {
57 if let Some(src_name) = node.connected_node(port) {
58 if let Some(&src_id) = comp.node_by_name.get(src_name) {
59 out.push(src_id);
60 }
61 }
62 }
63 out
64}
65
66/// Walks upstream from `render_node` through particle operators and returns every
67/// `(emitter_node_id, sprite_source_node_id)` pair for `pEmitter` nodes whose
68/// `ParticleStyleBitmap.DropToolsHere` input is connected.
69pub fn collect_bitmap_sources(comp: &Comp, render_node: NodeId) -> Vec<(NodeId, NodeId)> {
70 let mut visited = HashSet::new();
71 let mut out = Vec::new();
72 collect_bitmap_sources_dfs(comp, render_node, &mut visited, &mut out);
73 out
74}
75
76fn collect_bitmap_sources_dfs(
77 comp: &Comp,
78 node_id: NodeId,
79 visited: &mut HashSet<NodeId>,
80 out: &mut Vec<(NodeId, NodeId)>,
81) {
82 if !visited.insert(node_id) {
83 return;
84 }
85 let Some(node) = comp.nodes.get(node_id.0) else {
86 return;
87 };
88 if !is_particle_node_kind(&node.kind) {
89 return;
90 }
91
92 if node.kind == "pEmitter" {
93 if let Some(src_name) = node.connected_node("ParticleStyleBitmap.DropToolsHere") {
94 if let Some(&src_id) = comp.node_by_name.get(src_name) {
95 out.push((node_id, src_id));
96 }
97 }
98 }
99
100 for up_id in particle_stream_inputs(comp, node) {
101 collect_bitmap_sources_dfs(comp, up_id, visited, out);
102 }
103}
104
105/// Flattened, topologically-ordered particle graph upstream of a `pRender` node.
106pub(super) struct ParticlePlan {
107 pub(super) emitters: Vec<(NodeId, u64)>,
108 /// Forces/modifiers in topological order along with the set of upstream
109 /// emitter name hashes whose particles flow through each modifier.
110 pub(super) modifiers: Vec<(NodeId, HashSet<u64>)>,
111 pub(super) emitter_nodes: HashMap<u64, NodeId>,
112}
113
114pub(super) fn build_particle_plan(comp: &Comp, render_node: NodeId) -> ParticlePlan {
115 let mut visited = HashSet::new();
116 let mut emitters = Vec::new();
117 let mut modifiers = Vec::new();
118 let mut upstream_emitters: HashMap<NodeId, HashSet<u64>> = HashMap::new();
119 let mut emitter_nodes = HashMap::new();
120
121 build_plan_dfs(
122 comp,
123 render_node,
124 &mut visited,
125 &mut emitters,
126 &mut modifiers,
127 &mut upstream_emitters,
128 &mut emitter_nodes,
129 );
130
131 ParticlePlan {
132 emitters,
133 modifiers,
134 emitter_nodes,
135 }
136}
137
138fn build_plan_dfs(
139 comp: &Comp,
140 node_id: NodeId,
141 visited: &mut HashSet<NodeId>,
142 emitters: &mut Vec<(NodeId, u64)>,
143 modifiers: &mut Vec<(NodeId, HashSet<u64>)>,
144 upstream_emitters: &mut HashMap<NodeId, HashSet<u64>>,
145 emitter_nodes: &mut HashMap<u64, NodeId>,
146) -> HashSet<u64> {
147 if let Some(cached) = upstream_emitters.get(&node_id) {
148 return cached.clone();
149 }
150 if !visited.insert(node_id) {
151 return HashSet::new();
152 }
153
154 let Some(node) = comp.nodes.get(node_id.0) else {
155 return HashSet::new();
156 };
157 if !is_particle_node_kind(&node.kind) {
158 return HashSet::new();
159 }
160
161 let mut scope = HashSet::new();
162 for up_id in particle_stream_inputs(comp, node) {
163 let up_set = build_plan_dfs(
164 comp,
165 up_id,
166 visited,
167 emitters,
168 modifiers,
169 upstream_emitters,
170 emitter_nodes,
171 );
172 scope.extend(up_set);
173 }
174
175 if node.kind == "pEmitter" {
176 if !node.bypassed {
177 let emitter_hash = stable_name_hash(&node.name);
178 emitters.push((node_id, emitter_hash));
179 emitter_nodes.insert(emitter_hash, node_id);
180 scope.insert(emitter_hash);
181 }
182 } else if !node.bypassed
183 && matches!(
184 node.kind.as_str(),
185 "pPointForce"
186 | "pDirectionalForce"
187 | "pTurbulence"
188 | "pDrag"
189 | "pFriction"
190 | "pKill"
191 | "pBounce"
192 )
193 {
194 modifiers.push((node_id, scope.clone()));
195 }
196
197 upstream_emitters.insert(node_id, scope.clone());
198 scope
199}
200
201fn hash_spline(spline: &BezierSpline, h: &mut DefaultHasher) {
202 spline.name.hash(h);
203 spline.keyframes.len().hash(h);
204 for kf in &spline.keyframes {
205 kf.time.to_bits().hash(h);
206 kf.value.to_bits().hash(h);
207 if let Some([lx, ly]) = kf.lh {
208 1u8.hash(h);
209 lx.to_bits().hash(h);
210 ly.to_bits().hash(h);
211 } else {
212 0u8.hash(h);
213 }
214 if let Some([rx, ry]) = kf.rh {
215 1u8.hash(h);
216 rx.to_bits().hash(h);
217 ry.to_bits().hash(h);
218 } else {
219 0u8.hash(h);
220 }
221 [
222 kf.flags.linear,
223 kf.flags.step_in,
224 kf.flags.step_out,
225 kf.flags.loop_after,
226 kf.flags.loop_rel,
227 kf.flags.ping_pong,
228 kf.flags.locked_y,
229 ]
230 .hash(h);
231 (kf.handle_mode as u8).hash(h);
232 }
233}
234
235fn hash_gradient(grad: &Gradient, h: &mut DefaultHasher) {
236 grad.stops.len().hash(h);
237 for stop in &grad.stops {
238 stop.pos.to_bits().hash(h);
239 for c in stop.rgba {
240 c.to_bits().hash(h);
241 }
242 }
243}
244
245fn hash_input_binding(
246 comp: &Comp,
247 binding: &InputBinding,
248 visited_mods: &mut HashSet<String>,
249 h: &mut DefaultHasher,
250) {
251 binding.source_output.hash(h);
252 binding.expression.hash(h);
253 match &binding.value {
254 None => 0u8.hash(h),
255 Some(ParamValue::Number(v)) => {
256 1u8.hash(h);
257 v.to_bits().hash(h);
258 }
259 Some(ParamValue::Point([x, y])) => {
260 2u8.hash(h);
261 x.to_bits().hash(h);
262 y.to_bits().hash(h);
263 }
264 Some(ParamValue::Text(s)) => {
265 3u8.hash(h);
266 s.hash(h);
267 }
268 Some(ParamValue::FuId(s)) => {
269 4u8.hash(h);
270 s.hash(h);
271 }
272 Some(ParamValue::Gradient(g)) => {
273 5u8.hash(h);
274 hash_gradient(g, h);
275 }
276 Some(ParamValue::Raw(raw)) => {
277 6u8.hash(h);
278 format!("{raw:?}").hash(h);
279 }
280 }
281 binding.source_op.hash(h);
282 if let Some(op) = &binding.source_op {
283 if let Some(sp) = comp.splines.get(op) {
284 hash_spline(sp, h);
285 }
286 if let Some(pp) = comp.poly_paths.get(op) {
287 pp.name.hash(h);
288 pp.displacement_op.hash(h);
289 pp.displacement_value.to_bits().hash(h);
290 pp.closed.hash(h);
291 pp.points.len().hash(h);
292 for pt in &pp.points {
293 pt.x.to_bits().hash(h);
294 pt.y.to_bits().hash(h);
295 pt.lx.to_bits().hash(h);
296 pt.ly.to_bits().hash(h);
297 pt.rx.to_bits().hash(h);
298 pt.ry.to_bits().hash(h);
299 pt.linear.hash(h);
300 }
301 if let Some(disp_op) = &pp.displacement_op {
302 if let Some(sp) = comp.splines.get(disp_op) {
303 hash_spline(sp, h);
304 }
305 }
306 }
307 if let Some(sh) = comp.shakes.get(op) {
308 if visited_mods.insert(op.clone()) {
309 hash_sorted_inputs(comp, &sh.inputs, visited_mods, h);
310 visited_mods.remove(op);
311 } else {
312 0xC1C1_u16.hash(h);
313 op.hash(h);
314 }
315 }
316 if let Some(ex) = comp.expression_modifiers.get(op) {
317 if visited_mods.insert(op.clone()) {
318 hash_sorted_inputs(comp, &ex.inputs, visited_mods, h);
319 visited_mods.remove(op);
320 } else {
321 0xC1C2_u16.hash(h);
322 op.hash(h);
323 }
324 }
325 if let Some(gm) = comp.gradient_modifiers.get(op) {
326 gm.len().hash(h);
327 for (t, g) in gm {
328 t.to_bits().hash(h);
329 hash_gradient(g, h);
330 }
331 }
332 }
333}
334
335fn hash_sorted_inputs(
336 comp: &Comp,
337 inputs: &HashMap<String, InputBinding>,
338 visited_mods: &mut HashSet<String>,
339 h: &mut DefaultHasher,
340) {
341 let mut keys: Vec<&String> = inputs.keys().collect();
342 keys.sort_unstable();
343 keys.len().hash(h);
344 for k in keys {
345 k.hash(h);
346 hash_input_binding(comp, &inputs[k], visited_mods, h);
347 }
348}
349
350/// Content hash of the particle simulation subgraph upstream of `render_node`.
351/// Unrelated edits outside the particle branch leave this hash unchanged.
352pub(super) fn particle_subgraph_hash(comp: &Comp, render_node: NodeId, base_start: i64) -> u64 {
353 fn dfs(
354 comp: &Comp,
355 node_id: NodeId,
356 is_root: bool,
357 visited: &mut HashSet<NodeId>,
358 visited_mods: &mut HashSet<String>,
359 h: &mut DefaultHasher,
360 ) {
361 if !visited.insert(node_id) {
362 return;
363 }
364 let Some(node) = comp.nodes.get(node_id.0) else {
365 return;
366 };
367 if !is_particle_node_kind(&node.kind) {
368 return;
369 }
370 node.name.hash(h);
371 node.kind.hash(h);
372 node.bypassed.hash(h);
373
374 let mut keys: Vec<&String> = node.inputs.keys().collect();
375 keys.sort_unstable();
376 for k in keys {
377 // `pRender.Width` and bitmap drop target only affect rasterization, not simulation state.
378 if (is_root && k == "Width") || k == "ParticleStyleBitmap.DropToolsHere" {
379 continue;
380 }
381 k.hash(h);
382 hash_input_binding(comp, &node.inputs[k], visited_mods, h);
383 }
384 for up_id in particle_stream_inputs(comp, node) {
385 dfs(comp, up_id, false, visited, visited_mods, h);
386 }
387 }
388
389 let mut h = DefaultHasher::new();
390 base_start.hash(&mut h);
391 let mut visited = HashSet::new();
392 let mut visited_mods = HashSet::new();
393 dfs(comp, render_node, true, &mut visited, &mut visited_mods, &mut h);
394 h.finish()
395}
crates/engine/src/particles/raster.rs created+430
...@@ -0,0 +1,430 @@
1//! 2D particle rasterization (points, blobs, NGons, and bilinear bitmap sprites).
2
3use std::collections::HashMap;
4
5use model::{Comp, ExprEngine, Gradient, Node, NodeId};
6
7use super::{
8 BLOB_SIGMA_PER_SIZE, CAMERA_DISTANCE, Particle, ParticleStyleKind, SpriteImage,
9};
10
11struct EmitterRenderProps<'a> {
12 emitter_id: NodeId,
13 style: ParticleStyleKind,
14 tiny_sprite: Option<([f64; 2], SpriteImage)>,
15 ngon_sides: f64,
16 size_over_life: Option<&'a model::BezierSpline>,
17 fade_in: f64,
18 fade_out: f64,
19 color_over_life: Option<Gradient>,
20}
21
22fn collect_emitter_render_props<'a>(
23 comp: &'a Comp,
24 emitter_nodes: &HashMap<u64, NodeId>,
25 particles: &[Particle],
26 time: f64,
27 expr: &ExprEngine,
28) -> HashMap<u64, EmitterRenderProps<'a>> {
29 let mut map = HashMap::new();
30 for p in particles {
31 if map.contains_key(&p.emitter_hash) {
32 continue;
33 }
34 let Some(&emitter_id) = emitter_nodes.get(&p.emitter_hash) else {
35 continue;
36 };
37 let Some(node) = comp.nodes.get(emitter_id.0) else {
38 continue;
39 };
40 let style = match node.static_str("Style") {
41 Some("ParticleStyleBitmap") => ParticleStyleKind::Bitmap,
42 Some("ParticleStyleBlob") => ParticleStyleKind::Blob,
43 Some("ParticleStyleNGon") => ParticleStyleKind::NGon,
44 Some("ParticleStyleBrush") => ParticleStyleKind::Brush,
45 _ => ParticleStyleKind::Point,
46 };
47 let size_over_life = node
48 .inputs
49 .get("ParticleStyle.SizeOverLife")
50 .and_then(|b| b.source_op.as_deref())
51 .and_then(|src| comp.splines.get(src));
52 let fade_in = comp
53 .eval_number(node, "ParticleStyle.FadeIn", time, 0.0, expr)
54 .clamp(0.0, 1.0);
55 let fade_out = comp
56 .eval_number(node, "ParticleStyle.FadeOut", time, 1.0, expr)
57 .clamp(0.0, 1.0);
58 let color_over_life_on =
59 comp.eval_number(node, "ParticleStyle.ColorOverLifeControls", time, 0.0, expr) > 0.5;
60 let color_over_life = if color_over_life_on {
61 comp.eval_gradient(node, "ParticleStyle.ColorOverLife", time)
62 } else {
63 None
64 };
65 map.insert(
66 p.emitter_hash,
67 EmitterRenderProps {
68 emitter_id,
69 style,
70 tiny_sprite: tiny_background_sprite(comp, node, time, expr),
71 ngon_sides: comp.eval_number(node, "ParticleStyleNGon.NGonSides", time, 5.0, expr).round().max(3.0),
72 size_over_life,
73 fade_in,
74 fade_out,
75 color_over_life,
76 },
77 );
78 }
79 map
80}
81
82/// Solid sprite for a `Background` tool narrower than 16 px.
83///
84/// The engine evaluates such tools at comp size, so the particle uses the tool's nominal
85/// `Width`/`Height` and its flat color directly.
86fn tiny_background_sprite(
87 comp: &Comp,
88 emitter: &Node,
89 t: f64,
90 expr: &ExprEngine,
91) -> Option<([f64; 2], SpriteImage)> {
92 let src = emitter
93 .connected_node("ParticleStyleBitmap.DropToolsHere")
94 .and_then(|name| comp.find_node(name))
95 .map(|id| &comp.nodes[id.0])
96 .filter(|n| n.kind == "Background")?;
97 let w = comp.eval_number(src, "Width", t, 0.0, expr);
98 let h = comp.eval_number(src, "Height", t, 0.0, expr);
99 if !(w >= 1.0 && h >= 1.0 && (w < 16.0 || h < 16.0)) {
100 return None;
101 }
102 let channel = |name: &str, default: f64| comp.eval_number(src, name, t, default, expr).clamp(0.0, 1.0);
103 let a = channel("TopLeftAlpha", 1.0);
104 let px = |c: f64| (c * a * 255.0 + 0.5) as u8;
105 let rgba = vec![
106 px(channel("TopLeftRed", 0.0)),
107 px(channel("TopLeftGreen", 0.0)),
108 px(channel("TopLeftBlue", 0.0)),
109 (a * 255.0 + 0.5) as u8,
110 ];
111 Some(([w, h], SpriteImage { size: [1, 1], rgba }))
112}
113
114#[allow(clippy::too_many_arguments)]
115pub(super) fn rasterize_particles(
116 out: &mut [u8],
117 dims: [u32; 2],
118 px_scale: f64,
119 comp: &Comp,
120 emitter_nodes: &HashMap<u64, NodeId>,
121 particles: &[Particle],
122 time: f64,
123 expr: &ExprEngine,
124 sprites: &HashMap<NodeId, SpriteImage>,
125) {
126 if particles.is_empty() {
127 return;
128 }
129
130 let props_map = collect_emitter_render_props(comp, emitter_nodes, particles, time, expr);
131 let w = dims[0] as usize;
132 let h = dims[1] as usize;
133 let w_f = w as f64;
134 let h_f = h as f64;
135
136 // Accumulate in linear-ish float premultiplied RGBA for clean blending, then pack to u8.
137 let mut accum = vec![0.0f32; w * h * 4];
138
139 for p in particles {
140 if !p.alive {
141 continue;
142 }
143 let Some(props) = props_map.get(&p.emitter_hash) else {
144 continue;
145 };
146
147 let life_frac = (p.age / p.lifespan.max(1.0)).clamp(0.0, 1.0);
148 // Fusion's SizeOverLife LUT maps 0.5 -> 1.0x (0.0 -> 0x, 1.0 -> 2x).
149 let size_mult = props
150 .size_over_life
151 .map(|sp| (2.0 * sp.eval(life_frac)).max(0.0))
152 .unwrap_or(1.0);
153 let depth_scale = CAMERA_DISTANCE / (CAMERA_DISTANCE + p.pos[2]);
154 if !(depth_scale > 0.0) {
155 continue;
156 }
157 let size_world = p.size * size_mult * depth_scale;
158 if size_world <= 1e-6 {
159 continue;
160 }
161
162 let mut fade = 1.0f64;
163 if props.fade_in > 1e-6 && life_frac < props.fade_in {
164 fade *= life_frac / props.fade_in;
165 }
166 if props.fade_out < 1.0 - 1e-6 && life_frac > props.fade_out {
167 fade *= ((1.0 - life_frac) / (1.0 - props.fade_out)).max(0.0);
168 }
169
170 let mut cr = p.color[0];
171 let mut cg = p.color[1];
172 let mut cb = p.color[2];
173 let mut ca = p.color[3] * fade as f32;
174 if let Some(grad) = &props.color_over_life {
175 let g = grad.sample(life_frac);
176 cr *= g[0];
177 cg *= g[1];
178 cb *= g[2];
179 ca *= g[3];
180 }
181 ca = ca.clamp(0.0, 1.0);
182 if ca <= 1e-4 {
183 continue;
184 }
185
186 // Fusion 2D particle coordinates: X in [-0.5, +0.5], Y-up with same unit scale as X.
187 let cx = (p.pos[0] * depth_scale + 0.5) * w_f;
188 let cy = h_f * 0.5 - p.pos[1] * depth_scale * w_f;
189
190 if props.style == ParticleStyleKind::Bitmap {
191 let (sprite, nominal) = match &props.tiny_sprite {
192 Some((nominal, sprite)) => (Some(sprite), *nominal),
193 None => {
194 let sprite = sprites.get(&props.emitter_id);
195 (sprite, sprite.map_or([0.0; 2], |s| [s.size[0] as f64, s.size[1] as f64]))
196 }
197 };
198 if let Some(sprite) = sprite.filter(|s| {
199 s.size[0] > 0
200 && s.size[1] > 0
201 && s.rgba.len() >= (s.size[0] as usize).saturating_mul(s.size[1] as usize).saturating_mul(4)
202 }) {
203 draw_bitmap_particle(
204 &mut accum,
205 w,
206 h,
207 cx,
208 cy,
209 size_world * nominal[0] * px_scale,
210 size_world * nominal[1] * px_scale,
211 p.rot_z,
212 [cr, cg, cb, ca],
213 sprite,
214 );
215 continue;
216 }
217 }
218
219 match props.style {
220 ParticleStyleKind::Point => {
221 blend_pixel(&mut accum, w, h, cx.floor(), cy.floor(), [cr, cg, cb, ca]);
222 }
223 ParticleStyleKind::Blob | ParticleStyleKind::Bitmap => {
224 let sigma = BLOB_SIGMA_PER_SIZE * size_world * px_scale;
225 draw_soft_particle(&mut accum, w, h, cx, cy, sigma, [cr, cg, cb, ca], |_, _| 1.0);
226 }
227 ParticleStyleKind::NGon => {
228 let sigma = BLOB_SIGMA_PER_SIZE * size_world * px_scale;
229 let sides = props.ngon_sides;
230 let spike_period = std::f64::consts::TAU / sides;
231 let phase = std::f64::consts::FRAC_PI_2 + p.rot_z.to_radians();
232 // Spike sharpness fitted to Fusion 21.1: alpha mass is 0.18/0.48/0.78 of a blob for 3/5/8 sides.
233 let sharpness = 4.5 * (3.0 / sides).powf(2.8);
234 draw_soft_particle(&mut accum, w, h, cx, cy, sigma, [cr, cg, cb, ca], |dx, dy| {
235 // Distance to the nearest spike, as a fraction of half the spike period.
236 let angle = (-dy).atan2(dx) - phase;
237 let off = angle.rem_euclid(spike_period);
238 let to_spike = off.min(spike_period - off);
239 (1.0 - to_spike / (0.5 * spike_period)).powf(sharpness)
240 });
241 }
242 ParticleStyleKind::Brush => {}
243 }
244 }
245
246 for (dst, &src) in out.iter_mut().zip(accum.iter()) {
247 *dst = (src.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
248 }
249}
250
251#[allow(clippy::too_many_arguments)]
252fn draw_bitmap_particle(
253 accum: &mut [f32],
254 w: usize,
255 h: usize,
256 cx: f64,
257 cy: f64,
258 draw_w: f64,
259 draw_h: f64,
260 rot_z_deg: f64,
261 tint: [f32; 4],
262 sprite: &SpriteImage,
263) {
264 if draw_w < 0.5 || draw_h < 0.5 {
265 return;
266 }
267
268 let hw = draw_w * 0.5;
269 let hh = draw_h * 0.5;
270 let theta = rot_z_deg.to_radians();
271 let cos_t = theta.cos();
272 let sin_t = theta.sin();
273
274 let rx = hw * cos_t.abs() + hh * sin_t.abs() + 1.0;
275 let ry = hw * sin_t.abs() + hh * cos_t.abs() + 1.0;
276
277 let min_x = ((cx - rx).floor() as isize).max(0) as usize;
278 let max_x = ((cx + rx).ceil() as isize).min(w as isize - 1);
279 let min_y = ((cy - ry).floor() as isize).max(0) as usize;
280 let max_y = ((cy + ry).ceil() as isize).min(h as isize - 1);
281 if max_x < min_x as isize || max_y < min_y as isize {
282 return;
283 }
284
285 let inv_dw = 1.0 / draw_w;
286 let inv_dh = 1.0 / draw_h;
287 let edge_u = inv_dw * 0.5;
288 let edge_v = inv_dh * 0.5;
289 let sw_i = sprite.size[0] as usize;
290 let sh_i = sprite.size[1] as usize;
291
292 for py in min_y..=(max_y as usize) {
293 let dy = (py as f64 + 0.5) - cy;
294 let row_off = py * w * 4;
295 for px in min_x..=(max_x as usize) {
296 let dx = (px as f64 + 0.5) - cx;
297 // Inverse rotate into sprite local space (CCW in Y-up).
298 let lx = dx * cos_t - dy * sin_t;
299 let ly = dx * sin_t + dy * cos_t;
300
301 let u = lx * inv_dw + 0.5;
302 let v = ly * inv_dh + 0.5;
303 if u <= -edge_u || u >= 1.0 + edge_u || v <= -edge_v || v >= 1.0 + edge_v {
304 continue;
305 }
306
307 // Anti-aliased border coverage (0.5px feather at edges).
308 let cov_u = ((u + edge_u) / (2.0 * edge_u))
309 .min((1.0 + edge_u - u) / (2.0 * edge_u))
310 .clamp(0.0, 1.0);
311 let cov_v = ((v + edge_v) / (2.0 * edge_v))
312 .min((1.0 + edge_v - v) / (2.0 * edge_v))
313 .clamp(0.0, 1.0);
314 let cov = (cov_u * cov_v) as f32;
315 if cov <= 1e-4 {
316 continue;
317 }
318
319 let sample = sample_sprite_bilinear(
320 &sprite.rgba,
321 sw_i,
322 sh_i,
323 u.clamp(0.0, 1.0),
324 v.clamp(0.0, 1.0),
325 );
326 let alpha_scale = tint[3] * cov;
327 let pa = sample[3] * alpha_scale;
328 if pa <= 1e-5 {
329 continue;
330 }
331 let pr = sample[0] * tint[0] * alpha_scale;
332 let pg = sample[1] * tint[1] * alpha_scale;
333 let pb = sample[2] * tint[2] * alpha_scale;
334
335 let idx = row_off + px * 4;
336 let inv_a = 1.0 - pa;
337 accum[idx] = pr + accum[idx] * inv_a;
338 accum[idx + 1] = pg + accum[idx + 1] * inv_a;
339 accum[idx + 2] = pb + accum[idx + 2] * inv_a;
340 accum[idx + 3] = pa + accum[idx + 3] * inv_a;
341 }
342 }
343}
344
345#[inline]
346fn sample_sprite_bilinear(rgba: &[u8], w: usize, h: usize, u: f64, v: f64) -> [f32; 4] {
347 let fx = (u * w as f64 - 0.5).clamp(0.0, (w - 1) as f64);
348 let fy = (v * h as f64 - 0.5).clamp(0.0, (h - 1) as f64);
349 let x0 = fx.floor() as usize;
350 let y0 = fy.floor() as usize;
351 let x1 = (x0 + 1).min(w - 1);
352 let y1 = (y0 + 1).min(h - 1);
353 let tx = (fx - x0 as f64) as f32;
354 let ty = (fy - y0 as f64) as f32;
355
356 let i00 = (y0 * w + x0) * 4;
357 let i10 = (y0 * w + x1) * 4;
358 let i01 = (y1 * w + x0) * 4;
359 let i11 = (y1 * w + x1) * 4;
360
361 let w00 = (1.0 - tx) * (1.0 - ty) * (1.0 / 255.0);
362 let w10 = tx * (1.0 - ty) * (1.0 / 255.0);
363 let w01 = (1.0 - tx) * ty * (1.0 / 255.0);
364 let w11 = tx * ty * (1.0 / 255.0);
365
366 [
367 rgba[i00] as f32 * w00
368 + rgba[i10] as f32 * w10
369 + rgba[i01] as f32 * w01
370 + rgba[i11] as f32 * w11,
371 rgba[i00 + 1] as f32 * w00
372 + rgba[i10 + 1] as f32 * w10
373 + rgba[i01 + 1] as f32 * w01
374 + rgba[i11 + 1] as f32 * w11,
375 rgba[i00 + 2] as f32 * w00
376 + rgba[i10 + 2] as f32 * w10
377 + rgba[i01 + 2] as f32 * w01
378 + rgba[i11 + 2] as f32 * w11,
379 rgba[i00 + 3] as f32 * w00
380 + rgba[i10 + 3] as f32 * w10
381 + rgba[i01 + 3] as f32 * w01
382 + rgba[i11 + 3] as f32 * w11,
383 ]
384}
385
386/// Source-over blends one premultiplied-accumulator pixel; out-of-bounds coordinates are ignored.
387#[inline]
388fn blend_pixel(accum: &mut [f32], w: usize, h: usize, x: f64, y: f64, color: [f32; 4]) {
389 if x < 0.0 || y < 0.0 || x >= w as f64 || y >= h as f64 {
390 return;
391 }
392 let pa = color[3].clamp(0.0, 1.0);
393 if pa <= 1e-5 {
394 return;
395 }
396 let idx = (y as usize * w + x as usize) * 4;
397 let inv_a = 1.0 - pa;
398 accum[idx] = color[0] * pa + accum[idx] * inv_a;
399 accum[idx + 1] = color[1] * pa + accum[idx + 1] * inv_a;
400 accum[idx + 2] = color[2] * pa + accum[idx + 2] * inv_a;
401 accum[idx + 3] = pa + accum[idx + 3] * inv_a;
402}
403
404/// Gaussian falloff sampled at pixel centers out to `4 sigma`, scaled by `shape(dx, dy)`.
405#[allow(clippy::too_many_arguments)]
406fn draw_soft_particle(
407 accum: &mut [f32],
408 w: usize,
409 h: usize,
410 cx: f64,
411 cy: f64,
412 sigma: f64,
413 color: [f32; 4],
414 shape: impl Fn(f64, f64) -> f64,
415) {
416 let bound = 4.0 * sigma;
417 let min_x = ((cx - bound).floor() as isize).max(0);
418 let max_x = ((cx + bound).ceil() as isize).min(w as isize - 1);
419 let min_y = ((cy - bound).floor() as isize).max(0);
420 let max_y = ((cy + bound).ceil() as isize).min(h as isize - 1);
421 let inv_two_sigma_sq = 0.5 / (sigma * sigma);
422 for py in min_y..=max_y {
423 let dy = (py as f64 + 0.5) - cy;
424 for px in min_x..=max_x {
425 let dx = (px as f64 + 0.5) - cx;
426 let cov = ((-(dx * dx + dy * dy) * inv_two_sigma_sq).exp() * shape(dx, dy)) as f32;
427 blend_pixel(accum, w, h, px as f64, py as f64, [color[0], color[1], color[2], color[3] * cov]);
428 }
429 }
430}
crates/engine/src/particles/sim.rs created+889
...@@ -0,0 +1,889 @@
1//! Per-frame particle emission, regions, forces, collisions, and simulation stepping.
2
3use std::collections::HashSet;
4
5use model::{Comp, ExprEngine, Node};
6
7use super::plan::ParticlePlan;
8use super::{
9 MAX_PARTICLES, POINT_FORCE_SCALE, Particle, SimState, SplitMix64, TURBULENCE_SCALE,
10 VELOCITY_SCALE,
11};
12
13/// Advances the particle simulation by a single integer frame `frame`.
14pub(super) fn step_simulation(
15 state: &mut SimState,
16 comp: &Comp,
17 plan: &ParticlePlan,
18 frame: i64,
19 expr: &ExprEngine,
20) {
21 let t = frame as f64;
22
23 // 1. Apply forces & kills to existing live particles, then integrate motion and age.
24 if !state.particles.is_empty() {
25 for (mod_id, scope) in &plan.modifiers {
26 let Some(node) = comp.nodes.get(mod_id.0) else {
27 continue;
28 };
29 apply_modifier(&mut state.particles, comp, node, scope, t, expr);
30 }
31
32 for p in &mut state.particles {
33 if !p.alive {
34 continue;
35 }
36 p.pos[0] += p.vel[0];
37 p.pos[1] += p.vel[1];
38 p.pos[2] += p.vel[2];
39 p.rot_z += p.spin_z;
40 p.age += 1.0;
41 if p.age >= p.lifespan {
42 p.alive = false;
43 }
44 }
45 state.particles.retain(|p| p.alive);
46 }
47
48 // 2. Emit new particles for `frame` (born with `age = 0.0` at their spawn region).
49 let first_new = state.particles.len();
50 for &(emitter_id, emitter_hash) in &plan.emitters {
51 if state.particles.len() >= MAX_PARTICLES {
52 break;
53 }
54 let Some(node) = comp.nodes.get(emitter_id.0) else {
55 continue;
56 };
57 emit_particles(state, comp, node, emitter_hash, frame, t, expr);
58 }
59
60 // A newborn is damped by friction and then integrated once on its birth frame; other forces
61 // only start acting next frame.
62 for (mod_id, scope) in &plan.modifiers {
63 let Some(node) = comp.nodes.get(mod_id.0) else {
64 continue;
65 };
66 if matches!(node.kind.as_str(), "pDrag" | "pFriction") {
67 apply_modifier(&mut state.particles[first_new..], comp, node, scope, t, expr);
68 }
69 }
70 for p in &mut state.particles[first_new..] {
71 for axis in 0..3 {
72 p.pos[axis] += p.vel[axis];
73 }
74 p.rot_z += p.spin_z;
75 }
76}
77
78fn emit_particles(
79 state: &mut SimState,
80 comp: &Comp,
81 node: &Node,
82 emitter_hash: u64,
83 frame: i64,
84 t: f64,
85 expr: &ExprEngine,
86) {
87 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64;
88 let mut rng = SplitMix64::from_parts(seed, frame, &node.name);
89
90 let number = comp.eval_number(node, "Number", t, 10.0, expr).max(0.0);
91 let number_var = comp
92 .eval_number(node, "NumberVariance", t, 0.0, expr)
93 .max(0.0);
94
95 let rate = (number + rng.signed() * number_var).max(0.0);
96 let accum = state.emit_accum.entry(emitter_hash).or_insert(0.0);
97 *accum += rate;
98 let mut emit_count = accum.floor() as usize;
99 *accum -= emit_count as f64;
100
101 if emit_count == 0 {
102 return;
103 }
104 let remaining_cap = MAX_PARTICLES.saturating_sub(state.particles.len());
105 if emit_count > remaining_cap {
106 emit_count = remaining_cap;
107 }
108
109 let lifespan_base = comp.eval_number(node, "Lifespan", t, 100.0, expr).max(1.0);
110 let lifespan_var = comp
111 .eval_number(node, "LifespanVariance", t, 0.0, expr)
112 .max(0.0);
113 let pos_var = comp
114 .eval_number(node, "PositionVariance", t, 0.0, expr)
115 .max(0.0);
116
117 let vel_base = comp.eval_number(node, "Velocity", t, 0.0, expr);
118 let vel_var = comp
119 .eval_number(node, "VelocityVariance", t, 0.0, expr)
120 .max(0.0);
121 let angle_base = comp.eval_number(node, "Angle", t, 0.0, expr);
122 let angle_var = comp
123 .eval_number(node, "AngleVariance", t, 0.0, expr)
124 .max(0.0);
125 let angle_z_base = comp.eval_number(node, "AngleZ", t, 0.0, expr);
126 let angle_z_var = comp
127 .eval_number(node, "AngleZVariance", t, 0.0, expr)
128 .max(0.0);
129
130 let rot_z_base = comp.eval_number(node, "RotationZ", t, 0.0, expr);
131 let rot_z_var = comp
132 .eval_number(node, "RotationZVariance", t, 0.0, expr)
133 .max(0.0);
134 let spin_z_base = comp.eval_number(node, "SpinZ", t, 0.0, expr);
135 let spin_z_var = comp
136 .eval_number(node, "SpinZVariance", t, 0.0, expr)
137 .max(0.0);
138
139 let base_r = comp.eval_number(node, "ParticleStyle.Red", t, 1.0, expr);
140 let base_g = comp.eval_number(node, "ParticleStyle.Green", t, 1.0, expr);
141 let base_b = comp.eval_number(node, "ParticleStyle.Blue", t, 1.0, expr);
142 let base_a = comp.eval_number(node, "ParticleStyle.Alpha", t, 1.0, expr);
143
144 let color_var = comp.eval_number(node, "ParticleStyle.ColorVariance", t, 0.0, expr) > 0.5;
145 let r_lo = (base_r + comp.eval_number(node, "ParticleStyle.RedLow", t, 0.0, expr)).clamp(0.0, 1.0);
146 let r_hi = (base_r + comp.eval_number(node, "ParticleStyle.RedHigh", t, 0.0, expr)).clamp(0.0, 1.0);
147 let g_lo = (base_g + comp.eval_number(node, "ParticleStyle.GreenLow", t, 0.0, expr)).clamp(0.0, 1.0);
148 let g_hi = (base_g + comp.eval_number(node, "ParticleStyle.GreenHigh", t, 0.0, expr)).clamp(0.0, 1.0);
149 let b_lo = (base_b + comp.eval_number(node, "ParticleStyle.BlueLow", t, 0.0, expr)).clamp(0.0, 1.0);
150 let b_hi = (base_b + comp.eval_number(node, "ParticleStyle.BlueHigh", t, 0.0, expr)).clamp(0.0, 1.0);
151 let a_lo = (base_a + comp.eval_number(node, "ParticleStyle.AlphaLow", t, 0.0, expr)).clamp(0.0, 1.0);
152 let a_hi = (base_a + comp.eval_number(node, "ParticleStyle.AlphaHigh", t, 0.0, expr)).clamp(0.0, 1.0);
153
154 let size_base = comp
155 .eval_number(node, "ParticleStyle.Size", t, 1.0, expr)
156 .max(0.0);
157 let size_var = comp
158 .eval_number(node, "ParticleStyle.SizeVariance", t, 0.0, expr)
159 .max(0.0);
160
161 let region = RegionSpec::from_node(comp, node, t, expr);
162
163 for _ in 0..emit_count {
164 let mut pos = region.sample(&mut rng);
165 if pos_var > 0.0 {
166 pos[0] += rng.signed() * pos_var;
167 pos[1] += rng.signed() * pos_var;
168 pos[2] += rng.signed() * pos_var;
169 }
170
171 let speed = (vel_base + rng.signed() * vel_var) * VELOCITY_SCALE;
172 let ang = (angle_base + rng.signed() * angle_var).to_radians();
173 let ang_z = (angle_z_base + rng.signed() * angle_z_var).to_radians();
174 let cos_z = ang_z.cos();
175 let vel = [
176 speed * ang.cos() * cos_z,
177 speed * ang.sin() * cos_z,
178 speed * ang_z.sin(),
179 ];
180
181 let rot_z = rot_z_base + rng.signed() * rot_z_var;
182 let spin_z = spin_z_base + rng.signed() * spin_z_var;
183 let lifespan = (lifespan_base + rng.signed() * lifespan_var).max(1.0);
184 let size = (size_base + rng.signed() * size_var).max(0.0);
185
186 let color = if color_var {
187 [
188 rng.range(r_lo, r_hi) as f32,
189 rng.range(g_lo, g_hi) as f32,
190 rng.range(b_lo, b_hi) as f32,
191 rng.range(a_lo, a_hi) as f32,
192 ]
193 } else {
194 [
195 base_r.clamp(0.0, 1.0) as f32,
196 base_g.clamp(0.0, 1.0) as f32,
197 base_b.clamp(0.0, 1.0) as f32,
198 base_a.clamp(0.0, 1.0) as f32,
199 ]
200 };
201
202 state.particles.push(Particle {
203 emitter_hash,
204 pos,
205 vel,
206 rot_z,
207 spin_z,
208 age: 0.0,
209 lifespan,
210 size,
211 color,
212 alive: true,
213 });
214 }
215}
216
217#[derive(Clone, Copy)]
218pub(super) enum RegionSpec {
219 Point {
220 center: [f64; 3],
221 },
222 Rect {
223 center: [f64; 3],
224 width: f64,
225 height: f64,
226 },
227 Sphere {
228 center: [f64; 3],
229 radius: f64,
230 },
231 Cube {
232 center: [f64; 3],
233 width: f64,
234 height: f64,
235 depth: f64,
236 },
237 Line {
238 start: [f64; 3],
239 end: [f64; 3],
240 },
241 All,
242}
243
244impl RegionSpec {
245 pub(super) fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self {
246 let region_name = node.static_str("Region").unwrap_or("SphereRgn");
247 match region_name {
248 "RectRgn" => Self::Rect {
249 center: [
250 comp.eval_number(node, "RectRgn.Translate.X", t, 0.0, expr),
251 comp.eval_number(node, "RectRgn.Translate.Y", t, 0.0, expr),
252 comp.eval_number(node, "RectRgn.Translate.Z", t, 0.0, expr),
253 ],
254 width: comp.eval_number(node, "RectRgn.Width", t, 0.1, expr).abs(),
255 height: comp.eval_number(node, "RectRgn.Height", t, 0.1, expr).abs(),
256 },
257 "SphereRgn" => Self::Sphere {
258 center: [
259 comp.eval_number(node, "SphereRgn.Translate.X", t, 0.0, expr),
260 comp.eval_number(node, "SphereRgn.Translate.Y", t, 0.0, expr),
261 comp.eval_number(node, "SphereRgn.Translate.Z", t, 0.0, expr),
262 ],
263 radius: comp.eval_number(node, "SphereRgn.Size", t, 0.1, expr).abs() * 0.5,
264 },
265 "CubeRgn" => Self::Cube {
266 center: [
267 comp.eval_number(node, "CubeRgn.Translate.X", t, 0.0, expr),
268 comp.eval_number(node, "CubeRgn.Translate.Y", t, 0.0, expr),
269 comp.eval_number(node, "CubeRgn.Translate.Z", t, 0.0, expr),
270 ],
271 width: comp.eval_number(node, "CubeRgn.Width", t, 0.1, expr).abs(),
272 height: comp.eval_number(node, "CubeRgn.Height", t, 0.1, expr).abs(),
273 depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.1, expr).abs(),
274 },
275 "LineRgn" => {
276 let tx = comp.eval_number(node, "LineRgn.Translate.X", t, 0.0, expr);
277 let ty = comp.eval_number(node, "LineRgn.Translate.Y", t, 0.0, expr);
278 let tz = comp.eval_number(node, "LineRgn.Translate.Z", t, 0.0, expr);
279 Self::Line {
280 start: [
281 tx + comp.eval_number(node, "LineRgn.Start.X", t, -0.5, expr),
282 ty + comp.eval_number(node, "LineRgn.Start.Y", t, 0.0, expr),
283 tz + comp.eval_number(node, "LineRgn.Start.Z", t, 0.0, expr),
284 ],
285 end: [
286 tx + comp.eval_number(node, "LineRgn.End.X", t, 0.5, expr),
287 ty + comp.eval_number(node, "LineRgn.End.Y", t, 0.0, expr),
288 tz + comp.eval_number(node, "LineRgn.End.Z", t, 0.0, expr),
289 ],
290 }
291 }
292 "AllRgn" | "All" => Self::All,
293 _ => Self::Point {
294 center: [
295 comp.eval_number(node, "Point.Translate.X", t, 0.0, expr),
296 comp.eval_number(node, "Point.Translate.Y", t, 0.0, expr),
297 comp.eval_number(node, "Point.Translate.Z", t, 0.0, expr),
298 ],
299 },
300 }
301 }
302
303 fn sample(&self, rng: &mut SplitMix64) -> [f64; 3] {
304 match *self {
305 Self::Point { center } => center,
306 Self::Rect {
307 center,
308 width,
309 height,
310 } => [
311 center[0] + (rng.next_f64() - 0.5) * width,
312 center[1] + (rng.next_f64() - 0.5) * height,
313 center[2],
314 ],
315 Self::Sphere { center, radius } => {
316 let u = rng.next_f64();
317 let v = rng.next_f64();
318 let w = rng.next_f64();
319 let theta = u * std::f64::consts::TAU;
320 let cos_phi = 2.0 * v - 1.0;
321 let sin_phi = (1.0 - cos_phi * cos_phi).max(0.0).sqrt();
322 let r = radius * w.cbrt();
323 [
324 center[0] + r * sin_phi * theta.cos(),
325 center[1] + r * sin_phi * theta.sin(),
326 center[2] + r * cos_phi,
327 ]
328 }
329 Self::Cube {
330 center,
331 width,
332 height,
333 depth,
334 } => [
335 center[0] + (rng.next_f64() - 0.5) * width,
336 center[1] + (rng.next_f64() - 0.5) * height,
337 center[2] + (rng.next_f64() - 0.5) * depth,
338 ],
339 Self::Line { start, end } => {
340 let u = rng.next_f64();
341 [
342 start[0] + (end[0] - start[0]) * u,
343 start[1] + (end[1] - start[1]) * u,
344 start[2] + (end[2] - start[2]) * u,
345 ]
346 }
347 Self::All => [0.0, 0.0, 0.0],
348 }
349 }
350
351 fn contains(&self, p: [f64; 3]) -> bool {
352 match *self {
353 Self::All => true,
354 Self::Point { center } => {
355 let dx = p[0] - center[0];
356 let dy = p[1] - center[1];
357 let dz = p[2] - center[2];
358 dx * dx + dy * dy + dz * dz <= 1e-4
359 }
360 Self::Rect {
361 center,
362 width,
363 height,
364 } => {
365 (p[0] - center[0]).abs() <= width * 0.5
366 && (p[1] - center[1]).abs() <= height * 0.5
367 }
368 Self::Sphere { center, radius } => {
369 let dx = p[0] - center[0];
370 let dy = p[1] - center[1];
371 let dz = p[2] - center[2];
372 dx * dx + dy * dy + dz * dz <= radius * radius
373 }
374 Self::Cube {
375 center,
376 width,
377 height,
378 depth,
379 } => {
380 (p[0] - center[0]).abs() <= width * 0.5
381 && (p[1] - center[1]).abs() <= height * 0.5
382 && (p[2] - center[2]).abs() <= depth * 0.5
383 }
384 Self::Line { start, end } => {
385 let vx = end[0] - start[0];
386 let vy = end[1] - start[1];
387 let vz = end[2] - start[2];
388 let len_sq = vx * vx + vy * vy + vz * vz;
389 let u = if len_sq > 1e-9 {
390 (((p[0] - start[0]) * vx + (p[1] - start[1]) * vy + (p[2] - start[2]) * vz)
391 / len_sq)
392 .clamp(0.0, 1.0)
393 } else {
394 0.0
395 };
396 let cx = start[0] + vx * u;
397 let cy = start[1] + vy * u;
398 let cz = start[2] + vz * u;
399 let dx = p[0] - cx;
400 let dy = p[1] - cy;
401 let dz = p[2] - cz;
402 dx * dx + dy * dy + dz * dz <= 1e-3
403 }
404 }
405 }
406
407 /// Parses a `pBounce` region (supports `LineRgn`, `RectRgn`, `CubeRgn`, `SphereRgn`,
408 /// `MeshRegion`, and `Transform3DOp.Translate` fallback).
409 fn from_bounce_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self {
410 let tx = comp.eval_number(node, "Transform3DOp.Translate.X", t, 0.0, expr);
411 let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", t, 0.0, expr);
412 let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", t, 0.0, expr);
413 match node.static_str("Region") {
414 Some("RectRgn") => Self::Rect {
415 center: [
416 comp.eval_number(node, "RectRgn.Translate.X", t, tx, expr),
417 comp.eval_number(node, "RectRgn.Translate.Y", t, ty, expr),
418 comp.eval_number(node, "RectRgn.Translate.Z", t, tz, expr),
419 ],
420 width: comp.eval_number(node, "RectRgn.Width", t, 0.1, expr).abs(),
421 height: comp.eval_number(node, "RectRgn.Height", t, 0.1, expr).abs(),
422 },
423 Some("SphereRgn") => Self::Sphere {
424 center: [
425 comp.eval_number(node, "SphereRgn.Translate.X", t, tx, expr),
426 comp.eval_number(node, "SphereRgn.Translate.Y", t, ty, expr),
427 comp.eval_number(node, "SphereRgn.Translate.Z", t, tz, expr),
428 ],
429 radius: comp.eval_number(node, "SphereRgn.Size", t, 0.5, expr).abs() * 0.5,
430 },
431 Some("CubeRgn") => Self::Cube {
432 center: [
433 comp.eval_number(node, "CubeRgn.Translate.X", t, tx, expr),
434 comp.eval_number(node, "CubeRgn.Translate.Y", t, ty, expr),
435 comp.eval_number(node, "CubeRgn.Translate.Z", t, tz, expr),
436 ],
437 width: comp.eval_number(node, "CubeRgn.Width", t, 0.1, expr).abs(),
438 height: comp.eval_number(node, "CubeRgn.Height", t, 0.1, expr).abs(),
439 depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.1, expr).abs(),
440 },
441 Some("LineRgn") => {
442 let lx = comp.eval_number(node, "LineRgn.Translate.X", t, tx, expr);
443 let ly = comp.eval_number(node, "LineRgn.Translate.Y", t, ty, expr);
444 let lz = comp.eval_number(node, "LineRgn.Translate.Z", t, tz, expr);
445 Self::Line {
446 start: [
447 lx + comp.eval_number(node, "LineRgn.Start.X", t, -0.5, expr),
448 ly + comp.eval_number(node, "LineRgn.Start.Y", t, 0.0, expr),
449 lz + comp.eval_number(node, "LineRgn.Start.Z", t, 0.0, expr),
450 ],
451 end: [
452 lx + comp.eval_number(node, "LineRgn.End.X", t, 0.5, expr),
453 ly + comp.eval_number(node, "LineRgn.End.Y", t, 0.0, expr),
454 lz + comp.eval_number(node, "LineRgn.End.Z", t, 0.0, expr),
455 ],
456 }
457 }
458 Some("MeshRegion") | None => Self::Point { center: [tx, ty, tz] },
459 _ => Self::from_node(comp, node, t, expr),
460 }
461 }
462
463 /// Checks whether a particle stepping `pos -> pos + vel` collides with this bounce region.
464 /// Returns `(contact_pos, outward_unit_normal)` when a reflection should occur.
465 fn bounce_collision(&self, pos: [f64; 3], vel: [f64; 3]) -> Option<([f64; 3], [f64; 3])> {
466 let next = [pos[0] + vel[0], pos[1] + vel[1], pos[2] + vel[2]];
467 match *self {
468 Self::Line { start, end } => {
469 let sx = end[0] - start[0];
470 let sy = end[1] - start[1];
471 let len_sq = sx * sx + sy * sy;
472 let len = len_sq.sqrt();
473 if len < 1e-9 {
474 return None;
475 }
476 let mut n = [-sy / len, sx / len, 0.0];
477 let d0 = (pos[0] - start[0]) * n[0] + (pos[1] - start[1]) * n[1];
478 let d1 = (next[0] - start[0]) * n[0] + (next[1] - start[1]) * n[1];
479 let crosses = (d0 * d1 <= 0.0 && (d0.abs() > 1e-12 || d1.abs() > 1e-12))
480 || d1.abs() <= 1e-4;
481 if !crosses {
482 return None;
483 }
484 let alpha = if (d0 - d1).abs() > 1e-12 {
485 (d0 / (d0 - d1)).clamp(0.0, 1.0)
486 } else {
487 1.0
488 };
489 let hit = [
490 pos[0] + vel[0] * alpha,
491 pos[1] + vel[1] * alpha,
492 pos[2] + vel[2] * alpha,
493 ];
494 let u = ((hit[0] - start[0]) * sx + (hit[1] - start[1]) * sy) / len_sq;
495 if !(-1e-4..=1.0 + 1e-4).contains(&u) {
496 return None;
497 }
498 let vn = vel[0] * n[0] + vel[1] * n[1];
499 if vn > 0.0 {
500 n[0] = -n[0];
501 n[1] = -n[1];
502 }
503 if vel[0] * n[0] + vel[1] * n[1] >= -1e-12 {
504 return None;
505 }
506 Some(([hit[0] + n[0] * 1e-5, hit[1] + n[1] * 1e-5, hit[2]], n))
507 }
508 Self::Sphere { center, radius } => {
509 if radius < 1e-6 {
510 return None;
511 }
512 let dp = [pos[0] - center[0], pos[1] - center[1], pos[2] - center[2]];
513 let dn = [next[0] - center[0], next[1] - center[1], next[2] - center[2]];
514 let r_pos = (dp[0] * dp[0] + dp[1] * dp[1] + dp[2] * dp[2]).sqrt();
515 let r_next = (dn[0] * dn[0] + dn[1] * dn[1] + dn[2] * dn[2]).sqrt();
516 if r_pos > radius && r_next > radius {
517 return None;
518 }
519 let ref_v = if r_pos > 1e-9 { dp } else if r_next > 1e-9 { dn } else { [0.0, 1.0, 0.0] };
520 let r_len = (ref_v[0] * ref_v[0] + ref_v[1] * ref_v[1] + ref_v[2] * ref_v[2]).sqrt().max(1e-9);
521 let mut n = [ref_v[0] / r_len, ref_v[1] / r_len, ref_v[2] / r_len];
522 if r_pos < radius && r_next >= radius {
523 // Particle hitting sphere wall from inside
524 n = [-n[0], -n[1], -n[2]];
525 let pushed = [
526 center[0] - n[0] * (radius - 1e-5).max(0.0),
527 center[1] - n[1] * (radius - 1e-5).max(0.0),
528 center[2] - n[2] * (radius - 1e-5).max(0.0),
529 ];
530 return Some((pushed, n));
531 }
532 let pushed = [
533 center[0] + n[0] * (radius + 1e-5),
534 center[1] + n[1] * (radius + 1e-5),
535 center[2] + n[2] * (radius + 1e-5),
536 ];
537 Some((pushed, n))
538 }
539 Self::Rect { center, width, height } => {
540 let hx = width * 0.5;
541 let hy = height * 0.5;
542 if hy < 1e-6 {
543 let line = Self::Line {
544 start: [center[0] - hx, center[1], center[2]],
545 end: [center[0] + hx, center[1], center[2]],
546 };
547 return line.bounce_collision(pos, vel);
548 }
549 if hx < 1e-6 {
550 let line = Self::Line {
551 start: [center[0], center[1] - hy, center[2]],
552 end: [center[0], center[1] + hy, center[2]],
553 };
554 return line.bounce_collision(pos, vel);
555 }
556 bounce_aabb(pos, vel, center, [hx, hy, 1e6], false)
557 }
558 Self::Cube { center, width, height, depth } => {
559 bounce_aabb(pos, vel, center, [width * 0.5, height * 0.5, depth * 0.5], true)
560 }
561 Self::Point { center } => {
562 let cy = center[1];
563 let d0 = pos[1] - cy;
564 let d1 = next[1] - cy;
565 if d0 * d1 <= 0.0 || d1.abs() <= 1e-5 {
566 let ny = if vel[1] < 0.0 { 1.0 } else if vel[1] > 0.0 { -1.0 } else { return None };
567 let alpha = if (d0 - d1).abs() > 1e-12 {
568 (d0 / (d0 - d1)).clamp(0.0, 1.0)
569 } else {
570 1.0
571 };
572 let hit = [
573 pos[0] + vel[0] * alpha,
574 cy + ny * 1e-5,
575 pos[2] + vel[2] * alpha,
576 ];
577 return Some((hit, [0.0, ny, 0.0]));
578 }
579 None
580 }
581 Self::All => None,
582 }
583 }
584}
585
586/// Slab-method segment-vs-AABB bounce helper (2D when `check_z == false`, 3D when `check_z == true`).
587fn bounce_aabb(
588 pos: [f64; 3],
589 vel: [f64; 3],
590 center: [f64; 3],
591 half: [f64; 3],
592 check_z: bool,
593) -> Option<([f64; 3], [f64; 3])> {
594 let axes = if check_z { 3 } else { 2 };
595 let mut inside_pos = true;
596 for a in 0..axes {
597 if (pos[a] - center[a]).abs() > half[a] {
598 inside_pos = false;
599 break;
600 }
601 }
602
603 if inside_pos {
604 // Already inside: push out through the closest face
605 let mut best_axis = 0usize;
606 let mut best_pen = f64::INFINITY;
607 let mut best_sign = 1.0f64;
608 for a in 0..axes {
609 let delta = pos[a] - center[a];
610 let pen = half[a] - delta.abs();
611 if pen < best_pen {
612 best_pen = pen;
613 best_axis = a;
614 best_sign = if delta >= 0.0 { 1.0 } else { -1.0 };
615 }
616 }
617 let mut n = [0.0; 3];
618 n[best_axis] = best_sign;
619 let mut pushed = pos;
620 pushed[best_axis] = center[best_axis] + best_sign * (half[best_axis] + 1e-5);
621 return Some((pushed, n));
622 }
623
624 let mut t_min = 0.0_f64;
625 let mut t_max = 1.0_f64;
626 let mut hit_axis = 0usize;
627 let mut hit_sign = 1.0_f64;
628
629 for a in 0..axes {
630 let min_b = center[a] - half[a];
631 let max_b = center[a] + half[a];
632 if vel[a].abs() < 1e-12 {
633 if pos[a] < min_b || pos[a] > max_b {
634 return None;
635 }
636 } else {
637 let inv = 1.0 / vel[a];
638 let mut t1 = (min_b - pos[a]) * inv;
639 let mut t2 = (max_b - pos[a]) * inv;
640 let mut s = -1.0;
641 if t1 > t2 {
642 std::mem::swap(&mut t1, &mut t2);
643 s = 1.0;
644 }
645 if t1 > t_min {
646 t_min = t1;
647 hit_axis = a;
648 hit_sign = s;
649 }
650 t_max = t_max.min(t2);
651 if t_min > t_max {
652 return None;
653 }
654 }
655 }
656
657 let mut n = [0.0; 3];
658 n[hit_axis] = hit_sign;
659 let hit = [
660 pos[0] + vel[0] * t_min + n[0] * 1e-5,
661 pos[1] + vel[1] * t_min + n[1] * 1e-5,
662 pos[2] + vel[2] * t_min + n[2] * 1e-5,
663 ];
664 Some((hit, n))
665}
666
667fn apply_modifier(
668 particles: &mut [Particle],
669 comp: &Comp,
670 node: &Node,
671 scope: &HashSet<u64>,
672 t: f64,
673 expr: &ExprEngine,
674) {
675 match node.kind.as_str() {
676 "pPointForce" => {
677 let strength = comp.eval_number(node, "Strength", t, 0.0, expr);
678 if strength.abs() < 1e-12 {
679 return;
680 }
681 let power = comp.eval_number(node, "Power", t, 2.0, expr);
682 let tx = comp.eval_number(node, "Translate.X", t, 0.0, expr);
683 let ty = comp.eval_number(node, "Translate.Y", t, 0.0, expr);
684 let tz = comp.eval_number(node, "Translate.Z", t, 0.0, expr);
685
686 for p in particles.iter_mut() {
687 if !p.alive || !scope.contains(&p.emitter_hash) {
688 continue;
689 }
690 let dx = tx - p.pos[0];
691 let dy = ty - p.pos[1];
692 let dz = tz - p.pos[2];
693 let dist = (dx * dx + dy * dy + dz * dz).sqrt();
694 if dist < 1e-7 {
695 continue;
696 }
697 let falloff = dist.max(0.005).powf(power);
698 let mag = (strength * POINT_FORCE_SCALE / falloff).clamp(-0.25, 0.25);
699 let inv_d = 1.0 / dist;
700 p.vel[0] += dx * inv_d * mag;
701 p.vel[1] += dy * inv_d * mag;
702 p.vel[2] += dz * inv_d * mag;
703 }
704 }
705 "pDirectionalForce" => {
706 let strength = comp.eval_number(node, "Strength", t, 0.1, expr);
707 if strength.abs() < 1e-12 {
708 return;
709 }
710 let dir = comp
711 .eval_number(node, "Direction", t, -90.0, expr)
712 .to_radians();
713 let dir_z = comp
714 .eval_number(node, "DirectionZ", t, 0.0, expr)
715 .to_radians();
716 let mag = strength * VELOCITY_SCALE * VELOCITY_SCALE;
717 let ax = mag * dir.cos() * dir_z.cos();
718 let ay = mag * dir.sin() * dir_z.cos();
719 let az = mag * dir_z.sin();
720
721 for p in particles.iter_mut() {
722 if !p.alive || !scope.contains(&p.emitter_hash) {
723 continue;
724 }
725 p.vel[0] += ax;
726 p.vel[1] += ay;
727 p.vel[2] += az;
728 }
729 }
730 "pDrag" | "pFriction" => {
731 let damp = if node.kind == "pFriction" {
732 1.0 - comp.eval_number(node, "VelocityFriction", t, 0.05, expr)
733 } else {
734 1.0 - comp.eval_number(node, "Drag", t, 0.05, expr)
735 }
736 .clamp(0.0, 1.0);
737 let spin_damp = if node.kind == "pFriction" {
738 1.0 - comp.eval_number(node, "SpinFriction", t, 0.05, expr).clamp(0.0, 1.0)
739 } else {
740 1.0
741 };
742 for p in particles.iter_mut() {
743 if !p.alive || !scope.contains(&p.emitter_hash) {
744 continue;
745 }
746 p.vel[0] *= damp;
747 p.vel[1] *= damp;
748 p.vel[2] *= damp;
749 p.spin_z *= spin_damp;
750 }
751 }
752 "pTurbulence" => {
753 let sx = comp.eval_number(node, "XStrength", t, 0.1, expr);
754 let sy = comp.eval_number(node, "YStrength", t, 0.1, expr);
755 let sz = comp.eval_number(node, "ZStrength", t, 0.0, expr);
756 if sx.abs() < 1e-12 && sy.abs() < 1e-12 && sz.abs() < 1e-12 {
757 return;
758 }
759 let density = comp.eval_number(node, "Density", t, 1.0, expr).max(0.01);
760 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as u64;
761 let time_shift = t * 0.03;
762
763 for p in particles.iter_mut() {
764 if !p.alive || !scope.contains(&p.emitter_hash) {
765 continue;
766 }
767 let qx = p.pos[0] * density + time_shift;
768 let qy = p.pos[1] * density - time_shift * 0.7;
769 let qz = p.pos[2] * density;
770 let nx = value_noise_3d(qx, qy, qz, seed);
771 let ny = value_noise_3d(qx + 31.7, qy + 17.3, qz + 47.1, seed ^ 0x517C_C1B7_2722_0A95);
772 let nz = value_noise_3d(qx - 19.4, qy + 53.9, qz - 11.2, seed ^ 0x9E37_79B9_7F4A_7C15);
773 p.vel[0] += nx * sx * TURBULENCE_SCALE;
774 p.vel[1] += ny * sy * TURBULENCE_SCALE;
775 p.vel[2] += nz * sz * TURBULENCE_SCALE;
776 }
777 }
778 "pKill" => {
779 let region = if node.static_str("Region").is_some() {
780 RegionSpec::from_node(comp, node, t, expr)
781 } else {
782 RegionSpec::All
783 };
784 let kill_outside = matches!(
785 node.static_str("RegionMode"),
786 Some("Outside") | Some("Leaving")
787 );
788 for p in particles.iter_mut() {
789 if !p.alive || !scope.contains(&p.emitter_hash) {
790 continue;
791 }
792 let inside = region.contains(p.pos);
793 if (!kill_outside && inside) || (kill_outside && !inside) {
794 p.alive = false;
795 }
796 }
797 }
798 "pBounce" => {
799 let region = RegionSpec::from_bounce_node(comp, node, t, expr);
800 let elasticity = comp.eval_number(node, "Elasticity", t, 1.0, expr).clamp(0.0, 2.0);
801 let variance = comp.eval_number(node, "Variance", t, 0.0, expr).max(0.0);
802 let friction = comp.eval_number(node, "Friction", t, 0.0, expr).clamp(0.0, 1.0);
803 let roughness = comp.eval_number(node, "Roughness", t, 0.0, expr).max(0.0);
804 let spin = comp.eval_number(node, "Spin", t, 0.0, expr);
805 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64;
806 let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name);
807
808 for p in particles.iter_mut() {
809 if !p.alive || !scope.contains(&p.emitter_hash) {
810 continue;
811 }
812 let Some((pushed_pos, n)) = region.bounce_collision(p.pos, p.vel) else {
813 continue;
814 };
815 let vn = p.vel[0] * n[0] + p.vel[1] * n[1] + p.vel[2] * n[2];
816 if vn < 0.0 {
817 let e = (elasticity * (1.0 + rng.signed() * variance)).clamp(0.0, 2.0);
818 let t_damp = (1.0 - friction).clamp(0.0, 1.0);
819 let vnx = vn * n[0];
820 let vny = vn * n[1];
821 let vnz = vn * n[2];
822 let vtx = p.vel[0] - vnx;
823 let vty = p.vel[1] - vny;
824 let vtz = p.vel[2] - vnz;
825 p.vel[0] = vtx * t_damp - vnx * e;
826 p.vel[1] = vty * t_damp - vny * e;
827 p.vel[2] = vtz * t_damp - vnz * e;
828 if roughness > 1e-6 {
829 let scatter = roughness * 0.01 * vn.abs();
830 p.vel[0] += rng.signed() * scatter;
831 p.vel[1] += rng.signed() * scatter;
832 p.vel[2] += rng.signed() * scatter;
833 }
834 if spin.abs() > 1e-9 {
835 p.spin_z += spin * (1.0 + 0.5 * rng.signed());
836 }
837 p.pos = pushed_pos;
838 }
839 }
840 }
841 _ => {}
842 }
843}
844
845/// Smooth deterministic 3D value noise in `[-1.0, 1.0]`.
846fn value_noise_3d(x: f64, y: f64, z: f64, seed: u64) -> f64 {
847 let xi = x.floor() as i64;
848 let yi = y.floor() as i64;
849 let zi = z.floor() as i64;
850 let xf = x - xi as f64;
851 let yf = y - yi as f64;
852 let zf = z - zi as f64;
853
854 let u = xf * xf * (3.0 - 2.0 * xf);
855 let v = yf * yf * (3.0 - 2.0 * yf);
856 let w = zf * zf * (3.0 - 2.0 * zf);
857
858 let n000 = lattice_hash(xi, yi, zi, seed);
859 let n100 = lattice_hash(xi + 1, yi, zi, seed);
860 let n010 = lattice_hash(xi, yi + 1, zi, seed);
861 let n110 = lattice_hash(xi + 1, yi + 1, zi, seed);
862 let n001 = lattice_hash(xi, yi, zi + 1, seed);
863 let n101 = lattice_hash(xi + 1, yi, zi + 1, seed);
864 let n011 = lattice_hash(xi, yi + 1, zi + 1, seed);
865 let n111 = lattice_hash(xi + 1, yi + 1, zi + 1, seed);
866
867 let nx00 = n000 + (n100 - n000) * u;
868 let nx10 = n010 + (n110 - n010) * u;
869 let nx01 = n001 + (n101 - n001) * u;
870 let nx11 = n011 + (n111 - n011) * u;
871
872 let nxy0 = nx00 + (nx10 - nx00) * v;
873 let nxy1 = nx01 + (nx11 - nx01) * v;
874
875 nxy0 + (nxy1 - nxy0) * w
876}
877
878#[inline]
879fn lattice_hash(x: i64, y: i64, z: i64, seed: u64) -> f64 {
880 let mut h = seed
881 ^ (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
882 ^ (y as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9)
883 ^ (z as u64).wrapping_mul(0x94D0_49BB_1331_11EB);
884 h = (h ^ (h >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
885 h = (h ^ (h >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
886 h ^= h >> 31;
887 let unit = (h >> 11) as f64 * (1.0 / ((1u64 << 53) as f64));
888 unit * 2.0 - 1.0
889}
crates/engine/src/particles/tests.rs created+631
...@@ -0,0 +1,631 @@
1use super::plan::{build_particle_plan, particle_subgraph_hash};
2use super::sim::{RegionSpec, step_simulation};
3use super::*;
4use std::path::Path;
5use std::time::Instant;
6
7fn make_white_sprite(size: u32) -> SpriteImage {
8 SpriteImage {
9 size: [size, size],
10 rgba: vec![255u8; (size as usize) * (size as usize) * 4],
11 }
12}
13
14fn count_nonzero_alpha(buf: &[u8]) -> usize {
15 buf.chunks_exact(4).filter(|px| px[3] > 0).count()
16}
17
18#[test]
19fn test_particle_emitter_and_point_force_deterministic() {
20 let comp_src = r#"
21Composition {
22 GlobalRange = { 0, 100 },
23 RenderRange = { 0, 100 },
24 Tools = {
25 SpriteSrc = Background {
26 Inputs = {
27 Width = Input { Value = 32, },
28 Height = Input { Value = 32, },
29 },
30 },
31 pEmitter1SizeOverLife = LUTBezier {
32 KeyColorSplines = {
33 [0] = {
34 [0] = { 0.5, RH = { 0.333, 0.5 }, Flags = { Linear = true } },
35 [1] = { 0.25, LH = { 0.667, 0.25 }, Flags = { Linear = true } }
36 }
37 },
38 },
39 pEmitter1 = pEmitter {
40 Inputs = {
41 RandomSeed = Input { Value = 42, },
42 Number = Input { Value = 15, },
43 Lifespan = Input { Value = 60, },
44 Region = Input { Value = FuID { "RectRgn" }, },
45 ["RectRgn.Width"] = Input { Value = 0.6, },
46 ["RectRgn.Height"] = Input { Value = 0.4, },
47 Style = Input { Value = FuID { "ParticleStyleBitmap" }, },
48 ["ParticleStyleBitmap.DropToolsHere"] = Input {
49 SourceOp = "SpriteSrc",
50 Source = "Output",
51 },
52 ["ParticleStyle.Red"] = Input { Value = 1, },
53 ["ParticleStyle.Green"] = Input { Value = 0, },
54 ["ParticleStyle.Blue"] = Input { Value = 0, },
55 ["ParticleStyle.ColorVariance"] = Input { Value = 1, },
56 ["ParticleStyle.GreenHigh"] = Input { Value = 1, },
57 ["ParticleStyle.Size"] = Input { Value = 0.12, },
58 ["ParticleStyle.SizeOverLife"] = Input {
59 SourceOp = "pEmitter1SizeOverLife",
60 Source = "Value",
61 },
62 ["ParticleStyle.FadeIn"] = Input { Value = 0.1, },
63 ["ParticleStyle.FadeOut"] = Input { Value = 0.1, },
64 },
65 },
66 pPointForce1 = pPointForce {
67 Inputs = {
68 Strength = Input { Value = -3.0, },
69 Power = Input { Value = 0.5, },
70 ["Translate.X"] = Input { Value = 0.0, },
71 ["Translate.Y"] = Input { Value = 0.0, },
72 Input = Input {
73 SourceOp = "pEmitter1",
74 Source = "Output",
75 },
76 },
77 },
78 pRender1 = pRender {
79 Inputs = {
80 Input = Input {
81 SourceOp = "pPointForce1",
82 Source = "Output",
83 },
84 },
85 },
86 },
87}
88"#;
89
90 let comp = Comp::from_fusion_str(comp_src).expect("parse synthetic particle comp");
91 let render_id = comp.node_by_name["pRender1"];
92 let emitter_id = comp.node_by_name["pEmitter1"];
93 let sprite_id = comp.node_by_name["SpriteSrc"];
94 let force_id = comp.node_by_name["pPointForce1"];
95
96 // Verify bitmap source discovery.
97 let sources = collect_bitmap_sources(&comp, render_id);
98 assert_eq!(sources, vec![(emitter_id, sprite_id)]);
99
100 let expr = ExprEngine::new();
101 let mut sprites = HashMap::new();
102 sprites.insert(emitter_id, make_white_sprite(16));
103
104 let dims = [160, 90];
105
106 // 1. Determinism: two fresh caches produce bit-identical buffers.
107 let mut cache_a = ParticleCache::default();
108 let mut cache_b = ParticleCache::default();
109 let img_a = render_particles_2d(&mut cache_a, &comp, render_id, 25.0, dims, &expr, &sprites);
110 let img_b = render_particles_2d(&mut cache_b, &comp, render_id, 25.0, dims, &expr, &sprites);
111 assert_eq!(img_a, img_b, "particle render must be bit-identical across runs");
112 assert!(
113 count_nonzero_alpha(&img_a) > 50,
114 "expected non-empty rendered particles"
115 );
116
117 // 2. Force affects particle trajectories: bypassing pPointForce1 changes output.
118 let mut comp_no_force = comp.clone();
119 comp_no_force.nodes[force_id.0].bypassed = true;
120 comp_no_force.revision += 1;
121 let mut cache_no_force = ParticleCache::default();
122 let img_no_force = render_particles_2d(
123 &mut cache_no_force,
124 &comp_no_force,
125 render_id,
126 25.0,
127 dims,
128 &expr,
129 &sprites,
130 );
131 assert_ne!(
132 img_a, img_no_force,
133 "pPointForce must visibly change particle trajectories"
134 );
135
136 // 3. Cache consistency & sequential speedup: stepping 25 -> 26 matches fresh 0 -> 26.
137 let t_seq_start = Instant::now();
138 let img_26_cached =
139 render_particles_2d(&mut cache_a, &comp, render_id, 26.0, dims, &expr, &sprites);
140 let seq_elapsed = t_seq_start.elapsed();
141
142 let mut fresh_cache = ParticleCache::default();
143 let t_fresh_start = Instant::now();
144 let img_26_fresh = render_particles_2d(
145 &mut fresh_cache,
146 &comp,
147 render_id,
148 26.0,
149 dims,
150 &expr,
151 &sprites,
152 );
153 let fresh_elapsed = t_fresh_start.elapsed();
154 assert_eq!(
155 img_26_cached, img_26_fresh,
156 "cached sequential step must match fresh simulation"
157 );
158 assert!(
159 seq_elapsed <= fresh_elapsed * 2 + std::time::Duration::from_millis(5),
160 "cached sequential step should be fast (seq={seq_elapsed:?}, fresh={fresh_elapsed:?})"
161 );
162
163 cache_a.clear();
164 assert!(cache_a.entries.is_empty());
165}
166
167#[test]
168fn test_01_intro_particles_if_present() {
169 let path = Path::new("/Volumes/Project/trees/fusion/01_intro.comp");
170 if !path.exists() {
171 return;
172 }
173
174 let comp = Comp::from_fusion_file(path).expect("parse 01_intro.comp");
175 let render_id = comp.node_by_name["pRender1"];
176 let emitter_id = comp.node_by_name["pEmitter1"];
177 let bc4_id = comp.node_by_name["BrightnessContrast4"];
178
179 let sources = collect_bitmap_sources(&comp, render_id);
180 assert_eq!(
181 sources,
182 vec![(emitter_id, bc4_id)],
183 "01_intro.comp pEmitter1 bitmap source should be BrightnessContrast4"
184 );
185
186 let expr = ExprEngine::new();
187 let mut sprites = HashMap::new();
188 sprites.insert(emitter_id, make_white_sprite(32));
189
190 // In 01_intro.comp, TimeStretcher1 evaluates pRender1 at SourceTime = time / 25
191 // (so comp f600 -> t=24, comp f1600 -> t=64).
192 let ts_node = &comp.nodes[comp.node_by_name["TimeStretcher1"].0];
193 let t_f600 = comp.eval_number(ts_node, "SourceTime", 600.0, 24.0, &expr);
194 let t_f1600 = comp.eval_number(ts_node, "SourceTime", 1600.0, 64.0, &expr);
195
196 let dims = [320, 180];
197 let mut cache = ParticleCache::default();
198 let start = Instant::now();
199 let buf_600 = render_particles_2d(&mut cache, &comp, render_id, t_f600, dims, &expr, &sprites);
200 let buf_1600 =
201 render_particles_2d(&mut cache, &comp, render_id, t_f1600, dims, &expr, &sprites);
202 let elapsed = start.elapsed();
203
204 let nz_600 = count_nonzero_alpha(&buf_600);
205 assert!(
206 nz_600 > 0,
207 "expected non-zero alpha pixels at f600 (SourceTime={t_f600})"
208 );
209 assert_eq!(
210 buf_1600.len(),
211 dims[0] as usize * dims[1] as usize * 4,
212 "f1600 SourceTime={t_f1600}"
213 );
214 assert!(
215 elapsed.as_secs_f64() < 2.0,
216 "01_intro particle render should be fast, took {elapsed:?}"
217 );
218}
219
220#[test]
221fn test_pbounce_reverses_velocity_and_applies_friction() {
222 let comp_src = r#"
223Composition {
224 GlobalRange = { 0, 20 },
225 RenderRange = { 0, 20 },
226 Tools = {
227 pEmitter1 = pEmitter {
228 Inputs = {
229 Number = Input { Value = 1, },
230 Lifespan = Input { Value = 50, },
231 Velocity = Input { Value = 1.0, },
232 Angle = Input { Value = -60, },
233 ["SphereRgn.Size"] = Input { Value = 0, },
234 ["SphereRgn.Translate.Y"] = Input { Value = 0.2, },
235 },
236 },
237 pBounce1 = pBounce {
238 Inputs = {
239 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
240 Elasticity = Input { Value = 0.8, },
241 Friction = Input { Value = 0.25, },
242 Spin = Input { Value = 3.0, },
243 Region = Input { Value = FuID { "CubeRgn" }, },
244 ["CubeRgn.Translate.Y"] = Input { Value = -0.25, },
245 ["CubeRgn.Width"] = Input { Value = 2.0, },
246 ["CubeRgn.Height"] = Input { Value = 0.5, },
247 ["CubeRgn.Depth"] = Input { Value = 2.0, },
248 },
249 },
250 pRender1 = pRender {
251 Inputs = {
252 Input = Input { SourceOp = "pBounce1", Source = "Output", },
253 },
254 },
255 },
256}
257"#;
258 let comp = Comp::from_fusion_str(comp_src).expect("parse pBounce comp");
259 let render_id = comp.node_by_name["pRender1"];
260 let plan = build_particle_plan(&comp, render_id);
261 let expr = ExprEngine::new();
262 let mut state = SimState::default();
263
264 // Step until the first emitted particle (born at f=0 at y=0.2, vy≈-0.0866, vx=0.05)
265 // crosses the floor at y=0.0 around frame 3.
266 for f in 0..=4 {
267 step_simulation(&mut state, &comp, &plan, f, &expr);
268 }
269 let first = state.particles.first().expect("particle emitted");
270 let init_vx = 0.1 * (-60.0_f64).to_radians().cos();
271 let init_vy = 0.1 * (-60.0_f64).to_radians().sin();
272 assert!(
273 first.vel[1] > 0.0,
274 "pBounce should reverse downward Y velocity (got vy={})",
275 first.vel[1]
276 );
277 assert!(
278 (first.vel[1] - (-init_vy * 0.8)).abs() < 1e-4,
279 "expected reflected vy={}, got {}",
280 -init_vy * 0.8,
281 first.vel[1]
282 );
283 assert!(
284 (first.vel[0] - init_vx * 0.75).abs() < 1e-4,
285 "expected friction-damped vx={}, got {}",
286 init_vx * 0.75,
287 first.vel[0]
288 );
289 assert!(first.spin_z.abs() > 0.5, "expected Spin impulse on bounce");
290 assert!(first.pos[1] > 0.0, "bounced particle should be above floor y=0");
291}
292
293/// Single-particle comp: `Number` is a spline that is 1 at frame 0 and 0 afterwards.
294fn single_particle_comp(emitter_inputs: &str, forces: &str, last_node: &str) -> Comp {
295 let src = format!(
296 r#"
297Composition {{
298 GlobalRange = {{ 0, 100 }},
299 RenderRange = {{ 0, 100 }},
300 Tools = {{
301 EN = BezierSpline {{
302 KeyFrames = {{
303 [0] = {{ 1, Flags = {{ Linear = true }} }},
304 [1] = {{ 0, Flags = {{ Linear = true }} }}
305 }}
306 }},
307 pEmitter1 = pEmitter {{
308 Inputs = {{
309 Number = Input {{ SourceOp = "EN", Source = "Value", }},
310 Lifespan = Input {{ Value = 100, }},
311 ["SphereRgn.Size"] = Input {{ Value = 0, }},
312 {emitter_inputs}
313 }},
314 }},
315 {forces}
316 pRender1 = pRender {{
317 Inputs = {{
318 Input = Input {{ SourceOp = "{last_node}", Source = "Output", }},
319 }},
320 }},
321 }},
322}}
323"#
324 );
325 Comp::from_fusion_str(&src).expect("parse single-particle comp")
326}
327
328fn render(comp: &Comp, time: f64, dims: [u32; 2], sprites: &HashMap<NodeId, SpriteImage>) -> Vec<u8> {
329 let mut cache = ParticleCache::default();
330 render_particles_2d(&mut cache, comp, comp.node_by_name["pRender1"], time, dims, &ExprEngine::new(), sprites)
331}
332
333/// `(x, y, alpha)` of every pixel with non-zero alpha.
334fn lit(buf: &[u8], width: usize) -> Vec<(usize, usize, u8)> {
335 buf.chunks_exact(4)
336 .enumerate()
337 .filter(|(_, px)| px[3] > 0)
338 .map(|(i, px)| (i % width, i / width, px[3]))
339 .collect()
340}
341
342fn alpha_mass(buf: &[u8]) -> f64 {
343 buf.chunks_exact(4).map(|px| px[3] as f64 / 255.0).sum()
344}
345
346#[test]
347fn point_style_is_one_pixel_regardless_of_size() {
348 let comp = single_particle_comp(r#"["ParticleStyle.Size"] = Input { Value = 5, },"#, "", "pEmitter1");
349 let buf = render(&comp, 0.0, [200, 100], &HashMap::new());
350 assert_eq!(lit(&buf, 200), vec![(100, 50, 255)]);
351}
352
353#[test]
354fn blob_is_gaussian_with_sigma_per_size_unit() {
355 let comp = single_particle_comp(
356 r#"Style = Input { Value = FuID { "ParticleStyleBlob" }, }, ["ParticleStyle.Size"] = Input { Value = 2, },"#,
357 "",
358 "pEmitter1",
359 );
360 // Fusion 21.1: Size 2 blob has alpha mass ~276 (= 2*pi*(2*3.316)^2).
361 let mass = alpha_mass(&render(&comp, 0.0, [256, 256], &HashMap::new()));
362 assert!((mass - 276.0).abs() < 8.0, "blob mass {mass}");
363}
364
365#[test]
366fn newborn_moves_once_at_tenth_width_velocity() {
367 let comp = single_particle_comp(
368 r#"VelocityControls = Input { Value = 1, }, Velocity = Input { Value = 1, }, Angle = Input { Value = 0, },"#,
369 "",
370 "pEmitter1",
371 );
372 let at = |t: f64| lit(&render(&comp, t, [200, 100], &HashMap::new()), 200)[0].0;
373 assert_eq!(at(0.0), 120);
374 assert_eq!(at(2.0), 160);
375}
376
377#[test]
378fn directional_force_accelerates_down_by_strength_over_one_hundred() {
379 let comp = single_particle_comp(
380 "",
381 r#"pDirectionalForce1 = pDirectionalForce {
382 Inputs = {
383 Strength = Input { Value = 1, },
384 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
385 },
386 },"#,
387 "pDirectionalForce1",
388 );
389 // y(f) = 0.01 * f(f+1)/2 widths below the spawn point.
390 let buf = render(&comp, 4.0, [1000, 1000], &HashMap::new());
391 assert_eq!(lit(&buf, 1000), vec![(500, 600, 255)]);
392}
393
394#[test]
395fn particle_lives_while_age_is_below_lifespan() {
396 let comp = single_particle_comp(r#"Lifespan = Input { Value = 3, },"#, "", "pEmitter1");
397 let count = |t: f64| lit(&render(&comp, t, [64, 64], &HashMap::new()), 64).len();
398 assert_eq!((count(0.0), count(2.0), count(3.0)), (1, 1, 0));
399}
400
401#[test]
402fn fade_out_starts_at_fade_out_fraction_of_life() {
403 let comp = single_particle_comp(
404 r#"Lifespan = Input { Value = 20, }, Style = Input { Value = FuID { "ParticleStyleBlob" }, },
405 ["ParticleStyle.Size"] = Input { Value = 2, }, ["ParticleStyle.FadeOut"] = Input { Value = 0.5, },"#,
406 "",
407 "pEmitter1",
408 );
409 let mass = |t: f64| alpha_mass(&render(&comp, t, [256, 256], &HashMap::new()));
410 assert!((mass(15.0) / mass(10.0) - 0.5).abs() < 0.02);
411}
412
413#[test]
414fn bitmap_width_is_size_times_sprite_pixels() {
415 let comp = single_particle_comp(
416 r#"Style = Input { Value = FuID { "ParticleStyleBitmap" }, }, ["ParticleStyle.Size"] = Input { Value = 2, },"#,
417 "",
418 "pEmitter1",
419 );
420 let mut sprites = HashMap::new();
421 sprites.insert(comp.node_by_name["pEmitter1"], make_white_sprite(4));
422 let pixels = lit(&render(&comp, 0.0, [200, 100], &sprites), 200);
423 let (min_x, max_x) = pixels.iter().fold((usize::MAX, 0), |(lo, hi), &(x, _, _)| (lo.min(x), hi.max(x)));
424 assert!((8..=9).contains(&(max_x - min_x + 1)), "bitmap width {}", max_x - min_x + 1);
425}
426
427#[test]
428fn default_region_is_sphere_of_diameter_one_tenth_width() {
429 let comp = Comp::from_fusion_str("Composition { Tools = { pEmitter1 = pEmitter { Inputs = { }, }, }, }")
430 .expect("parse bare emitter");
431 let node = &comp.nodes[comp.node_by_name["pEmitter1"].0];
432 match RegionSpec::from_node(&comp, node, 0.0, &ExprEngine::new()) {
433 RegionSpec::Sphere { radius, .. } => assert!((radius - 0.05).abs() < 1e-12),
434 _ => panic!("default region must be a sphere"),
435 }
436}
437
438#[test]
439fn depth_scales_screen_position_by_camera_distance() {
440 let comp = single_particle_comp(
441 r#"["SphereRgn.Translate.X"] = Input { Value = 0.2, }, ["SphereRgn.Translate.Z"] = Input { Value = 0.9722222222222222, },"#,
442 "",
443 "pEmitter1",
444 );
445 // z equal to the camera distance halves the projected offset: x = (0.2 * 0.5 + 0.5) * 1000.
446 let buf = render(&comp, 0.0, [1000, 1000], &HashMap::new());
447 assert_eq!(lit(&buf, 1000), vec![(600, 500, 255)]);
448}
449
450#[test]
451fn particle_cache_advances_past_600_incrementally_and_scrubs_with_snapshots() {
452 let comp_src = r#"
453Composition {
454 GlobalRange = { 0, 800 },
455 RenderRange = { 0, 800 },
456 Tools = {
457 pEmitter1 = pEmitter {
458 Inputs = {
459 RandomSeed = Input { Value = 7, },
460 Number = Input { Value = 2, },
461 Lifespan = Input { Value = 25, },
462 Velocity = Input { Value = 0.2, },
463 VelocityVariance = Input { Value = 0.1, },
464 AngleVariance = Input { Value = 180, },
465 },
466 },
467 pRender1 = pRender {
468 Inputs = {
469 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
470 },
471 },
472 },
473}
474"#;
475 let comp = Comp::from_fusion_str(comp_src).expect("parse particle comp");
476 let render_id = comp.node_by_name["pRender1"];
477 let expr = ExprEngine::new();
478 let sprites = HashMap::new();
479 let dims = [64, 64];
480
481 let mut cache = ParticleCache::default();
482 let mut last_img = Vec::new();
483 for f in 580..=625 {
484 last_img = render_particles_2d(&mut cache, &comp, render_id, f as f64, dims, &expr, &sprites);
485 }
486
487 let key = (
488 "pRender1".to_owned(),
489 particle_subgraph_hash(&comp, render_id, 0),
490 );
491 let cached = cache.entries.get(&key).expect("cached entry");
492 assert_eq!(cached.base_start, 0);
493 assert_eq!(cached.current_frame, 625);
494 assert!(cached.snapshots.contains_key(&600), "expected snapshot at frame 600");
495
496 // Scrubbing back to frame 605 restores snapshot 600 and matches direct render at 605.
497 let scrub_605 = render_particles_2d(&mut cache, &comp, render_id, 605.0, dims, &expr, &sprites);
498 let mut fresh_cache = ParticleCache::default();
499 let fresh_605 = render_particles_2d(&mut fresh_cache, &comp, render_id, 605.0, dims, &expr, &sprites);
500 assert_eq!(scrub_605, fresh_605, "scrubbed frame 605 must match fresh simulation");
501
502 let mut fresh_625_cache = ParticleCache::default();
503 let fresh_625 = render_particles_2d(&mut fresh_625_cache, &comp, render_id, 625.0, dims, &expr, &sprites);
504 assert_eq!(last_img, fresh_625, "incremental advance past 600 must match fresh simulation");
505}
506
507#[test]
508fn particle_cache_ignores_unrelated_comp_edits_and_node_id_shifts() {
509 let with_unrelated = r#"
510Composition {
511 GlobalRange = { 0, 100 },
512 RenderRange = { 0, 100 },
513 Tools = {
514 UnrelatedBg = Background {
515 Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, },
516 },
517 pEmitter1 = pEmitter {
518 Inputs = {
519 RandomSeed = Input { Value = 19, },
520 Number = Input { Value = 8, },
521 Lifespan = Input { Value = 40, },
522 Velocity = Input { Value = 0.5, },
523 VelocityVariance = Input { Value = 0.25, },
524 AngleVariance = Input { Value = 180, },
525 },
526 },
527 pRender1 = pRender {
528 Inputs = {
529 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
530 },
531 },
532 },
533}
534"#;
535 let without_unrelated = r#"
536Composition {
537 GlobalRange = { 0, 100 },
538 RenderRange = { 0, 100 },
539 Tools = {
540 pEmitter1 = pEmitter {
541 Inputs = {
542 RandomSeed = Input { Value = 19, },
543 Number = Input { Value = 8, },
544 Lifespan = Input { Value = 40, },
545 Velocity = Input { Value = 0.5, },
546 VelocityVariance = Input { Value = 0.25, },
547 AngleVariance = Input { Value = 180, },
548 },
549 },
550 pRender1 = pRender {
551 Inputs = {
552 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
553 },
554 },
555 },
556}
557"#;
558 let mut comp_a = Comp::from_fusion_str(with_unrelated).expect("parse comp_a");
559 let comp_b = Comp::from_fusion_str(without_unrelated).expect("parse comp_b");
560 let ra = comp_a.node_by_name["pRender1"];
561 let rb = comp_b.node_by_name["pRender1"];
562 assert_ne!(ra, rb, "deleting UnrelatedBg should shift NodeIds");
563
564 let expr = ExprEngine::new();
565 let sprites = HashMap::new();
566 let dims = [64, 64];
567
568 let mut cache_a = ParticleCache::default();
569 let img_a_20 = render_particles_2d(&mut cache_a, &comp_a, ra, 20.0, dims, &expr, &sprites);
570
571 // Bumping comp.revision (simulating unrelated node edit) reuses cached simulation.
572 comp_a.revision += 99;
573 let hash_before = particle_subgraph_hash(&comp_a, ra, 0);
574 let hash_after_del = particle_subgraph_hash(&comp_b, rb, 0);
575 assert_eq!(hash_before, hash_after_del, "subgraph hash must ignore NodeId shifts and unrelated nodes");
576
577 let mut cache_b = ParticleCache::default();
578 let img_b_20 = render_particles_2d(&mut cache_b, &comp_b, rb, 20.0, dims, &expr, &sprites);
579 assert_eq!(img_a_20, img_b_20, "deleting an unrelated node must not re-randomize particles");
580
581 // Stepping comp_b using cache_a (which has old NodeIds!) must still match fresh comp_b at frame 21.
582 let img_a_to_b_21 = render_particles_2d(&mut cache_a, &comp_b, rb, 21.0, dims, &expr, &sprites);
583 let mut fresh_b = ParticleCache::default();
584 let img_b_21 = render_particles_2d(&mut fresh_b, &comp_b, rb, 21.0, dims, &expr, &sprites);
585 assert_eq!(img_a_to_b_21, img_b_21);
586}
587
588#[test]
589fn cyclic_expression_modifier_does_not_stack_overflow() {
590 let comp_src = r#"
591Composition {
592 GlobalRange = { 0, 20 },
593 RenderRange = { 0, 20 },
594 Tools = ordered() {
595 Expr1 = Expression {
596 Inputs = {
597 n1 = Input { SourceOp = "Expr1", Source = "NumberResult", },
598 NumberExpression = Input { Value = "n1 + 4", },
599 },
600 },
601 pEmitter1 = pEmitter {
602 Inputs = {
603 RandomSeed = Input { Value = 7, },
604 Number = Input { SourceOp = "Expr1", Source = "NumberResult", },
605 Lifespan = Input { Value = 15, },
606 Velocity = Input { Value = 0.2, },
607 },
608 },
609 pRender1 = pRender {
610 Inputs = {
611 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
612 },
613 },
614 },
615}
616"#;
617 let comp = Comp::from_fusion_str(comp_src).expect("parse cyclic Expr1 comp");
618 assert!(comp.expression_modifiers.contains_key("Expr1"));
619 let pr = comp.find_node("pRender1").expect("find pRender1");
620 let expr = ExprEngine::new();
621 let sprites = HashMap::new();
622 let mut cache = ParticleCache::default();
623
624 // Both subgraph hashing and particle evaluation must terminate cleanly without overflowing.
625 let h1 = particle_subgraph_hash(&comp, pr, 0);
626 let h2 = particle_subgraph_hash(&comp, pr, 0);
627 assert_eq!(h1, h2);
628
629 let img = render_particles_2d(&mut cache, &comp, pr, 5.0, [64, 64], &expr, &sprites);
630 assert_eq!(img.len(), 64 * 64 * 4);
631}