diff --git a/crates/engine/src/eval/dispatch.rs b/crates/engine/src/eval/dispatch.rs new file mode 100644 index 0000000000000000000000000000000000000000..3f9c49ac8371526fc7c654a5e4bfe6cde54e8212 --- /dev/null +++ b/crates/engine/src/eval/dispatch.rs @@ -0,0 +1,428 @@ +//! GPU texture allocation, compute shader dispatch, readback, and viewer upload helpers. + +use std::cell::RefCell; +use std::time::Instant; + +use bytemuck::{Pod, Zeroable}; +use model::BitDepth; + +use crate::cache::{CachedTexture, EvalStats}; + +use super::registry::{ShaderOp, ShaderRegistry}; +use super::{DisplaySettings, Engine}; + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +pub(super) struct UniformParams { + pub(super) p: [[f32; 4]; 16], +} + +impl Default for UniformParams { + fn default() -> Self { + Self { p: [[0.0; 4]; 16] } + } +} + +impl Engine { + pub(super) fn alloc_tex(&self, size: [u32; 2], depth: BitDepth, content_hash: u64) -> CachedTexture { + self.alloc_tex_dod(size, [0, 0], size, depth, content_hash) + } + + pub(super) fn alloc_tex_like( + &self, + src: &CachedTexture, + depth: BitDepth, + content_hash: u64, + ) -> CachedTexture { + let mut t = self.alloc_tex_dod(src.size, src.origin, src.canvas_size, depth, content_hash); + t.tex_scale = src.tex_scale; + t + } + + pub(super) fn crop_to_canvas(&self, enc: &mut wgpu::CommandEncoder, tex: CachedTexture) -> CachedTexture { + if !tex.has_dod() { + return tex; + } + let mut cropped = self.alloc_tex(tex.canvas_size, tex.depth, tex.content_hash ^ 0xD0D0); + cropped.tex_scale = tex.tex_scale; + let mut params = UniformParams::default(); + params.p[0] = [1.0, 1.0, 0.0, 0.0]; + params.p[4] = [ + tex.origin[0] as f32, + tex.origin[1] as f32, + tex.canvas_size[0] as f32, + tex.canvas_size[1] as f32, + ]; + self.dispatch_op( + enc, + ShaderOp::DisplayBlit, + &tex.view, + &self.dummy.view, + &self.dummy.view, + &cropped, + ¶ms, + ); + cropped + } + + pub(super) fn alloc_tex_dod( + &self, + size: [u32; 2], + origin: [i32; 2], + canvas_size: [u32; 2], + depth: BitDepth, + content_hash: u64, + ) -> CachedTexture { + let d = self.effective_depth(depth); + let fmt = self.texture_format_for(d); + self.cache + .acquire_texture_dod_fmt(&self.device, size, origin, canvas_size, d, fmt, content_hash) + } + + pub(super) fn pipelines_for(&self, depth: BitDepth) -> &RefCell { + match depth { + BitDepth::Int8 => &self.pipelines, + BitDepth::Int16 => self.pipelines_int16.get_or_init(|| { + RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba16Float, false)) + }), + BitDepth::Float16 => self.pipelines_f16.get_or_init(|| { + RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba16Float, true)) + }), + BitDepth::Float32 => { + if self.supports_f32_filter { + self.pipelines_f32.get_or_init(|| { + RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba32Float, true)) + }) + } else { + self.pipelines_f16.get_or_init(|| { + RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba16Float, true)) + }) + } + } + } + } + + /// Uploads a cached `RamFrame` directly into a viewer `wgpu::Texture` with full + /// `DisplaySettings` (exposure, gamma, channel isolate, zoom/pan) without evaluating the DAG. + pub fn render_ram_frame_into_viewer( + &self, + frame: &crate::ram_cache::RamFrame, + dst_texture: &wgpu::Texture, + display: DisplaySettings, + ) -> EvalStats { + let t0 = Instant::now(); + let mut upload_slot = self.ram_upload_tex.borrow_mut(); + let needs_alloc = upload_slot + .as_ref() + .is_none_or(|t| t.size != frame.size); + if needs_alloc { + let max_dim = self.device.limits().max_texture_dimension_2d.max(1); + let (clamped, _) = crate::cache::clamp_dims_to_limit(frame.size[0], frame.size[1], max_dim); + let tex = self.device.create_texture(&wgpu::TextureDescriptor { + label: Some("ram-viewer-upload"), + size: wgpu::Extent3d { + width: clamped[0], + height: clamped[1], + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + *upload_slot = Some(CachedTexture::from_texture(tex, clamped, 0)); + } + let src = upload_slot.as_ref().expect("ram upload texture initialized"); + if src.size == frame.size { + self.queue.write_texture( + src.texture.as_image_copy(), + &frame.rgba, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(frame.size[0] * 4), + rows_per_image: Some(frame.size[1]), + }, + wgpu::Extent3d { + width: frame.size[0], + height: frame.size[1], + depth_or_array_layers: 1, + }, + ); + } + let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("comp-ram-viewer-blit"), + }); + let dst_size = [dst_texture.width(), dst_texture.height()]; + let dst_view = dst_texture.create_view(&wgpu::TextureViewDescriptor::default()); + let mut params = UniformParams::default(); + params.p[0] = [ + 2.0_f32.powf(display.exposure), + display.gamma, + display.channel as f32, + if display.checker_bg { 1.0 } else { 0.0 }, + ]; + params.p[1] = display.uv_rect; + params.p[2] = [if display.smooth_resize { 0.0 } else { 1.0 }, 0.0, 0.0, 0.0]; + self.dispatch_to_view( + &mut encoder, + ShaderOp::DisplayBlit, + &src.view, + &self.dummy.view, + &self.dummy.view, + &dst_view, + dst_size, + ¶ms, + ); + self.queue.submit(Some(encoder.finish())); + + EvalStats { + eval_ms: t0.elapsed().as_secs_f64() * 1000.0, + cache_hits: 1, + cached_entries: self.cache.entry_count(), + cached_vram_mb: self.vram_mb(), + media_entries: self.media.entry_count(), + media_mb: self.media.total_mb(), + ..EvalStats::default() + } + } + + /// Reads back a `CachedTexture` to CPU RGBA8 bytes (for CLI `render-check` / PNG export). + /// Automatically converts Float16 / Float32 working textures to clamped RGBA8 on GPU before readback. + pub fn readback_rgba(&self, tex: &CachedTexture) -> Result, Box> { + let [w, h] = tex.size; + let bpp = 4u32; + let unpadded_bpr = w * bpp; + let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let padded_bpr = unpadded_bpr.div_ceil(align) * align; + let buf = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("readback"), + size: u64::from(padded_bpr) * u64::from(h), + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut enc = self.device.create_command_encoder(&Default::default()); + let converted; + let src_tex = if tex.format != wgpu::TextureFormat::Rgba8Unorm { + converted = create_texture(&self.device, tex.size, 0); + let mut params = UniformParams::default(); + params.p[0] = [1.0, 1.0, 0.0, 0.0]; + self.dispatch_to_view( + &mut enc, + ShaderOp::DisplayBlit, + &tex.view, + &self.dummy.view, + &self.dummy.view, + &converted.view, + converted.size, + ¶ms, + ); + &converted + } else { + tex + }; + enc.copy_texture_to_buffer( + src_tex.texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &buf, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(padded_bpr), + rows_per_image: Some(h), + }, + }, + wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, + ); + self.queue.submit(Some(enc.finish())); + + let slice = buf.slice(..); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |res| { + let _ = tx.send(res); + }); + self.device.poll(wgpu::PollType::Wait { + submission_index: None, + timeout: Some(std::time::Duration::from_secs(10)), + })?; + rx.recv()??; + let data = slice.get_mapped_range()?; + let mut out = Vec::with_capacity((w * h * 4) as usize); + for row in 0..h as usize { + let start = row * padded_bpr as usize; + out.extend_from_slice(&data[start..start + unpadded_bpr as usize]); + } + drop(data); + buf.unmap(); + Ok(out) + } + + #[allow(clippy::too_many_arguments)] + pub(super) fn dispatch_op( + &self, + enc: &mut wgpu::CommandEncoder, + op: ShaderOp, + src_a: &wgpu::TextureView, + src_b: &wgpu::TextureView, + mask: &wgpu::TextureView, + dst: &CachedTexture, + params: &UniformParams, + ) { + let reg_cell = self.pipelines_for(dst.depth); + reg_cell.borrow_mut().ensure_pipeline(&self.device, op); + let reg = reg_cell.borrow(); + let ubuf = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("op-params"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + self.queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(params)); + + let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("op-bg"), + layout: ®.bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) }, + wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(®.sampler) }, + wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst.view) }, + wgpu::BindGroupEntry { binding: 5, resource: ubuf.as_entire_binding() }, + ], + }); + + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("comp-op"), + timestamp_writes: None, + }); + pass.set_pipeline(®.pipelines[&op]); + pass.set_bind_group(0, &bg, &[]); + pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); + } + + #[allow(clippy::too_many_arguments)] + pub(super) fn dispatch_to_view( + &self, + enc: &mut wgpu::CommandEncoder, + op: ShaderOp, + src_a: &wgpu::TextureView, + src_b: &wgpu::TextureView, + mask: &wgpu::TextureView, + dst_view: &wgpu::TextureView, + dst_size: [u32; 2], + params: &UniformParams, + ) { + self.pipelines.borrow_mut().ensure_pipeline(&self.device, op); + let reg = self.pipelines.borrow(); + let ubuf = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("op-params"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + self.queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(params)); + + let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("op-bg"), + layout: ®.bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) }, + wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(®.sampler) }, + wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(dst_view) }, + wgpu::BindGroupEntry { binding: 5, resource: ubuf.as_entire_binding() }, + ], + }); + + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("comp-op"), + timestamp_writes: None, + }); + pass.set_pipeline(®.pipelines[&op]); + pass.set_bind_group(0, &bg, &[]); + pass.dispatch_workgroups(dst_size[0].div_ceil(8), dst_size[1].div_ceil(8), 1); + } +} + +pub fn create_texture(device: &wgpu::Device, size: [u32; 2], content_hash: u64) -> CachedTexture { + create_texture_dod(device, size, [0, 0], size, content_hash) +} + +pub fn create_texture_dod( + device: &wgpu::Device, + size: [u32; 2], + origin: [i32; 2], + canvas_size: [u32; 2], + content_hash: u64, +) -> CachedTexture { + create_texture_dod_fmt( + device, + size, + origin, + canvas_size, + BitDepth::Int8, + wgpu::TextureFormat::Rgba8Unorm, + content_hash, + ) +} + +pub fn create_texture_dod_fmt( + device: &wgpu::Device, + size: [u32; 2], + origin: [i32; 2], + canvas_size: [u32; 2], + depth: BitDepth, + format: wgpu::TextureFormat, + content_hash: u64, +) -> CachedTexture { + let max_dim = device.limits().max_texture_dimension_2d.max(1); + let (clamped, tex_scale) = crate::cache::clamp_dims_to_limit(size[0], size[1], max_dim); + let eff_origin = if tex_scale < 1.0 { + [ + (origin[0] as f32 * tex_scale).round() as i32, + (origin[1] as f32 * tex_scale).round() as i32, + ] + } else { + origin + }; + let eff_canvas = if size == canvas_size { + clamped + } else if tex_scale < 1.0 { + [ + ((canvas_size[0].max(1) as f32 * tex_scale).round() as u32).max(1), + ((canvas_size[1].max(1) as f32 * tex_scale).round() as u32).max(1), + ] + } else { + [canvas_size[0].max(1), canvas_size[1].max(1)] + }; + let tex = device.create_texture(&wgpu::TextureDescriptor { + label: Some("comp-tex"), + size: wgpu::Extent3d { + width: clamped[0], + height: clamped[1], + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::STORAGE_BINDING + | wgpu::TextureUsages::COPY_SRC + | wgpu::TextureUsages::COPY_DST + | wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + let mut cached = CachedTexture::from_texture_dod_depth( + tex, + clamped, + eff_origin, + eff_canvas, + depth, + content_hash, + ); + cached.tex_scale = tex_scale; + cached +} diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index 636692a1126c419199cd21aa8dcfdf7c1e285919..bca0d8e52673199cfd5f9d33ec470761f18556a4 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -3,7 +3,6 @@ use crate::cache::{CacheMode, CachedTexture, EvalStats, NodeCache}; use crate::media::{MediaCache, TextPlusParams, rasterize_polyline_mask, rasterize_text_plus}; -use bytemuck::{Pod, Zeroable}; use model::{BitDepth, Comp, ExprEngine, Node, NodeId, default_main_input_port}; use std::cell::{OnceCell, RefCell}; use std::collections::{HashMap, HashSet}; @@ -22,19 +21,14 @@ mod paint; mod shapes; mod warps; mod text_3d; +mod registry; +mod dispatch; +mod output_cache; - -#[repr(C)] -#[derive(Clone, Copy, Pod, Zeroable)] -struct UniformParams { - p: [[f32; 4]; 16], -} - -impl Default for UniformParams { - fn default() -> Self { - Self { p: [[0.0; 4]; 16] } - } -} +use dispatch::UniformParams; +pub use dispatch::{create_texture, create_texture_dod, create_texture_dod_fmt}; +use output_cache::OutputCache; +use registry::{ShaderOp, ShaderRegistry}; #[derive(Clone, Copy, Debug, PartialEq)] pub struct DisplaySettings { @@ -62,340 +56,6 @@ impl Default for DisplaySettings { } } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -enum ShaderDomain { - Composite, - Color, - BlurGlow, - Transform, - Masks, - KeyersGen, - ArchiveFx, -} - -impl ShaderDomain { - fn source(self) -> &'static str { - match self { - Self::Composite => include_str!("../shaders/composite.wgsl"), - Self::Color => include_str!("../shaders/color.wgsl"), - Self::BlurGlow => include_str!("../shaders/blur_glow.wgsl"), - Self::Transform => include_str!("../shaders/transform.wgsl"), - Self::Masks => include_str!("../shaders/masks.wgsl"), - Self::KeyersGen => include_str!("../shaders/keyers_gen.wgsl"), - Self::ArchiveFx => include_str!("../shaders/archive_fx.wgsl"), - } - } - - fn label(self) -> &'static str { - match self { - Self::Composite => "compositor-shaders-composite", - Self::Color => "compositor-shaders-color", - Self::BlurGlow => "compositor-shaders-blur-glow", - Self::Transform => "compositor-shaders-transform", - Self::Masks => "compositor-shaders-masks", - Self::KeyersGen => "compositor-shaders-keyers-gen", - Self::ArchiveFx => "compositor-shaders-archive-fx", - } - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -enum ShaderOp { - Bg, - Merge, - Transform, - Bc, - Cc, - ColorGain, - LumaKey, - Blur, - DirBlur, - FastNoise, - Displace, - MaskShape, - MaskCombine, - MaskApply, - BitmapMask, - Colorize, - ColorCurves, - XfChroma, - GamutConvert, - VariBlur, - OutlineTint, - OutlineComposite, - #[allow(dead_code)] - CustomWave, - Crop, - GlowAdd, - XGlowPrep, - XGlowAccum, - DisplayBlit, - Invert, - ChannelBoolean, - Filter, - HueCurves, - UltraKeyer, - Dissolve, - Homography, - ShadowComp, - Plasma, - FilmGrain, - SetDomain, - ChangeDepth, - Vortex, - KScope, - Drip, - Dent, - PerspectivePos, - DaySky, - GridWarp, -} - -impl ShaderOp { - fn domain(self) -> ShaderDomain { - match self { - Self::Bg - | Self::Merge - | Self::DisplayBlit - | Self::ChannelBoolean - | Self::Dissolve - | Self::ShadowComp - | Self::SetDomain - | Self::ChangeDepth => ShaderDomain::Composite, - - Self::Bc - | Self::Cc - | Self::ColorGain - | Self::Colorize - | Self::ColorCurves - | Self::GamutConvert - | Self::Invert - | Self::HueCurves => ShaderDomain::Color, - - Self::Blur - | Self::DirBlur - | Self::VariBlur - | Self::GlowAdd - | Self::XGlowPrep - | Self::XGlowAccum - | Self::Filter - | Self::FilmGrain => ShaderDomain::BlurGlow, - - Self::Transform - | Self::Displace - | Self::XfChroma - | Self::Crop - | Self::Homography - | Self::Vortex - | Self::KScope => ShaderDomain::Transform, - - Self::MaskShape - | Self::MaskCombine - | Self::MaskApply - | Self::BitmapMask => ShaderDomain::Masks, - - Self::LumaKey - | Self::FastNoise - | Self::OutlineTint - | Self::OutlineComposite - | Self::CustomWave - | Self::UltraKeyer - | Self::Plasma => ShaderDomain::KeyersGen, - - Self::Drip | Self::Dent | Self::PerspectivePos | Self::DaySky | Self::GridWarp => { - ShaderDomain::ArchiveFx - } - } - } - - fn entry_point(self) -> &'static str { - match self { - Self::Bg => "bg_op", - Self::Merge => "merge_op", - Self::Transform => "transform_op", - Self::Bc => "bc_op", - Self::Cc => "cc_op", - Self::ColorGain => "color_gain_op", - Self::LumaKey => "luma_key_op", - Self::Blur => "blur_op", - Self::DirBlur => "dir_blur_op", - Self::FastNoise => "fast_noise_op", - Self::Displace => "displace_op", - Self::MaskShape => "mask_shape_op", - Self::MaskCombine => "mask_combine_op", - Self::MaskApply => "mask_apply_op", - Self::BitmapMask => "bitmap_mask_op", - Self::Colorize => "colorize_op", - Self::ColorCurves => "color_curves_op", - Self::XfChroma => "xf_chroma_op", - Self::GamutConvert => "gamut_convert_op", - Self::VariBlur => "vari_blur_op", - Self::OutlineTint => "outline_tint", - Self::OutlineComposite => "outline_composite", - Self::CustomWave => "custom_wave_op", - Self::Crop => "crop_op", - Self::GlowAdd => "glow_add_op", - Self::XGlowPrep => "xglow_prep_op", - Self::XGlowAccum => "xglow_accum_op", - Self::DisplayBlit => "display_blit_op", - Self::Invert => "invert_op", - Self::ChannelBoolean => "channel_boolean_op", - Self::Filter => "filter_op", - Self::HueCurves => "hue_curves_op", - Self::UltraKeyer => "ultra_keyer_op", - Self::Dissolve => "dissolve_op", - Self::Homography => "homography_op", - Self::ShadowComp => "shadow_comp_op", - Self::Plasma => "plasma_op", - Self::FilmGrain => "film_grain_op", - Self::SetDomain => "set_domain_op", - Self::ChangeDepth => "change_depth_op", - Self::Vortex => "vortex_op", - Self::KScope => "kscope_op", - Self::Drip => "drip_op", - Self::Dent => "dent_op", - Self::PerspectivePos => "perspective_pos_op", - Self::DaySky => "day_sky_op", - Self::GridWarp => "grid_warp_op", - } - } -} - -const COMMON_WGSL: &str = include_str!("../shaders/common.wgsl"); - -struct ShaderRegistry { - format: wgpu::TextureFormat, - hdr_float: bool, - bgl: wgpu::BindGroupLayout, - pl: wgpu::PipelineLayout, - sampler: wgpu::Sampler, - modules: HashMap, - pipelines: HashMap, -} - -impl ShaderRegistry { - fn new(device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) -> Self { - let tex_entry = |binding| wgpu::BindGroupLayoutEntry { - binding, - visibility: wgpu::ShaderStages::COMPUTE, - ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Float { filterable: true }, - view_dimension: wgpu::TextureViewDimension::D2, - multisampled: false, - }, - count: None, - }; - let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("compositor-bgl"), - entries: &[ - tex_entry(0), - tex_entry(1), - tex_entry(2), - wgpu::BindGroupLayoutEntry { - binding: 3, - visibility: wgpu::ShaderStages::COMPUTE, - ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 4, - visibility: wgpu::ShaderStages::COMPUTE, - ty: wgpu::BindingType::StorageTexture { - access: wgpu::StorageTextureAccess::WriteOnly, - format, - view_dimension: wgpu::TextureViewDimension::D2, - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 5, - visibility: wgpu::ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - ], - }); - - let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("compositor-pl"), - bind_group_layouts: &[Some(&bgl)], - immediate_size: 0, - }); - - let sampler = device.create_sampler(&wgpu::SamplerDescriptor { - label: Some("compositor-linear"), - address_mode_u: wgpu::AddressMode::ClampToEdge, - address_mode_v: wgpu::AddressMode::ClampToEdge, - mag_filter: wgpu::FilterMode::Linear, - min_filter: wgpu::FilterMode::Linear, - mipmap_filter: wgpu::MipmapFilterMode::Nearest, - ..Default::default() - }); - - Self { - format, - hdr_float, - bgl, - pl, - sampler, - modules: HashMap::new(), - pipelines: HashMap::new(), - } - } - - fn ensure_pipeline(&mut self, device: &wgpu::Device, op: ShaderOp) { - if self.pipelines.contains_key(&op) { - return; - } - let domain = op.domain(); - let format = self.format; - let hdr_float = self.hdr_float; - let module = self.modules.entry(domain).or_insert_with(|| { - let domain_src = domain.source(); - let mut src = String::with_capacity(COMMON_WGSL.len() + domain_src.len() + 1); - src.push_str(COMMON_WGSL); - src.push('\n'); - src.push_str(domain_src); - let storage_fmt = match format { - wgpu::TextureFormat::Rgba16Float => "rgba16float", - wgpu::TextureFormat::Rgba32Float => "rgba32float", - _ => "rgba8unorm", - }; - if storage_fmt != "rgba8unorm" { - src = src.replace( - "texture_storage_2d", - &format!("texture_storage_2d<{storage_fmt}, write>"), - ); - } - if hdr_float { - src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); - } - device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some(domain.label()), - source: wgpu::ShaderSource::Wgsl(src.into()), - }) - }); - - let entry = op.entry_point(); - let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some(entry), - layout: Some(&self.pl), - module, - entry_point: Some(entry), - compilation_options: Default::default(), - cache: None, - }); - self.pipelines.insert(op, pipeline); - } -} - -const MAX_OUTPUT_CACHE_BYTES: u64 = 128 * 1024 * 1024; -const MAX_OUTPUT_CACHE_ENTRIES: usize = 64; - pub struct Engine { device: wgpu::Device, queue: wgpu::Queue, @@ -417,9 +77,7 @@ pub struct Engine { pub expr: ExprEngine, /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame. frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>, - /// Bounded LRU of recent final output textures capped by byte budget (`min(vram_budget / 4, 128 MiB)`), - /// always keeping at least the most recent frame for `<0.1ms` warm hits during pan/zoom/exposure/scrubbing. - output_cache: std::collections::VecDeque<(u64, CachedTexture, Vec)>, + output_cache: OutputCache, /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default /// to matching the dimensions & aspect ratio of the node they mask!). mask_target_size: Option<[u32; 2]>, @@ -468,7 +126,7 @@ impl Engine { media: MediaCache::new(512), expr: ExprEngine::new(), frame_memo: HashMap::new(), - output_cache: std::collections::VecDeque::new(), + output_cache: OutputCache::new(), mask_target_size: None, proxy_scale: 1, use_proxy_clips: false, @@ -541,70 +199,6 @@ impl Engine { } } - fn alloc_tex(&self, size: [u32; 2], depth: BitDepth, content_hash: u64) -> CachedTexture { - self.alloc_tex_dod(size, [0, 0], size, depth, content_hash) - } - - fn alloc_tex_like(&self, src: &CachedTexture, depth: BitDepth, content_hash: u64) -> CachedTexture { - let mut t = self.alloc_tex_dod(src.size, src.origin, src.canvas_size, depth, content_hash); - t.tex_scale = src.tex_scale; - t - } - - fn crop_to_canvas(&self, enc: &mut wgpu::CommandEncoder, tex: CachedTexture) -> CachedTexture { - if !tex.has_dod() { - return tex; - } - let mut cropped = self.alloc_tex(tex.canvas_size, tex.depth, tex.content_hash ^ 0xD0D0); - cropped.tex_scale = tex.tex_scale; - let mut params = UniformParams::default(); - params.p[0] = [1.0, 1.0, 0.0, 0.0]; - params.p[4] = [ - tex.origin[0] as f32, - tex.origin[1] as f32, - tex.canvas_size[0] as f32, - tex.canvas_size[1] as f32, - ]; - self.dispatch_op(enc, ShaderOp::DisplayBlit, &tex.view, &self.dummy.view, &self.dummy.view, &cropped, ¶ms); - cropped - } - - fn alloc_tex_dod( - &self, - size: [u32; 2], - origin: [i32; 2], - canvas_size: [u32; 2], - depth: BitDepth, - content_hash: u64, - ) -> CachedTexture { - let d = self.effective_depth(depth); - let fmt = self.texture_format_for(d); - self.cache.acquire_texture_dod_fmt(&self.device, size, origin, canvas_size, d, fmt, content_hash) - } - - fn pipelines_for(&self, depth: BitDepth) -> &RefCell { - match depth { - BitDepth::Int8 => &self.pipelines, - BitDepth::Int16 => self.pipelines_int16.get_or_init(|| { - RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba16Float, false)) - }), - BitDepth::Float16 => self.pipelines_f16.get_or_init(|| { - RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba16Float, true)) - }), - BitDepth::Float32 => { - if self.supports_f32_filter { - self.pipelines_f32.get_or_init(|| { - RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba32Float, true)) - }) - } else { - self.pipelines_f16.get_or_init(|| { - RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba16Float, true)) - }) - } - } - } - } - pub fn device(&self) -> &wgpu::Device { &self.device } @@ -625,143 +219,10 @@ impl Engine { self.cache.mode = mode; } - fn output_cache_budget_bytes(&self) -> u64 { - if self.vram_budget_bytes < 64 * 1024 * 1024 { - 0 - } else { - (self.vram_budget_bytes / 4).min(MAX_OUTPUT_CACHE_BYTES) - } - } - - /// Total GPU bytes held by `output_cache`. - pub fn output_cache_bytes(&self) -> u64 { - self.output_cache.iter().map(|(_, tex, _)| tex.bytes).sum() - } - - /// Total resident GPU VRAM bytes across `NodeCache` (live + pooled) and `output_cache`. - pub fn vram_bytes(&self) -> u64 { - self.cache.total_vram_bytes().saturating_add(self.output_cache_bytes()) - } - - pub fn vram_mb(&self) -> f64 { - self.vram_bytes() as f64 / (1024.0 * 1024.0) - } - - fn sync_node_cache_budget(&mut self) { - let remaining_bytes = self.vram_budget_bytes.saturating_sub(self.output_cache_bytes()); - let remaining_mb = remaining_bytes / (1024 * 1024); - if self.cache.budget_bytes != remaining_mb.saturating_mul(1024 * 1024) { - self.cache.set_budget_mb(remaining_mb); - } - } - - pub fn set_vram_budget_mb(&mut self, budget_mb: u64) { - self.vram_budget_bytes = budget_mb.saturating_mul(1024 * 1024); - let cap = self.output_cache_budget_bytes(); - if cap == 0 { - self.output_cache.clear(); - } else { - while self.output_cache.len() > 1 && self.output_cache_bytes() > cap { - self.output_cache.pop_front(); - } - } - self.sync_node_cache_budget(); - } - - pub fn vram_budget_mb(&self) -> u64 { - self.vram_budget_bytes / (1024 * 1024) - } - pub fn set_media_budget_mb(&mut self, budget_mb: u64) { self.media.set_budget_mb(budget_mb); } - /// Uploads a cached `RamFrame` directly into a viewer `wgpu::Texture` with full - /// `DisplaySettings` (exposure, gamma, channel isolate, zoom/pan) without evaluating the DAG. - pub fn render_ram_frame_into_viewer( - &self, - frame: &crate::ram_cache::RamFrame, - dst_texture: &wgpu::Texture, - display: DisplaySettings, - ) -> EvalStats { - let t0 = Instant::now(); - let mut upload_slot = self.ram_upload_tex.borrow_mut(); - let needs_alloc = upload_slot - .as_ref() - .is_none_or(|t| t.size != frame.size); - if needs_alloc { - let max_dim = self.device.limits().max_texture_dimension_2d.max(1); - let (clamped, _) = crate::cache::clamp_dims_to_limit(frame.size[0], frame.size[1], max_dim); - let tex = self.device.create_texture(&wgpu::TextureDescriptor { - label: Some("ram-viewer-upload"), - size: wgpu::Extent3d { - width: clamped[0], - height: clamped[1], - depth_or_array_layers: 1, - }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::Rgba8Unorm, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - *upload_slot = Some(CachedTexture::from_texture(tex, clamped, 0)); - } - let src = upload_slot.as_ref().expect("ram upload texture initialized"); - if src.size == frame.size { - self.queue.write_texture( - src.texture.as_image_copy(), - &frame.rgba, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(frame.size[0] * 4), - rows_per_image: Some(frame.size[1]), - }, - wgpu::Extent3d { - width: frame.size[0], - height: frame.size[1], - depth_or_array_layers: 1, - }, - ); - } - let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { - label: Some("comp-ram-viewer-blit"), - }); - let dst_size = [dst_texture.width(), dst_texture.height()]; - let dst_view = dst_texture.create_view(&wgpu::TextureViewDescriptor::default()); - let mut params = UniformParams::default(); - params.p[0] = [ - 2.0_f32.powf(display.exposure), - display.gamma, - display.channel as f32, - if display.checker_bg { 1.0 } else { 0.0 }, - ]; - params.p[1] = display.uv_rect; - params.p[2] = [if display.smooth_resize { 0.0 } else { 1.0 }, 0.0, 0.0, 0.0]; - self.dispatch_to_view( - &mut encoder, - ShaderOp::DisplayBlit, - &src.view, - &self.dummy.view, - &self.dummy.view, - &dst_view, - dst_size, - ¶ms, - ); - self.queue.submit(Some(encoder.finish())); - - EvalStats { - eval_ms: t0.elapsed().as_secs_f64() * 1000.0, - cache_hits: 1, - cached_entries: self.cache.entry_count(), - cached_vram_mb: self.vram_mb(), - media_entries: self.media.entry_count(), - media_mb: self.media.total_mb(), - ..EvalStats::default() - } - } - pub fn bust_all_caches(&mut self) { self.output_cache.clear(); self.sync_node_cache_budget(); @@ -793,49 +254,6 @@ impl Engine { self.cache.bust_subtree(node) } - fn output_cache_key(&self, comp: &Comp, target: NodeId, time: f64) -> u64 { - let mut h = DefaultHasher::new(); - self.cache.gpu_salt.hash(&mut h); - comp.name.hash(&mut h); - comp.path.hash(&mut h); - comp.nodes.len().hash(&mut h); - comp.revision.hash(&mut h); - target.hash(&mut h); - time.to_bits().hash(&mut h); - self.proxy_scale.hash(&mut h); - self.hiq.hash(&mut h); - self.use_proxy_clips.hash(&mut h); - h.finish() - } - - fn output_cache_get(&mut self, key: u64) -> Option<(CachedTexture, Vec)> { - if self.cache.mode == CacheMode::Bypass { - return None; - } - let pos = self.output_cache.iter().position(|(k, _, _)| *k == key)?; - let entry = self.output_cache.remove(pos)?; - let res = (entry.1.clone(), entry.2.clone()); - self.output_cache.push_back(entry); - Some(res) - } - - fn output_cache_insert(&mut self, key: u64, tex: CachedTexture, unsupported: Vec) { - let cap = self.output_cache_budget_bytes(); - if self.cache.mode == CacheMode::Bypass || cap == 0 { - return; - } - if let Some(pos) = self.output_cache.iter().position(|(k, _, _)| *k == key) { - self.output_cache.remove(pos); - } - self.output_cache.push_back((key, tex, unsupported)); - while self.output_cache.len() > 1 - && (self.output_cache_bytes() > cap || self.output_cache.len() > MAX_OUTPUT_CACHE_ENTRIES) - { - self.output_cache.pop_front(); - } - self.sync_node_cache_budget(); - } - /// Evaluates `target` node at `time` and returns its GPU texture + telemetry. pub fn evaluate( &mut self, @@ -954,75 +372,6 @@ impl Engine { stats } - /// Reads back a `CachedTexture` to CPU RGBA8 bytes (for CLI `render-check` / PNG export). - /// Automatically converts Float16 / Float32 working textures to clamped RGBA8 on GPU before readback. - pub fn readback_rgba(&self, tex: &CachedTexture) -> Result, Box> { - let [w, h] = tex.size; - let bpp = 4u32; - let unpadded_bpr = w * bpp; - let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; - let padded_bpr = unpadded_bpr.div_ceil(align) * align; - let buf = self.device.create_buffer(&wgpu::BufferDescriptor { - label: Some("readback"), - size: u64::from(padded_bpr) * u64::from(h), - usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, - mapped_at_creation: false, - }); - let mut enc = self.device.create_command_encoder(&Default::default()); - let converted; - let src_tex = if tex.format != wgpu::TextureFormat::Rgba8Unorm { - converted = create_texture(&self.device, tex.size, 0); - let mut params = UniformParams::default(); - params.p[0] = [1.0, 1.0, 0.0, 0.0]; - self.dispatch_to_view( - &mut enc, - ShaderOp::DisplayBlit, - &tex.view, - &self.dummy.view, - &self.dummy.view, - &converted.view, - converted.size, - ¶ms, - ); - &converted - } else { - tex - }; - enc.copy_texture_to_buffer( - src_tex.texture.as_image_copy(), - wgpu::TexelCopyBufferInfo { - buffer: &buf, - layout: wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(padded_bpr), - rows_per_image: Some(h), - }, - }, - wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, - ); - self.queue.submit(Some(enc.finish())); - - let slice = buf.slice(..); - let (tx, rx) = std::sync::mpsc::channel(); - slice.map_async(wgpu::MapMode::Read, move |res| { - let _ = tx.send(res); - }); - self.device.poll(wgpu::PollType::Wait { - submission_index: None, - timeout: Some(std::time::Duration::from_secs(10)), - })?; - rx.recv()??; - let data = slice.get_mapped_range()?; - let mut out = Vec::with_capacity((w * h * 4) as usize); - for row in 0..h as usize { - let start = row * padded_bpr as usize; - out.extend_from_slice(&data[start..start + unpadded_bpr as usize]); - } - drop(data); - buf.unmap(); - Ok(out) - } - fn scaled_dims(&self, w: u32, h: u32) -> [u32; 2] { let s = self.proxy_scale.max(1); [(w / s).max(1), (h / s).max(1)] @@ -1338,176 +687,6 @@ impl Engine { } h.finish() } - - #[allow(clippy::too_many_arguments)] - fn dispatch_op( - &self, - enc: &mut wgpu::CommandEncoder, - op: ShaderOp, - src_a: &wgpu::TextureView, - src_b: &wgpu::TextureView, - mask: &wgpu::TextureView, - dst: &CachedTexture, - params: &UniformParams, - ) { - let reg_cell = self.pipelines_for(dst.depth); - reg_cell.borrow_mut().ensure_pipeline(&self.device, op); - let reg = reg_cell.borrow(); - let ubuf = self.device.create_buffer(&wgpu::BufferDescriptor { - label: Some("op-params"), - size: std::mem::size_of::() as u64, - usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - self.queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(params)); - - let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("op-bg"), - layout: ®.bgl, - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) }, - wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) }, - wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) }, - wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(®.sampler) }, - wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst.view) }, - wgpu::BindGroupEntry { binding: 5, resource: ubuf.as_entire_binding() }, - ], - }); - - let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { - label: Some("comp-op"), - timestamp_writes: None, - }); - pass.set_pipeline(®.pipelines[&op]); - pass.set_bind_group(0, &bg, &[]); - pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); - } - - #[allow(clippy::too_many_arguments)] - fn dispatch_to_view( - &self, - enc: &mut wgpu::CommandEncoder, - op: ShaderOp, - src_a: &wgpu::TextureView, - src_b: &wgpu::TextureView, - mask: &wgpu::TextureView, - dst_view: &wgpu::TextureView, - dst_size: [u32; 2], - params: &UniformParams, - ) { - self.pipelines.borrow_mut().ensure_pipeline(&self.device, op); - let reg = self.pipelines.borrow(); - let ubuf = self.device.create_buffer(&wgpu::BufferDescriptor { - label: Some("op-params"), - size: std::mem::size_of::() as u64, - usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - self.queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(params)); - - let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("op-bg"), - layout: ®.bgl, - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) }, - wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) }, - wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) }, - wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(®.sampler) }, - wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(dst_view) }, - wgpu::BindGroupEntry { binding: 5, resource: ubuf.as_entire_binding() }, - ], - }); - - let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { - label: Some("comp-op"), - timestamp_writes: None, - }); - pass.set_pipeline(®.pipelines[&op]); - pass.set_bind_group(0, &bg, &[]); - pass.dispatch_workgroups(dst_size[0].div_ceil(8), dst_size[1].div_ceil(8), 1); - } - -} - -pub fn create_texture(device: &wgpu::Device, size: [u32; 2], content_hash: u64) -> CachedTexture { - create_texture_dod(device, size, [0, 0], size, content_hash) -} - -pub fn create_texture_dod( - device: &wgpu::Device, - size: [u32; 2], - origin: [i32; 2], - canvas_size: [u32; 2], - content_hash: u64, -) -> CachedTexture { - create_texture_dod_fmt( - device, - size, - origin, - canvas_size, - BitDepth::Int8, - wgpu::TextureFormat::Rgba8Unorm, - content_hash, - ) -} - -pub fn create_texture_dod_fmt( - device: &wgpu::Device, - size: [u32; 2], - origin: [i32; 2], - canvas_size: [u32; 2], - depth: BitDepth, - format: wgpu::TextureFormat, - content_hash: u64, -) -> CachedTexture { - let max_dim = device.limits().max_texture_dimension_2d.max(1); - let (clamped, tex_scale) = crate::cache::clamp_dims_to_limit(size[0], size[1], max_dim); - let eff_origin = if tex_scale < 1.0 { - [ - (origin[0] as f32 * tex_scale).round() as i32, - (origin[1] as f32 * tex_scale).round() as i32, - ] - } else { - origin - }; - let eff_canvas = if size == canvas_size { - clamped - } else if tex_scale < 1.0 { - [ - ((canvas_size[0].max(1) as f32 * tex_scale).round() as u32).max(1), - ((canvas_size[1].max(1) as f32 * tex_scale).round() as u32).max(1), - ] - } else { - [canvas_size[0].max(1), canvas_size[1].max(1)] - }; - let tex = device.create_texture(&wgpu::TextureDescriptor { - label: Some("comp-tex"), - size: wgpu::Extent3d { - width: clamped[0], - height: clamped[1], - depth_or_array_layers: 1, - }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format, - usage: wgpu::TextureUsages::TEXTURE_BINDING - | wgpu::TextureUsages::STORAGE_BINDING - | wgpu::TextureUsages::COPY_SRC - | wgpu::TextureUsages::COPY_DST - | wgpu::TextureUsages::RENDER_ATTACHMENT, - view_formats: &[], - }); - let mut cached = CachedTexture::from_texture_dod_depth( - tex, - clamped, - eff_origin, - eff_canvas, - depth, - content_hash, - ); - cached.tex_scale = tex_scale; - cached } #[cfg(test)] @@ -1935,4 +1114,51 @@ Composition { assert_eq!(eng.output_cache.len(), 1); assert_eq!(eng.output_cache_bytes(), 32 * 1024 * 1024); } + + #[test] + fn output_cache_does_not_double_count_shared_node_cache_textures() { + let mut eng = Engine::new_headless().expect("gpu"); + eng.set_vram_budget_mb(64); + + let src = r#" +Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + BG = Background { + Inputs = { + Width = Input { Value = 2048, }, + Height = Input { Value = 1024, }, + TopLeftRed = Input { Value = 0.5, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(src).expect("parse shared vram comp"); + let bg = comp.find_node("BG").unwrap(); + + let (tex, _) = eng.evaluate(&comp, bg, 0.0); + assert_eq!(tex.bytes, 8 * 1024 * 1024); + drop(tex); + + // Texture is held in both NodeCache and output_cache (Arc::strong_count >= 2). + // vram_bytes() must count the 8 MiB allocation once, not 16 MiB, and NodeCache's + // budget must remain at the full 64 MiB. + assert_eq!(eng.output_cache.unshared_bytes(), 0); + assert_eq!(eng.vram_bytes(), eng.cache.total_vram_bytes()); + assert_eq!(eng.vram_bytes(), 8 * 1024 * 1024); + assert_eq!(eng.cache.budget_bytes, 64 * 1024 * 1024); + + // If an unshared texture (strong_count == 1) is in output_cache, it IS counted + // in vram_bytes() and subtracted from NodeCache's budget. + let unshared = create_texture(&eng.device, [2048, 1024], 42); + assert_eq!(std::sync::Arc::strong_count(&unshared.texture), 1); + eng.output_cache_insert(123_456, unshared, Vec::new()); + assert_eq!(eng.output_cache.unshared_bytes(), 8 * 1024 * 1024); + assert_eq!(eng.vram_bytes(), 16 * 1024 * 1024); + assert_eq!(eng.cache.budget_bytes, 56 * 1024 * 1024); + } } diff --git a/crates/engine/src/eval/output_cache.rs b/crates/engine/src/eval/output_cache.rs new file mode 100644 index 0000000000000000000000000000000000000000..0437cf32063eeba346042f365af8e4d9a8cd4d8b --- /dev/null +++ b/crates/engine/src/eval/output_cache.rs @@ -0,0 +1,175 @@ +//! Bounded LRU cache for recent final evaluation outputs and VRAM budget accounting. + +use std::collections::VecDeque; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use model::{Comp, NodeId}; + +use crate::cache::{CacheMode, CachedTexture}; + +use super::Engine; + +const MAX_OUTPUT_CACHE_BYTES: u64 = 128 * 1024 * 1024; +const MAX_OUTPUT_CACHE_ENTRIES: usize = 64; + +/// Bounded LRU of recent final output textures capped by byte budget (`min(vram_budget / 4, 128 MiB)`), +/// always keeping at least the most recent frame for `<0.1ms` warm hits during pan/zoom/exposure/scrubbing. +pub(super) struct OutputCache { + entries: VecDeque<(u64, CachedTexture, Vec)>, +} + +impl OutputCache { + pub(super) fn new() -> Self { + Self { + entries: VecDeque::new(), + } + } + + #[cfg(test)] + pub(super) fn len(&self) -> usize { + self.entries.len() + } + + pub(super) fn clear(&mut self) { + self.entries.clear(); + } + + pub(super) fn budget_bytes(vram_budget_bytes: u64) -> u64 { + if vram_budget_bytes < 64 * 1024 * 1024 { + 0 + } else { + (vram_budget_bytes / 4).min(MAX_OUTPUT_CACHE_BYTES) + } + } + + /// Total GPU bytes referenced by `output_cache` entries (including textures shared with `NodeCache`). + pub(super) fn total_bytes(&self) -> u64 { + self.entries.iter().map(|(_, tex, _)| tex.bytes).sum() + } + + /// GPU bytes held *exclusively* by `output_cache` (`Arc::strong_count(&tex.texture) == 1`). + /// + /// Textures still resident in `NodeCache` have `strong_count >= 2` and are already counted in + /// `NodeCache::total_vram_bytes()`, so skipping them prevents double-counting against the VRAM budget. + pub(super) fn unshared_bytes(&self) -> u64 { + self.entries + .iter() + .filter(|(_, tex, _)| Arc::strong_count(&tex.texture) == 1) + .map(|(_, tex, _)| tex.bytes) + .sum() + } + + pub(super) fn get(&mut self, key: u64, mode: CacheMode) -> Option<(CachedTexture, Vec)> { + if mode == CacheMode::Bypass { + return None; + } + let pos = self.entries.iter().position(|(k, _, _)| *k == key)?; + let entry = self.entries.remove(pos)?; + let res = (entry.1.clone(), entry.2.clone()); + self.entries.push_back(entry); + Some(res) + } + + pub(super) fn insert( + &mut self, + key: u64, + tex: CachedTexture, + unsupported: Vec, + mode: CacheMode, + cap: u64, + ) { + if mode == CacheMode::Bypass || cap == 0 { + return; + } + if let Some(pos) = self.entries.iter().position(|(k, _, _)| *k == key) { + self.entries.remove(pos); + } + self.entries.push_back((key, tex, unsupported)); + while self.entries.len() > 1 + && (self.total_bytes() > cap || self.entries.len() > MAX_OUTPUT_CACHE_ENTRIES) + { + self.entries.pop_front(); + } + } + + pub(super) fn trim_to_cap(&mut self, cap: u64) { + if cap == 0 { + self.entries.clear(); + } else { + while self.entries.len() > 1 && self.total_bytes() > cap { + self.entries.pop_front(); + } + } + } +} + +impl Engine { + pub(super) fn output_cache_budget_bytes(&self) -> u64 { + OutputCache::budget_bytes(self.vram_budget_bytes) + } + + /// Total GPU bytes held by `output_cache`. + pub fn output_cache_bytes(&self) -> u64 { + self.output_cache.total_bytes() + } + + /// Total resident GPU VRAM bytes across `NodeCache` (live + pooled) and unshared `output_cache` entries. + pub fn vram_bytes(&self) -> u64 { + self.cache + .total_vram_bytes() + .saturating_add(self.output_cache.unshared_bytes()) + } + + pub fn vram_mb(&self) -> f64 { + self.vram_bytes() as f64 / (1024.0 * 1024.0) + } + + pub(super) fn sync_node_cache_budget(&mut self) { + let remaining_bytes = self + .vram_budget_bytes + .saturating_sub(self.output_cache.unshared_bytes()); + let remaining_mb = remaining_bytes / (1024 * 1024); + if self.cache.budget_bytes != remaining_mb.saturating_mul(1024 * 1024) { + self.cache.set_budget_mb(remaining_mb); + } + } + + pub fn set_vram_budget_mb(&mut self, budget_mb: u64) { + self.vram_budget_bytes = budget_mb.saturating_mul(1024 * 1024); + let cap = self.output_cache_budget_bytes(); + self.output_cache.trim_to_cap(cap); + self.sync_node_cache_budget(); + } + + pub fn vram_budget_mb(&self) -> u64 { + self.vram_budget_bytes / (1024 * 1024) + } + + pub(super) fn output_cache_key(&self, comp: &Comp, target: NodeId, time: f64) -> u64 { + let mut h = DefaultHasher::new(); + self.cache.gpu_salt.hash(&mut h); + comp.name.hash(&mut h); + comp.path.hash(&mut h); + comp.nodes.len().hash(&mut h); + comp.revision.hash(&mut h); + target.hash(&mut h); + time.to_bits().hash(&mut h); + self.proxy_scale.hash(&mut h); + self.hiq.hash(&mut h); + self.use_proxy_clips.hash(&mut h); + h.finish() + } + + pub(super) fn output_cache_get(&mut self, key: u64) -> Option<(CachedTexture, Vec)> { + self.output_cache.get(key, self.cache.mode) + } + + pub(super) fn output_cache_insert(&mut self, key: u64, tex: CachedTexture, unsupported: Vec) { + let cap = self.output_cache_budget_bytes(); + self.output_cache + .insert(key, tex, unsupported, self.cache.mode, cap); + self.sync_node_cache_budget(); + } +} diff --git a/crates/engine/src/eval/registry.rs b/crates/engine/src/eval/registry.rs new file mode 100644 index 0000000000000000000000000000000000000000..4f4987fac98a7ce142fee34198eeb692c46b9679 --- /dev/null +++ b/crates/engine/src/eval/registry.rs @@ -0,0 +1,334 @@ +//! Shader domains, GPU op enum, and lazy WGSL pipeline compilation cache. + +use std::collections::HashMap; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum ShaderDomain { + Composite, + Color, + BlurGlow, + Transform, + Masks, + KeyersGen, + ArchiveFx, +} + +impl ShaderDomain { + pub(super) fn source(self) -> &'static str { + match self { + Self::Composite => include_str!("../shaders/composite.wgsl"), + Self::Color => include_str!("../shaders/color.wgsl"), + Self::BlurGlow => include_str!("../shaders/blur_glow.wgsl"), + Self::Transform => include_str!("../shaders/transform.wgsl"), + Self::Masks => include_str!("../shaders/masks.wgsl"), + Self::KeyersGen => include_str!("../shaders/keyers_gen.wgsl"), + Self::ArchiveFx => include_str!("../shaders/archive_fx.wgsl"), + } + } + + pub(super) fn label(self) -> &'static str { + match self { + Self::Composite => "compositor-shaders-composite", + Self::Color => "compositor-shaders-color", + Self::BlurGlow => "compositor-shaders-blur-glow", + Self::Transform => "compositor-shaders-transform", + Self::Masks => "compositor-shaders-masks", + Self::KeyersGen => "compositor-shaders-keyers-gen", + Self::ArchiveFx => "compositor-shaders-archive-fx", + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum ShaderOp { + Bg, + Merge, + Transform, + Bc, + Cc, + ColorGain, + LumaKey, + Blur, + DirBlur, + FastNoise, + Displace, + MaskShape, + MaskCombine, + MaskApply, + BitmapMask, + Colorize, + ColorCurves, + XfChroma, + GamutConvert, + VariBlur, + OutlineTint, + OutlineComposite, + #[allow(dead_code)] + CustomWave, + Crop, + GlowAdd, + XGlowPrep, + XGlowAccum, + DisplayBlit, + Invert, + ChannelBoolean, + Filter, + HueCurves, + UltraKeyer, + Dissolve, + Homography, + ShadowComp, + Plasma, + FilmGrain, + SetDomain, + ChangeDepth, + Vortex, + KScope, + Drip, + Dent, + PerspectivePos, + DaySky, + GridWarp, +} + +impl ShaderOp { + pub(super) fn domain(self) -> ShaderDomain { + match self { + Self::Bg + | Self::Merge + | Self::DisplayBlit + | Self::ChannelBoolean + | Self::Dissolve + | Self::ShadowComp + | Self::SetDomain + | Self::ChangeDepth => ShaderDomain::Composite, + + Self::Bc + | Self::Cc + | Self::ColorGain + | Self::Colorize + | Self::ColorCurves + | Self::GamutConvert + | Self::Invert + | Self::HueCurves => ShaderDomain::Color, + + Self::Blur + | Self::DirBlur + | Self::VariBlur + | Self::GlowAdd + | Self::XGlowPrep + | Self::XGlowAccum + | Self::Filter + | Self::FilmGrain => ShaderDomain::BlurGlow, + + Self::Transform + | Self::Displace + | Self::XfChroma + | Self::Crop + | Self::Homography + | Self::Vortex + | Self::KScope => ShaderDomain::Transform, + + Self::MaskShape + | Self::MaskCombine + | Self::MaskApply + | Self::BitmapMask => ShaderDomain::Masks, + + Self::LumaKey + | Self::FastNoise + | Self::OutlineTint + | Self::OutlineComposite + | Self::CustomWave + | Self::UltraKeyer + | Self::Plasma => ShaderDomain::KeyersGen, + + Self::Drip | Self::Dent | Self::PerspectivePos | Self::DaySky | Self::GridWarp => { + ShaderDomain::ArchiveFx + } + } + } + + pub(super) fn entry_point(self) -> &'static str { + match self { + Self::Bg => "bg_op", + Self::Merge => "merge_op", + Self::Transform => "transform_op", + Self::Bc => "bc_op", + Self::Cc => "cc_op", + Self::ColorGain => "color_gain_op", + Self::LumaKey => "luma_key_op", + Self::Blur => "blur_op", + Self::DirBlur => "dir_blur_op", + Self::FastNoise => "fast_noise_op", + Self::Displace => "displace_op", + Self::MaskShape => "mask_shape_op", + Self::MaskCombine => "mask_combine_op", + Self::MaskApply => "mask_apply_op", + Self::BitmapMask => "bitmap_mask_op", + Self::Colorize => "colorize_op", + Self::ColorCurves => "color_curves_op", + Self::XfChroma => "xf_chroma_op", + Self::GamutConvert => "gamut_convert_op", + Self::VariBlur => "vari_blur_op", + Self::OutlineTint => "outline_tint", + Self::OutlineComposite => "outline_composite", + Self::CustomWave => "custom_wave_op", + Self::Crop => "crop_op", + Self::GlowAdd => "glow_add_op", + Self::XGlowPrep => "xglow_prep_op", + Self::XGlowAccum => "xglow_accum_op", + Self::DisplayBlit => "display_blit_op", + Self::Invert => "invert_op", + Self::ChannelBoolean => "channel_boolean_op", + Self::Filter => "filter_op", + Self::HueCurves => "hue_curves_op", + Self::UltraKeyer => "ultra_keyer_op", + Self::Dissolve => "dissolve_op", + Self::Homography => "homography_op", + Self::ShadowComp => "shadow_comp_op", + Self::Plasma => "plasma_op", + Self::FilmGrain => "film_grain_op", + Self::SetDomain => "set_domain_op", + Self::ChangeDepth => "change_depth_op", + Self::Vortex => "vortex_op", + Self::KScope => "kscope_op", + Self::Drip => "drip_op", + Self::Dent => "dent_op", + Self::PerspectivePos => "perspective_pos_op", + Self::DaySky => "day_sky_op", + Self::GridWarp => "grid_warp_op", + } + } +} + +const COMMON_WGSL: &str = include_str!("../shaders/common.wgsl"); + +pub(super) struct ShaderRegistry { + format: wgpu::TextureFormat, + hdr_float: bool, + pub(super) bgl: wgpu::BindGroupLayout, + pl: wgpu::PipelineLayout, + pub(super) sampler: wgpu::Sampler, + pub(super) modules: HashMap, + pub(super) pipelines: HashMap, +} + +impl ShaderRegistry { + pub(super) fn new(device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) -> Self { + let tex_entry = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }; + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("compositor-bgl"), + entries: &[ + tex_entry(0), + tex_entry(1), + tex_entry(2), + wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 4, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 5, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }); + + let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("compositor-pl"), + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("compositor-linear"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, + ..Default::default() + }); + + Self { + format, + hdr_float, + bgl, + pl, + sampler, + modules: HashMap::new(), + pipelines: HashMap::new(), + } + } + + pub(super) fn ensure_pipeline(&mut self, device: &wgpu::Device, op: ShaderOp) { + if self.pipelines.contains_key(&op) { + return; + } + let domain = op.domain(); + let format = self.format; + let hdr_float = self.hdr_float; + let module = self.modules.entry(domain).or_insert_with(|| { + let domain_src = domain.source(); + let mut src = String::with_capacity(COMMON_WGSL.len() + domain_src.len() + 1); + src.push_str(COMMON_WGSL); + src.push('\n'); + src.push_str(domain_src); + let storage_fmt = match format { + wgpu::TextureFormat::Rgba16Float => "rgba16float", + wgpu::TextureFormat::Rgba32Float => "rgba32float", + _ => "rgba8unorm", + }; + if storage_fmt != "rgba8unorm" { + src = src.replace( + "texture_storage_2d", + &format!("texture_storage_2d<{storage_fmt}, write>"), + ); + } + if hdr_float { + src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); + } + device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some(domain.label()), + source: wgpu::ShaderSource::Wgsl(src.into()), + }) + }); + + let entry = op.entry_point(); + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some(entry), + layout: Some(&self.pl), + module, + entry_point: Some(entry), + compilation_options: Default::default(), + cache: None, + }); + self.pipelines.insert(op, pipeline); + } +} diff --git a/crates/engine/src/particles.rs b/crates/engine/src/particles.rs index 03cec7623b31bf1142a6291431c002f4e79f679f..ac9439538174e079a510d2ee0d4a8fdc9d4e88b9 100644 --- a/crates/engine/src/particles.rs +++ b/crates/engine/src/particles.rs @@ -3,11 +3,21 @@ //! Supports `pEmitter`, `pPointForce`, `pDirectionalForce`, `pTurbulence`, //! `pDrag` / `pFriction`, `pKill`, `pBounce`, `pMerge`, and `pRender` (2D mode). -use std::collections::hash_map::DefaultHasher; -use std::collections::{BTreeMap, HashMap, HashSet}; -use std::hash::{Hash, Hasher}; +mod plan; +mod raster; +mod sim; +#[cfg(test)] +mod tests; -use model::{BezierSpline, Comp, ExprEngine, Gradient, InputBinding, Node, NodeId, ParamValue}; +pub use plan::collect_bitmap_sources; + +use std::collections::{BTreeMap, HashMap}; + +use model::{Comp, ExprEngine, NodeId}; + +use plan::{build_particle_plan, particle_subgraph_hash}; +use raster::rasterize_particles; +use sim::step_simulation; /// Maximum simultaneous live particles kept in a single simulation to prevent /// pathological comps from hanging or exhausting memory. @@ -153,392 +163,6 @@ impl SplitMix64 { } } -/// Returns true if `kind` is a Fusion particle stream operator. -fn is_particle_node_kind(kind: &str) -> bool { - matches!( - kind, - "pRender" - | "pEmitter" - | "pPointForce" - | "pDirectionalForce" - | "pTurbulence" - | "pDrag" - | "pFriction" - | "pKill" - | "pMerge" - | "pBounce" - | "pVortex" - | "pFlock" - | "pAvoid" - | "pSpawn" - | "pChangeStyle" - | "pCustom" - | "pCustomForce" - | "pGradientForce" - | "pImageEmitter" - ) || (kind.starts_with('p') - && kind - .as_bytes() - .get(1) - .is_some_and(|b| b.is_ascii_uppercase())) -} - -/// Returns the particle stream input node IDs of `node` in deterministic order. -fn particle_stream_inputs(comp: &Comp, node: &Node) -> Vec { - let mut ports: Vec<&str> = Vec::new(); - for key in node.inputs.keys() { - if key == "Input" - || key - .strip_prefix("Input") - .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit())) - { - ports.push(key.as_str()); - } - } - ports.sort_unstable(); - - let mut out = Vec::with_capacity(ports.len()); - for port in ports { - if let Some(src_name) = node.connected_node(port) { - if let Some(&src_id) = comp.node_by_name.get(src_name) { - out.push(src_id); - } - } - } - out -} - -/// Walks upstream from `render_node` through particle operators and returns every -/// `(emitter_node_id, sprite_source_node_id)` pair for `pEmitter` nodes whose -/// `ParticleStyleBitmap.DropToolsHere` input is connected. -pub fn collect_bitmap_sources(comp: &Comp, render_node: NodeId) -> Vec<(NodeId, NodeId)> { - let mut visited = HashSet::new(); - let mut out = Vec::new(); - collect_bitmap_sources_dfs(comp, render_node, &mut visited, &mut out); - out -} - -fn collect_bitmap_sources_dfs( - comp: &Comp, - node_id: NodeId, - visited: &mut HashSet, - out: &mut Vec<(NodeId, NodeId)>, -) { - if !visited.insert(node_id) { - return; - } - let Some(node) = comp.nodes.get(node_id.0) else { - return; - }; - if !is_particle_node_kind(&node.kind) { - return; - } - - if node.kind == "pEmitter" { - if let Some(src_name) = node.connected_node("ParticleStyleBitmap.DropToolsHere") { - if let Some(&src_id) = comp.node_by_name.get(src_name) { - out.push((node_id, src_id)); - } - } - } - - for up_id in particle_stream_inputs(comp, node) { - collect_bitmap_sources_dfs(comp, up_id, visited, out); - } -} - -/// Flattened, topologically-ordered particle graph upstream of a `pRender` node. -struct ParticlePlan { - emitters: Vec<(NodeId, u64)>, - /// Forces/modifiers in topological order along with the set of upstream - /// emitter name hashes whose particles flow through each modifier. - modifiers: Vec<(NodeId, HashSet)>, - emitter_nodes: HashMap, -} - -fn build_particle_plan(comp: &Comp, render_node: NodeId) -> ParticlePlan { - let mut visited = HashSet::new(); - let mut emitters = Vec::new(); - let mut modifiers = Vec::new(); - let mut upstream_emitters: HashMap> = HashMap::new(); - let mut emitter_nodes = HashMap::new(); - - build_plan_dfs( - comp, - render_node, - &mut visited, - &mut emitters, - &mut modifiers, - &mut upstream_emitters, - &mut emitter_nodes, - ); - - ParticlePlan { - emitters, - modifiers, - emitter_nodes, - } -} - -fn build_plan_dfs( - comp: &Comp, - node_id: NodeId, - visited: &mut HashSet, - emitters: &mut Vec<(NodeId, u64)>, - modifiers: &mut Vec<(NodeId, HashSet)>, - upstream_emitters: &mut HashMap>, - emitter_nodes: &mut HashMap, -) -> HashSet { - if let Some(cached) = upstream_emitters.get(&node_id) { - return cached.clone(); - } - if !visited.insert(node_id) { - return HashSet::new(); - } - - let Some(node) = comp.nodes.get(node_id.0) else { - return HashSet::new(); - }; - if !is_particle_node_kind(&node.kind) { - return HashSet::new(); - } - - let mut scope = HashSet::new(); - for up_id in particle_stream_inputs(comp, node) { - let up_set = build_plan_dfs( - comp, - up_id, - visited, - emitters, - modifiers, - upstream_emitters, - emitter_nodes, - ); - scope.extend(up_set); - } - - if node.kind == "pEmitter" { - if !node.bypassed { - let emitter_hash = stable_name_hash(&node.name); - emitters.push((node_id, emitter_hash)); - emitter_nodes.insert(emitter_hash, node_id); - scope.insert(emitter_hash); - } - } else if !node.bypassed - && matches!( - node.kind.as_str(), - "pPointForce" - | "pDirectionalForce" - | "pTurbulence" - | "pDrag" - | "pFriction" - | "pKill" - | "pBounce" - ) - { - modifiers.push((node_id, scope.clone())); - } - - upstream_emitters.insert(node_id, scope.clone()); - scope -} - -fn hash_spline(spline: &BezierSpline, h: &mut DefaultHasher) { - spline.name.hash(h); - spline.keyframes.len().hash(h); - for kf in &spline.keyframes { - kf.time.to_bits().hash(h); - kf.value.to_bits().hash(h); - if let Some([lx, ly]) = kf.lh { - 1u8.hash(h); - lx.to_bits().hash(h); - ly.to_bits().hash(h); - } else { - 0u8.hash(h); - } - if let Some([rx, ry]) = kf.rh { - 1u8.hash(h); - rx.to_bits().hash(h); - ry.to_bits().hash(h); - } else { - 0u8.hash(h); - } - [ - kf.flags.linear, - kf.flags.step_in, - kf.flags.step_out, - kf.flags.loop_after, - kf.flags.loop_rel, - kf.flags.ping_pong, - kf.flags.locked_y, - ] - .hash(h); - (kf.handle_mode as u8).hash(h); - } -} - -fn hash_gradient(grad: &Gradient, h: &mut DefaultHasher) { - grad.stops.len().hash(h); - for stop in &grad.stops { - stop.pos.to_bits().hash(h); - for c in stop.rgba { - c.to_bits().hash(h); - } - } -} - -fn hash_input_binding( - comp: &Comp, - binding: &InputBinding, - visited_mods: &mut HashSet, - h: &mut DefaultHasher, -) { - binding.source_output.hash(h); - binding.expression.hash(h); - match &binding.value { - None => 0u8.hash(h), - Some(ParamValue::Number(v)) => { - 1u8.hash(h); - v.to_bits().hash(h); - } - Some(ParamValue::Point([x, y])) => { - 2u8.hash(h); - x.to_bits().hash(h); - y.to_bits().hash(h); - } - Some(ParamValue::Text(s)) => { - 3u8.hash(h); - s.hash(h); - } - Some(ParamValue::FuId(s)) => { - 4u8.hash(h); - s.hash(h); - } - Some(ParamValue::Gradient(g)) => { - 5u8.hash(h); - hash_gradient(g, h); - } - Some(ParamValue::Raw(raw)) => { - 6u8.hash(h); - format!("{raw:?}").hash(h); - } - } - binding.source_op.hash(h); - if let Some(op) = &binding.source_op { - if let Some(sp) = comp.splines.get(op) { - hash_spline(sp, h); - } - if let Some(pp) = comp.poly_paths.get(op) { - pp.name.hash(h); - pp.displacement_op.hash(h); - pp.displacement_value.to_bits().hash(h); - pp.closed.hash(h); - pp.points.len().hash(h); - for pt in &pp.points { - pt.x.to_bits().hash(h); - pt.y.to_bits().hash(h); - pt.lx.to_bits().hash(h); - pt.ly.to_bits().hash(h); - pt.rx.to_bits().hash(h); - pt.ry.to_bits().hash(h); - pt.linear.hash(h); - } - if let Some(disp_op) = &pp.displacement_op { - if let Some(sp) = comp.splines.get(disp_op) { - hash_spline(sp, h); - } - } - } - if let Some(sh) = comp.shakes.get(op) { - if visited_mods.insert(op.clone()) { - hash_sorted_inputs(comp, &sh.inputs, visited_mods, h); - visited_mods.remove(op); - } else { - 0xC1C1_u16.hash(h); - op.hash(h); - } - } - if let Some(ex) = comp.expression_modifiers.get(op) { - if visited_mods.insert(op.clone()) { - hash_sorted_inputs(comp, &ex.inputs, visited_mods, h); - visited_mods.remove(op); - } else { - 0xC1C2_u16.hash(h); - op.hash(h); - } - } - if let Some(gm) = comp.gradient_modifiers.get(op) { - gm.len().hash(h); - for (t, g) in gm { - t.to_bits().hash(h); - hash_gradient(g, h); - } - } - } -} - -fn hash_sorted_inputs( - comp: &Comp, - inputs: &HashMap, - visited_mods: &mut HashSet, - h: &mut DefaultHasher, -) { - let mut keys: Vec<&String> = inputs.keys().collect(); - keys.sort_unstable(); - keys.len().hash(h); - for k in keys { - k.hash(h); - hash_input_binding(comp, &inputs[k], visited_mods, h); - } -} - -/// Content hash of the particle simulation subgraph upstream of `render_node`. -/// Unrelated edits outside the particle branch leave this hash unchanged. -fn particle_subgraph_hash(comp: &Comp, render_node: NodeId, base_start: i64) -> u64 { - fn dfs( - comp: &Comp, - node_id: NodeId, - is_root: bool, - visited: &mut HashSet, - visited_mods: &mut HashSet, - h: &mut DefaultHasher, - ) { - if !visited.insert(node_id) { - return; - } - let Some(node) = comp.nodes.get(node_id.0) else { - return; - }; - if !is_particle_node_kind(&node.kind) { - return; - } - node.name.hash(h); - node.kind.hash(h); - node.bypassed.hash(h); - - let mut keys: Vec<&String> = node.inputs.keys().collect(); - keys.sort_unstable(); - for k in keys { - // `pRender.Width` and bitmap drop target only affect rasterization, not simulation state. - if (is_root && k == "Width") || k == "ParticleStyleBitmap.DropToolsHere" { - continue; - } - k.hash(h); - hash_input_binding(comp, &node.inputs[k], visited_mods, h); - } - for up_id in particle_stream_inputs(comp, node) { - dfs(comp, up_id, false, visited, visited_mods, h); - } - } - - let mut h = DefaultHasher::new(); - base_start.hash(&mut h); - let mut visited = HashSet::new(); - let mut visited_mods = HashSet::new(); - dfs(comp, render_node, true, &mut visited, &mut visited_mods, &mut h); - h.finish() -} - fn maybe_record_snapshot(cached: &mut CachedSim, frame: i64) { if (frame - cached.base_start).rem_euclid(SNAPSHOT_INTERVAL) == 0 { cached.snapshots.insert(frame, cached.state.clone()); @@ -665,1935 +289,3 @@ pub fn render_particles_2d( ); out } - -/// Advances the particle simulation by a single integer frame `frame`. -fn step_simulation( - state: &mut SimState, - comp: &Comp, - plan: &ParticlePlan, - frame: i64, - expr: &ExprEngine, -) { - let t = frame as f64; - - // 1. Apply forces & kills to existing live particles, then integrate motion and age. - if !state.particles.is_empty() { - for (mod_id, scope) in &plan.modifiers { - let Some(node) = comp.nodes.get(mod_id.0) else { - continue; - }; - apply_modifier(&mut state.particles, comp, node, scope, t, expr); - } - - for p in &mut state.particles { - if !p.alive { - continue; - } - p.pos[0] += p.vel[0]; - p.pos[1] += p.vel[1]; - p.pos[2] += p.vel[2]; - p.rot_z += p.spin_z; - p.age += 1.0; - if p.age >= p.lifespan { - p.alive = false; - } - } - state.particles.retain(|p| p.alive); - } - - // 2. Emit new particles for `frame` (born with `age = 0.0` at their spawn region). - let first_new = state.particles.len(); - for &(emitter_id, emitter_hash) in &plan.emitters { - if state.particles.len() >= MAX_PARTICLES { - break; - } - let Some(node) = comp.nodes.get(emitter_id.0) else { - continue; - }; - emit_particles(state, comp, node, emitter_hash, frame, t, expr); - } - - // A newborn is damped by friction and then integrated once on its birth frame; other forces - // only start acting next frame. - for (mod_id, scope) in &plan.modifiers { - let Some(node) = comp.nodes.get(mod_id.0) else { - continue; - }; - if matches!(node.kind.as_str(), "pDrag" | "pFriction") { - apply_modifier(&mut state.particles[first_new..], comp, node, scope, t, expr); - } - } - for p in &mut state.particles[first_new..] { - for axis in 0..3 { - p.pos[axis] += p.vel[axis]; - } - p.rot_z += p.spin_z; - } -} - -fn emit_particles( - state: &mut SimState, - comp: &Comp, - node: &Node, - emitter_hash: u64, - frame: i64, - t: f64, - expr: &ExprEngine, -) { - let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; - let mut rng = SplitMix64::from_parts(seed, frame, &node.name); - - let number = comp.eval_number(node, "Number", t, 10.0, expr).max(0.0); - let number_var = comp - .eval_number(node, "NumberVariance", t, 0.0, expr) - .max(0.0); - - let rate = (number + rng.signed() * number_var).max(0.0); - let accum = state.emit_accum.entry(emitter_hash).or_insert(0.0); - *accum += rate; - let mut emit_count = accum.floor() as usize; - *accum -= emit_count as f64; - - if emit_count == 0 { - return; - } - let remaining_cap = MAX_PARTICLES.saturating_sub(state.particles.len()); - if emit_count > remaining_cap { - emit_count = remaining_cap; - } - - let lifespan_base = comp.eval_number(node, "Lifespan", t, 100.0, expr).max(1.0); - let lifespan_var = comp - .eval_number(node, "LifespanVariance", t, 0.0, expr) - .max(0.0); - let pos_var = comp - .eval_number(node, "PositionVariance", t, 0.0, expr) - .max(0.0); - - let vel_base = comp.eval_number(node, "Velocity", t, 0.0, expr); - let vel_var = comp - .eval_number(node, "VelocityVariance", t, 0.0, expr) - .max(0.0); - let angle_base = comp.eval_number(node, "Angle", t, 0.0, expr); - let angle_var = comp - .eval_number(node, "AngleVariance", t, 0.0, expr) - .max(0.0); - let angle_z_base = comp.eval_number(node, "AngleZ", t, 0.0, expr); - let angle_z_var = comp - .eval_number(node, "AngleZVariance", t, 0.0, expr) - .max(0.0); - - let rot_z_base = comp.eval_number(node, "RotationZ", t, 0.0, expr); - let rot_z_var = comp - .eval_number(node, "RotationZVariance", t, 0.0, expr) - .max(0.0); - let spin_z_base = comp.eval_number(node, "SpinZ", t, 0.0, expr); - let spin_z_var = comp - .eval_number(node, "SpinZVariance", t, 0.0, expr) - .max(0.0); - - let base_r = comp.eval_number(node, "ParticleStyle.Red", t, 1.0, expr); - let base_g = comp.eval_number(node, "ParticleStyle.Green", t, 1.0, expr); - let base_b = comp.eval_number(node, "ParticleStyle.Blue", t, 1.0, expr); - let base_a = comp.eval_number(node, "ParticleStyle.Alpha", t, 1.0, expr); - - let color_var = comp.eval_number(node, "ParticleStyle.ColorVariance", t, 0.0, expr) > 0.5; - let r_lo = (base_r + comp.eval_number(node, "ParticleStyle.RedLow", t, 0.0, expr)).clamp(0.0, 1.0); - let r_hi = (base_r + comp.eval_number(node, "ParticleStyle.RedHigh", t, 0.0, expr)).clamp(0.0, 1.0); - let g_lo = (base_g + comp.eval_number(node, "ParticleStyle.GreenLow", t, 0.0, expr)).clamp(0.0, 1.0); - let g_hi = (base_g + comp.eval_number(node, "ParticleStyle.GreenHigh", t, 0.0, expr)).clamp(0.0, 1.0); - let b_lo = (base_b + comp.eval_number(node, "ParticleStyle.BlueLow", t, 0.0, expr)).clamp(0.0, 1.0); - let b_hi = (base_b + comp.eval_number(node, "ParticleStyle.BlueHigh", t, 0.0, expr)).clamp(0.0, 1.0); - let a_lo = (base_a + comp.eval_number(node, "ParticleStyle.AlphaLow", t, 0.0, expr)).clamp(0.0, 1.0); - let a_hi = (base_a + comp.eval_number(node, "ParticleStyle.AlphaHigh", t, 0.0, expr)).clamp(0.0, 1.0); - - let size_base = comp - .eval_number(node, "ParticleStyle.Size", t, 1.0, expr) - .max(0.0); - let size_var = comp - .eval_number(node, "ParticleStyle.SizeVariance", t, 0.0, expr) - .max(0.0); - - let region = RegionSpec::from_node(comp, node, t, expr); - - for _ in 0..emit_count { - let mut pos = region.sample(&mut rng); - if pos_var > 0.0 { - pos[0] += rng.signed() * pos_var; - pos[1] += rng.signed() * pos_var; - pos[2] += rng.signed() * pos_var; - } - - let speed = (vel_base + rng.signed() * vel_var) * VELOCITY_SCALE; - let ang = (angle_base + rng.signed() * angle_var).to_radians(); - let ang_z = (angle_z_base + rng.signed() * angle_z_var).to_radians(); - let cos_z = ang_z.cos(); - let vel = [ - speed * ang.cos() * cos_z, - speed * ang.sin() * cos_z, - speed * ang_z.sin(), - ]; - - let rot_z = rot_z_base + rng.signed() * rot_z_var; - let spin_z = spin_z_base + rng.signed() * spin_z_var; - let lifespan = (lifespan_base + rng.signed() * lifespan_var).max(1.0); - let size = (size_base + rng.signed() * size_var).max(0.0); - - let color = if color_var { - [ - rng.range(r_lo, r_hi) as f32, - rng.range(g_lo, g_hi) as f32, - rng.range(b_lo, b_hi) as f32, - rng.range(a_lo, a_hi) as f32, - ] - } else { - [ - base_r.clamp(0.0, 1.0) as f32, - base_g.clamp(0.0, 1.0) as f32, - base_b.clamp(0.0, 1.0) as f32, - base_a.clamp(0.0, 1.0) as f32, - ] - }; - - state.particles.push(Particle { - emitter_hash, - pos, - vel, - rot_z, - spin_z, - age: 0.0, - lifespan, - size, - color, - alive: true, - }); - } -} - -#[derive(Clone, Copy)] -enum RegionSpec { - Point { - center: [f64; 3], - }, - Rect { - center: [f64; 3], - width: f64, - height: f64, - }, - Sphere { - center: [f64; 3], - radius: f64, - }, - Cube { - center: [f64; 3], - width: f64, - height: f64, - depth: f64, - }, - Line { - start: [f64; 3], - end: [f64; 3], - }, - All, -} - -impl RegionSpec { - fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self { - let region_name = node.static_str("Region").unwrap_or("SphereRgn"); - match region_name { - "RectRgn" => Self::Rect { - center: [ - comp.eval_number(node, "RectRgn.Translate.X", t, 0.0, expr), - comp.eval_number(node, "RectRgn.Translate.Y", t, 0.0, expr), - comp.eval_number(node, "RectRgn.Translate.Z", t, 0.0, expr), - ], - width: comp.eval_number(node, "RectRgn.Width", t, 0.1, expr).abs(), - height: comp.eval_number(node, "RectRgn.Height", t, 0.1, expr).abs(), - }, - "SphereRgn" => Self::Sphere { - center: [ - comp.eval_number(node, "SphereRgn.Translate.X", t, 0.0, expr), - comp.eval_number(node, "SphereRgn.Translate.Y", t, 0.0, expr), - comp.eval_number(node, "SphereRgn.Translate.Z", t, 0.0, expr), - ], - radius: comp.eval_number(node, "SphereRgn.Size", t, 0.1, expr).abs() * 0.5, - }, - "CubeRgn" => Self::Cube { - center: [ - comp.eval_number(node, "CubeRgn.Translate.X", t, 0.0, expr), - comp.eval_number(node, "CubeRgn.Translate.Y", t, 0.0, expr), - comp.eval_number(node, "CubeRgn.Translate.Z", t, 0.0, expr), - ], - width: comp.eval_number(node, "CubeRgn.Width", t, 0.1, expr).abs(), - height: comp.eval_number(node, "CubeRgn.Height", t, 0.1, expr).abs(), - depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.1, expr).abs(), - }, - "LineRgn" => { - let tx = comp.eval_number(node, "LineRgn.Translate.X", t, 0.0, expr); - let ty = comp.eval_number(node, "LineRgn.Translate.Y", t, 0.0, expr); - let tz = comp.eval_number(node, "LineRgn.Translate.Z", t, 0.0, expr); - Self::Line { - start: [ - tx + comp.eval_number(node, "LineRgn.Start.X", t, -0.5, expr), - ty + comp.eval_number(node, "LineRgn.Start.Y", t, 0.0, expr), - tz + comp.eval_number(node, "LineRgn.Start.Z", t, 0.0, expr), - ], - end: [ - tx + comp.eval_number(node, "LineRgn.End.X", t, 0.5, expr), - ty + comp.eval_number(node, "LineRgn.End.Y", t, 0.0, expr), - tz + comp.eval_number(node, "LineRgn.End.Z", t, 0.0, expr), - ], - } - } - "AllRgn" | "All" => Self::All, - _ => Self::Point { - center: [ - comp.eval_number(node, "Point.Translate.X", t, 0.0, expr), - comp.eval_number(node, "Point.Translate.Y", t, 0.0, expr), - comp.eval_number(node, "Point.Translate.Z", t, 0.0, expr), - ], - }, - } - } - - fn sample(&self, rng: &mut SplitMix64) -> [f64; 3] { - match *self { - Self::Point { center } => center, - Self::Rect { - center, - width, - height, - } => [ - center[0] + (rng.next_f64() - 0.5) * width, - center[1] + (rng.next_f64() - 0.5) * height, - center[2], - ], - Self::Sphere { center, radius } => { - let u = rng.next_f64(); - let v = rng.next_f64(); - let w = rng.next_f64(); - let theta = u * std::f64::consts::TAU; - let cos_phi = 2.0 * v - 1.0; - let sin_phi = (1.0 - cos_phi * cos_phi).max(0.0).sqrt(); - let r = radius * w.cbrt(); - [ - center[0] + r * sin_phi * theta.cos(), - center[1] + r * sin_phi * theta.sin(), - center[2] + r * cos_phi, - ] - } - Self::Cube { - center, - width, - height, - depth, - } => [ - center[0] + (rng.next_f64() - 0.5) * width, - center[1] + (rng.next_f64() - 0.5) * height, - center[2] + (rng.next_f64() - 0.5) * depth, - ], - Self::Line { start, end } => { - let u = rng.next_f64(); - [ - start[0] + (end[0] - start[0]) * u, - start[1] + (end[1] - start[1]) * u, - start[2] + (end[2] - start[2]) * u, - ] - } - Self::All => [0.0, 0.0, 0.0], - } - } - - fn contains(&self, p: [f64; 3]) -> bool { - match *self { - Self::All => true, - Self::Point { center } => { - let dx = p[0] - center[0]; - let dy = p[1] - center[1]; - let dz = p[2] - center[2]; - dx * dx + dy * dy + dz * dz <= 1e-4 - } - Self::Rect { - center, - width, - height, - } => { - (p[0] - center[0]).abs() <= width * 0.5 - && (p[1] - center[1]).abs() <= height * 0.5 - } - Self::Sphere { center, radius } => { - let dx = p[0] - center[0]; - let dy = p[1] - center[1]; - let dz = p[2] - center[2]; - dx * dx + dy * dy + dz * dz <= radius * radius - } - Self::Cube { - center, - width, - height, - depth, - } => { - (p[0] - center[0]).abs() <= width * 0.5 - && (p[1] - center[1]).abs() <= height * 0.5 - && (p[2] - center[2]).abs() <= depth * 0.5 - } - Self::Line { start, end } => { - let vx = end[0] - start[0]; - let vy = end[1] - start[1]; - let vz = end[2] - start[2]; - let len_sq = vx * vx + vy * vy + vz * vz; - let u = if len_sq > 1e-9 { - (((p[0] - start[0]) * vx + (p[1] - start[1]) * vy + (p[2] - start[2]) * vz) - / len_sq) - .clamp(0.0, 1.0) - } else { - 0.0 - }; - let cx = start[0] + vx * u; - let cy = start[1] + vy * u; - let cz = start[2] + vz * u; - let dx = p[0] - cx; - let dy = p[1] - cy; - let dz = p[2] - cz; - dx * dx + dy * dy + dz * dz <= 1e-3 - } - } - } - - /// Parses a `pBounce` region (supports `LineRgn`, `RectRgn`, `CubeRgn`, `SphereRgn`, - /// `MeshRegion`, and `Transform3DOp.Translate` fallback). - fn from_bounce_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self { - let tx = comp.eval_number(node, "Transform3DOp.Translate.X", t, 0.0, expr); - let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", t, 0.0, expr); - let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", t, 0.0, expr); - match node.static_str("Region") { - Some("RectRgn") => Self::Rect { - center: [ - comp.eval_number(node, "RectRgn.Translate.X", t, tx, expr), - comp.eval_number(node, "RectRgn.Translate.Y", t, ty, expr), - comp.eval_number(node, "RectRgn.Translate.Z", t, tz, expr), - ], - width: comp.eval_number(node, "RectRgn.Width", t, 0.1, expr).abs(), - height: comp.eval_number(node, "RectRgn.Height", t, 0.1, expr).abs(), - }, - Some("SphereRgn") => Self::Sphere { - center: [ - comp.eval_number(node, "SphereRgn.Translate.X", t, tx, expr), - comp.eval_number(node, "SphereRgn.Translate.Y", t, ty, expr), - comp.eval_number(node, "SphereRgn.Translate.Z", t, tz, expr), - ], - radius: comp.eval_number(node, "SphereRgn.Size", t, 0.5, expr).abs() * 0.5, - }, - Some("CubeRgn") => Self::Cube { - center: [ - comp.eval_number(node, "CubeRgn.Translate.X", t, tx, expr), - comp.eval_number(node, "CubeRgn.Translate.Y", t, ty, expr), - comp.eval_number(node, "CubeRgn.Translate.Z", t, tz, expr), - ], - width: comp.eval_number(node, "CubeRgn.Width", t, 0.1, expr).abs(), - height: comp.eval_number(node, "CubeRgn.Height", t, 0.1, expr).abs(), - depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.1, expr).abs(), - }, - Some("LineRgn") => { - let lx = comp.eval_number(node, "LineRgn.Translate.X", t, tx, expr); - let ly = comp.eval_number(node, "LineRgn.Translate.Y", t, ty, expr); - let lz = comp.eval_number(node, "LineRgn.Translate.Z", t, tz, expr); - Self::Line { - start: [ - lx + comp.eval_number(node, "LineRgn.Start.X", t, -0.5, expr), - ly + comp.eval_number(node, "LineRgn.Start.Y", t, 0.0, expr), - lz + comp.eval_number(node, "LineRgn.Start.Z", t, 0.0, expr), - ], - end: [ - lx + comp.eval_number(node, "LineRgn.End.X", t, 0.5, expr), - ly + comp.eval_number(node, "LineRgn.End.Y", t, 0.0, expr), - lz + comp.eval_number(node, "LineRgn.End.Z", t, 0.0, expr), - ], - } - } - Some("MeshRegion") | None => Self::Point { center: [tx, ty, tz] }, - _ => Self::from_node(comp, node, t, expr), - } - } - - /// Checks whether a particle stepping `pos -> pos + vel` collides with this bounce region. - /// Returns `(contact_pos, outward_unit_normal)` when a reflection should occur. - fn bounce_collision(&self, pos: [f64; 3], vel: [f64; 3]) -> Option<([f64; 3], [f64; 3])> { - let next = [pos[0] + vel[0], pos[1] + vel[1], pos[2] + vel[2]]; - match *self { - Self::Line { start, end } => { - let sx = end[0] - start[0]; - let sy = end[1] - start[1]; - let len_sq = sx * sx + sy * sy; - let len = len_sq.sqrt(); - if len < 1e-9 { - return None; - } - let mut n = [-sy / len, sx / len, 0.0]; - let d0 = (pos[0] - start[0]) * n[0] + (pos[1] - start[1]) * n[1]; - let d1 = (next[0] - start[0]) * n[0] + (next[1] - start[1]) * n[1]; - let crosses = (d0 * d1 <= 0.0 && (d0.abs() > 1e-12 || d1.abs() > 1e-12)) - || d1.abs() <= 1e-4; - if !crosses { - return None; - } - let alpha = if (d0 - d1).abs() > 1e-12 { - (d0 / (d0 - d1)).clamp(0.0, 1.0) - } else { - 1.0 - }; - let hit = [ - pos[0] + vel[0] * alpha, - pos[1] + vel[1] * alpha, - pos[2] + vel[2] * alpha, - ]; - let u = ((hit[0] - start[0]) * sx + (hit[1] - start[1]) * sy) / len_sq; - if !(-1e-4..=1.0 + 1e-4).contains(&u) { - return None; - } - let vn = vel[0] * n[0] + vel[1] * n[1]; - if vn > 0.0 { - n[0] = -n[0]; - n[1] = -n[1]; - } - if vel[0] * n[0] + vel[1] * n[1] >= -1e-12 { - return None; - } - Some(([hit[0] + n[0] * 1e-5, hit[1] + n[1] * 1e-5, hit[2]], n)) - } - Self::Sphere { center, radius } => { - if radius < 1e-6 { - return None; - } - let dp = [pos[0] - center[0], pos[1] - center[1], pos[2] - center[2]]; - let dn = [next[0] - center[0], next[1] - center[1], next[2] - center[2]]; - let r_pos = (dp[0] * dp[0] + dp[1] * dp[1] + dp[2] * dp[2]).sqrt(); - let r_next = (dn[0] * dn[0] + dn[1] * dn[1] + dn[2] * dn[2]).sqrt(); - if r_pos > radius && r_next > radius { - return None; - } - let ref_v = if r_pos > 1e-9 { dp } else if r_next > 1e-9 { dn } else { [0.0, 1.0, 0.0] }; - 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); - let mut n = [ref_v[0] / r_len, ref_v[1] / r_len, ref_v[2] / r_len]; - if r_pos < radius && r_next >= radius { - // Particle hitting sphere wall from inside - n = [-n[0], -n[1], -n[2]]; - let pushed = [ - center[0] - n[0] * (radius - 1e-5).max(0.0), - center[1] - n[1] * (radius - 1e-5).max(0.0), - center[2] - n[2] * (radius - 1e-5).max(0.0), - ]; - return Some((pushed, n)); - } - let pushed = [ - center[0] + n[0] * (radius + 1e-5), - center[1] + n[1] * (radius + 1e-5), - center[2] + n[2] * (radius + 1e-5), - ]; - Some((pushed, n)) - } - Self::Rect { center, width, height } => { - let hx = width * 0.5; - let hy = height * 0.5; - if hy < 1e-6 { - let line = Self::Line { - start: [center[0] - hx, center[1], center[2]], - end: [center[0] + hx, center[1], center[2]], - }; - return line.bounce_collision(pos, vel); - } - if hx < 1e-6 { - let line = Self::Line { - start: [center[0], center[1] - hy, center[2]], - end: [center[0], center[1] + hy, center[2]], - }; - return line.bounce_collision(pos, vel); - } - bounce_aabb(pos, vel, center, [hx, hy, 1e6], false) - } - Self::Cube { center, width, height, depth } => { - bounce_aabb(pos, vel, center, [width * 0.5, height * 0.5, depth * 0.5], true) - } - Self::Point { center } => { - let cy = center[1]; - let d0 = pos[1] - cy; - let d1 = next[1] - cy; - if d0 * d1 <= 0.0 || d1.abs() <= 1e-5 { - let ny = if vel[1] < 0.0 { 1.0 } else if vel[1] > 0.0 { -1.0 } else { return None }; - let alpha = if (d0 - d1).abs() > 1e-12 { - (d0 / (d0 - d1)).clamp(0.0, 1.0) - } else { - 1.0 - }; - let hit = [ - pos[0] + vel[0] * alpha, - cy + ny * 1e-5, - pos[2] + vel[2] * alpha, - ]; - return Some((hit, [0.0, ny, 0.0])); - } - None - } - Self::All => None, - } - } -} - -/// Slab-method segment-vs-AABB bounce helper (2D when `check_z == false`, 3D when `check_z == true`). -fn bounce_aabb( - pos: [f64; 3], - vel: [f64; 3], - center: [f64; 3], - half: [f64; 3], - check_z: bool, -) -> Option<([f64; 3], [f64; 3])> { - let axes = if check_z { 3 } else { 2 }; - let mut inside_pos = true; - for a in 0..axes { - if (pos[a] - center[a]).abs() > half[a] { - inside_pos = false; - break; - } - } - - if inside_pos { - // Already inside: push out through the closest face - let mut best_axis = 0usize; - let mut best_pen = f64::INFINITY; - let mut best_sign = 1.0f64; - for a in 0..axes { - let delta = pos[a] - center[a]; - let pen = half[a] - delta.abs(); - if pen < best_pen { - best_pen = pen; - best_axis = a; - best_sign = if delta >= 0.0 { 1.0 } else { -1.0 }; - } - } - let mut n = [0.0; 3]; - n[best_axis] = best_sign; - let mut pushed = pos; - pushed[best_axis] = center[best_axis] + best_sign * (half[best_axis] + 1e-5); - return Some((pushed, n)); - } - - let mut t_min = 0.0_f64; - let mut t_max = 1.0_f64; - let mut hit_axis = 0usize; - let mut hit_sign = 1.0_f64; - - for a in 0..axes { - let min_b = center[a] - half[a]; - let max_b = center[a] + half[a]; - if vel[a].abs() < 1e-12 { - if pos[a] < min_b || pos[a] > max_b { - return None; - } - } else { - let inv = 1.0 / vel[a]; - let mut t1 = (min_b - pos[a]) * inv; - let mut t2 = (max_b - pos[a]) * inv; - let mut s = -1.0; - if t1 > t2 { - std::mem::swap(&mut t1, &mut t2); - s = 1.0; - } - if t1 > t_min { - t_min = t1; - hit_axis = a; - hit_sign = s; - } - t_max = t_max.min(t2); - if t_min > t_max { - return None; - } - } - } - - let mut n = [0.0; 3]; - n[hit_axis] = hit_sign; - let hit = [ - pos[0] + vel[0] * t_min + n[0] * 1e-5, - pos[1] + vel[1] * t_min + n[1] * 1e-5, - pos[2] + vel[2] * t_min + n[2] * 1e-5, - ]; - Some((hit, n)) -} - -fn apply_modifier( - particles: &mut [Particle], - comp: &Comp, - node: &Node, - scope: &HashSet, - t: f64, - expr: &ExprEngine, -) { - match node.kind.as_str() { - "pPointForce" => { - let strength = comp.eval_number(node, "Strength", t, 0.0, expr); - if strength.abs() < 1e-12 { - return; - } - let power = comp.eval_number(node, "Power", t, 2.0, expr); - let tx = comp.eval_number(node, "Translate.X", t, 0.0, expr); - let ty = comp.eval_number(node, "Translate.Y", t, 0.0, expr); - let tz = comp.eval_number(node, "Translate.Z", t, 0.0, expr); - - for p in particles.iter_mut() { - if !p.alive || !scope.contains(&p.emitter_hash) { - continue; - } - let dx = tx - p.pos[0]; - let dy = ty - p.pos[1]; - let dz = tz - p.pos[2]; - let dist = (dx * dx + dy * dy + dz * dz).sqrt(); - if dist < 1e-7 { - continue; - } - let falloff = dist.max(0.005).powf(power); - let mag = (strength * POINT_FORCE_SCALE / falloff).clamp(-0.25, 0.25); - let inv_d = 1.0 / dist; - p.vel[0] += dx * inv_d * mag; - p.vel[1] += dy * inv_d * mag; - p.vel[2] += dz * inv_d * mag; - } - } - "pDirectionalForce" => { - let strength = comp.eval_number(node, "Strength", t, 0.1, expr); - if strength.abs() < 1e-12 { - return; - } - let dir = comp - .eval_number(node, "Direction", t, -90.0, expr) - .to_radians(); - let dir_z = comp - .eval_number(node, "DirectionZ", t, 0.0, expr) - .to_radians(); - let mag = strength * VELOCITY_SCALE * VELOCITY_SCALE; - let ax = mag * dir.cos() * dir_z.cos(); - let ay = mag * dir.sin() * dir_z.cos(); - let az = mag * dir_z.sin(); - - for p in particles.iter_mut() { - if !p.alive || !scope.contains(&p.emitter_hash) { - continue; - } - p.vel[0] += ax; - p.vel[1] += ay; - p.vel[2] += az; - } - } - "pDrag" | "pFriction" => { - let damp = if node.kind == "pFriction" { - 1.0 - comp.eval_number(node, "VelocityFriction", t, 0.05, expr) - } else { - 1.0 - comp.eval_number(node, "Drag", t, 0.05, expr) - } - .clamp(0.0, 1.0); - let spin_damp = if node.kind == "pFriction" { - 1.0 - comp.eval_number(node, "SpinFriction", t, 0.05, expr).clamp(0.0, 1.0) - } else { - 1.0 - }; - for p in particles.iter_mut() { - if !p.alive || !scope.contains(&p.emitter_hash) { - continue; - } - p.vel[0] *= damp; - p.vel[1] *= damp; - p.vel[2] *= damp; - p.spin_z *= spin_damp; - } - } - "pTurbulence" => { - let sx = comp.eval_number(node, "XStrength", t, 0.1, expr); - let sy = comp.eval_number(node, "YStrength", t, 0.1, expr); - let sz = comp.eval_number(node, "ZStrength", t, 0.0, expr); - if sx.abs() < 1e-12 && sy.abs() < 1e-12 && sz.abs() < 1e-12 { - return; - } - let density = comp.eval_number(node, "Density", t, 1.0, expr).max(0.01); - let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as u64; - let time_shift = t * 0.03; - - for p in particles.iter_mut() { - if !p.alive || !scope.contains(&p.emitter_hash) { - continue; - } - let qx = p.pos[0] * density + time_shift; - let qy = p.pos[1] * density - time_shift * 0.7; - let qz = p.pos[2] * density; - let nx = value_noise_3d(qx, qy, qz, seed); - let ny = value_noise_3d(qx + 31.7, qy + 17.3, qz + 47.1, seed ^ 0x517C_C1B7_2722_0A95); - let nz = value_noise_3d(qx - 19.4, qy + 53.9, qz - 11.2, seed ^ 0x9E37_79B9_7F4A_7C15); - p.vel[0] += nx * sx * TURBULENCE_SCALE; - p.vel[1] += ny * sy * TURBULENCE_SCALE; - p.vel[2] += nz * sz * TURBULENCE_SCALE; - } - } - "pKill" => { - let region = if node.static_str("Region").is_some() { - RegionSpec::from_node(comp, node, t, expr) - } else { - RegionSpec::All - }; - let kill_outside = matches!( - node.static_str("RegionMode"), - Some("Outside") | Some("Leaving") - ); - for p in particles.iter_mut() { - if !p.alive || !scope.contains(&p.emitter_hash) { - continue; - } - let inside = region.contains(p.pos); - if (!kill_outside && inside) || (kill_outside && !inside) { - p.alive = false; - } - } - } - "pBounce" => { - let region = RegionSpec::from_bounce_node(comp, node, t, expr); - let elasticity = comp.eval_number(node, "Elasticity", t, 1.0, expr).clamp(0.0, 2.0); - let variance = comp.eval_number(node, "Variance", t, 0.0, expr).max(0.0); - let friction = comp.eval_number(node, "Friction", t, 0.0, expr).clamp(0.0, 1.0); - let roughness = comp.eval_number(node, "Roughness", t, 0.0, expr).max(0.0); - let spin = comp.eval_number(node, "Spin", t, 0.0, expr); - let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; - let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); - - for p in particles.iter_mut() { - if !p.alive || !scope.contains(&p.emitter_hash) { - continue; - } - let Some((pushed_pos, n)) = region.bounce_collision(p.pos, p.vel) else { - continue; - }; - let vn = p.vel[0] * n[0] + p.vel[1] * n[1] + p.vel[2] * n[2]; - if vn < 0.0 { - let e = (elasticity * (1.0 + rng.signed() * variance)).clamp(0.0, 2.0); - let t_damp = (1.0 - friction).clamp(0.0, 1.0); - let vnx = vn * n[0]; - let vny = vn * n[1]; - let vnz = vn * n[2]; - let vtx = p.vel[0] - vnx; - let vty = p.vel[1] - vny; - let vtz = p.vel[2] - vnz; - p.vel[0] = vtx * t_damp - vnx * e; - p.vel[1] = vty * t_damp - vny * e; - p.vel[2] = vtz * t_damp - vnz * e; - if roughness > 1e-6 { - let scatter = roughness * 0.01 * vn.abs(); - p.vel[0] += rng.signed() * scatter; - p.vel[1] += rng.signed() * scatter; - p.vel[2] += rng.signed() * scatter; - } - if spin.abs() > 1e-9 { - p.spin_z += spin * (1.0 + 0.5 * rng.signed()); - } - p.pos = pushed_pos; - } - } - } - _ => {} - } -} - -/// Smooth deterministic 3D value noise in `[-1.0, 1.0]`. -fn value_noise_3d(x: f64, y: f64, z: f64, seed: u64) -> f64 { - let xi = x.floor() as i64; - let yi = y.floor() as i64; - let zi = z.floor() as i64; - let xf = x - xi as f64; - let yf = y - yi as f64; - let zf = z - zi as f64; - - let u = xf * xf * (3.0 - 2.0 * xf); - let v = yf * yf * (3.0 - 2.0 * yf); - let w = zf * zf * (3.0 - 2.0 * zf); - - let n000 = lattice_hash(xi, yi, zi, seed); - let n100 = lattice_hash(xi + 1, yi, zi, seed); - let n010 = lattice_hash(xi, yi + 1, zi, seed); - let n110 = lattice_hash(xi + 1, yi + 1, zi, seed); - let n001 = lattice_hash(xi, yi, zi + 1, seed); - let n101 = lattice_hash(xi + 1, yi, zi + 1, seed); - let n011 = lattice_hash(xi, yi + 1, zi + 1, seed); - let n111 = lattice_hash(xi + 1, yi + 1, zi + 1, seed); - - let nx00 = n000 + (n100 - n000) * u; - let nx10 = n010 + (n110 - n010) * u; - let nx01 = n001 + (n101 - n001) * u; - let nx11 = n011 + (n111 - n011) * u; - - let nxy0 = nx00 + (nx10 - nx00) * v; - let nxy1 = nx01 + (nx11 - nx01) * v; - - nxy0 + (nxy1 - nxy0) * w -} - -#[inline] -fn lattice_hash(x: i64, y: i64, z: i64, seed: u64) -> f64 { - let mut h = seed - ^ (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) - ^ (y as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9) - ^ (z as u64).wrapping_mul(0x94D0_49BB_1331_11EB); - h = (h ^ (h >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - h = (h ^ (h >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - h ^= h >> 31; - let unit = (h >> 11) as f64 * (1.0 / ((1u64 << 53) as f64)); - unit * 2.0 - 1.0 -} - -struct EmitterRenderProps<'a> { - emitter_id: NodeId, - style: ParticleStyleKind, - tiny_sprite: Option<([f64; 2], SpriteImage)>, - ngon_sides: f64, - size_over_life: Option<&'a model::BezierSpline>, - fade_in: f64, - fade_out: f64, - color_over_life: Option, -} - -fn collect_emitter_render_props<'a>( - comp: &'a Comp, - emitter_nodes: &HashMap, - particles: &[Particle], - time: f64, - expr: &ExprEngine, -) -> HashMap> { - let mut map = HashMap::new(); - for p in particles { - if map.contains_key(&p.emitter_hash) { - continue; - } - let Some(&emitter_id) = emitter_nodes.get(&p.emitter_hash) else { - continue; - }; - let Some(node) = comp.nodes.get(emitter_id.0) else { - continue; - }; - let style = match node.static_str("Style") { - Some("ParticleStyleBitmap") => ParticleStyleKind::Bitmap, - Some("ParticleStyleBlob") => ParticleStyleKind::Blob, - Some("ParticleStyleNGon") => ParticleStyleKind::NGon, - Some("ParticleStyleBrush") => ParticleStyleKind::Brush, - _ => ParticleStyleKind::Point, - }; - let size_over_life = node - .inputs - .get("ParticleStyle.SizeOverLife") - .and_then(|b| b.source_op.as_deref()) - .and_then(|src| comp.splines.get(src)); - let fade_in = comp - .eval_number(node, "ParticleStyle.FadeIn", time, 0.0, expr) - .clamp(0.0, 1.0); - let fade_out = comp - .eval_number(node, "ParticleStyle.FadeOut", time, 1.0, expr) - .clamp(0.0, 1.0); - let color_over_life_on = - comp.eval_number(node, "ParticleStyle.ColorOverLifeControls", time, 0.0, expr) > 0.5; - let color_over_life = if color_over_life_on { - comp.eval_gradient(node, "ParticleStyle.ColorOverLife", time) - } else { - None - }; - map.insert( - p.emitter_hash, - EmitterRenderProps { - emitter_id, - style, - tiny_sprite: tiny_background_sprite(comp, node, time, expr), - ngon_sides: comp.eval_number(node, "ParticleStyleNGon.NGonSides", time, 5.0, expr).round().max(3.0), - size_over_life, - fade_in, - fade_out, - color_over_life, - }, - ); - } - map -} - -/// Solid sprite for a `Background` tool narrower than 16 px. -/// -/// The engine evaluates such tools at comp size, so the particle uses the tool's nominal -/// `Width`/`Height` and its flat color directly. -fn tiny_background_sprite( - comp: &Comp, - emitter: &Node, - t: f64, - expr: &ExprEngine, -) -> Option<([f64; 2], SpriteImage)> { - let src = emitter - .connected_node("ParticleStyleBitmap.DropToolsHere") - .and_then(|name| comp.find_node(name)) - .map(|id| &comp.nodes[id.0]) - .filter(|n| n.kind == "Background")?; - let w = comp.eval_number(src, "Width", t, 0.0, expr); - let h = comp.eval_number(src, "Height", t, 0.0, expr); - if !(w >= 1.0 && h >= 1.0 && (w < 16.0 || h < 16.0)) { - return None; - } - let channel = |name: &str, default: f64| comp.eval_number(src, name, t, default, expr).clamp(0.0, 1.0); - let a = channel("TopLeftAlpha", 1.0); - let px = |c: f64| (c * a * 255.0 + 0.5) as u8; - let rgba = vec![ - px(channel("TopLeftRed", 0.0)), - px(channel("TopLeftGreen", 0.0)), - px(channel("TopLeftBlue", 0.0)), - (a * 255.0 + 0.5) as u8, - ]; - Some(([w, h], SpriteImage { size: [1, 1], rgba })) -} - -#[allow(clippy::too_many_arguments)] -fn rasterize_particles( - out: &mut [u8], - dims: [u32; 2], - px_scale: f64, - comp: &Comp, - emitter_nodes: &HashMap, - particles: &[Particle], - time: f64, - expr: &ExprEngine, - sprites: &HashMap, -) { - if particles.is_empty() { - return; - } - - let props_map = collect_emitter_render_props(comp, emitter_nodes, particles, time, expr); - let w = dims[0] as usize; - let h = dims[1] as usize; - let w_f = w as f64; - let h_f = h as f64; - - // Accumulate in linear-ish float premultiplied RGBA for clean blending, then pack to u8. - let mut accum = vec![0.0f32; w * h * 4]; - - for p in particles { - if !p.alive { - continue; - } - let Some(props) = props_map.get(&p.emitter_hash) else { - continue; - }; - - let life_frac = (p.age / p.lifespan.max(1.0)).clamp(0.0, 1.0); - // Fusion's SizeOverLife LUT maps 0.5 -> 1.0x (0.0 -> 0x, 1.0 -> 2x). - let size_mult = props - .size_over_life - .map(|sp| (2.0 * sp.eval(life_frac)).max(0.0)) - .unwrap_or(1.0); - let depth_scale = CAMERA_DISTANCE / (CAMERA_DISTANCE + p.pos[2]); - if !(depth_scale > 0.0) { - continue; - } - let size_world = p.size * size_mult * depth_scale; - if size_world <= 1e-6 { - continue; - } - - let mut fade = 1.0f64; - if props.fade_in > 1e-6 && life_frac < props.fade_in { - fade *= life_frac / props.fade_in; - } - if props.fade_out < 1.0 - 1e-6 && life_frac > props.fade_out { - fade *= ((1.0 - life_frac) / (1.0 - props.fade_out)).max(0.0); - } - - let mut cr = p.color[0]; - let mut cg = p.color[1]; - let mut cb = p.color[2]; - let mut ca = p.color[3] * fade as f32; - if let Some(grad) = &props.color_over_life { - let g = grad.sample(life_frac); - cr *= g[0]; - cg *= g[1]; - cb *= g[2]; - ca *= g[3]; - } - ca = ca.clamp(0.0, 1.0); - if ca <= 1e-4 { - continue; - } - - // Fusion 2D particle coordinates: X in [-0.5, +0.5], Y-up with same unit scale as X. - let cx = (p.pos[0] * depth_scale + 0.5) * w_f; - let cy = h_f * 0.5 - p.pos[1] * depth_scale * w_f; - - if props.style == ParticleStyleKind::Bitmap { - let (sprite, nominal) = match &props.tiny_sprite { - Some((nominal, sprite)) => (Some(sprite), *nominal), - None => { - let sprite = sprites.get(&props.emitter_id); - (sprite, sprite.map_or([0.0; 2], |s| [s.size[0] as f64, s.size[1] as f64])) - } - }; - if let Some(sprite) = sprite.filter(|s| { - s.size[0] > 0 - && s.size[1] > 0 - && s.rgba.len() >= (s.size[0] as usize).saturating_mul(s.size[1] as usize).saturating_mul(4) - }) { - draw_bitmap_particle( - &mut accum, - w, - h, - cx, - cy, - size_world * nominal[0] * px_scale, - size_world * nominal[1] * px_scale, - p.rot_z, - [cr, cg, cb, ca], - sprite, - ); - continue; - } - } - - match props.style { - ParticleStyleKind::Point => { - blend_pixel(&mut accum, w, h, cx.floor(), cy.floor(), [cr, cg, cb, ca]); - } - ParticleStyleKind::Blob | ParticleStyleKind::Bitmap => { - let sigma = BLOB_SIGMA_PER_SIZE * size_world * px_scale; - draw_soft_particle(&mut accum, w, h, cx, cy, sigma, [cr, cg, cb, ca], |_, _| 1.0); - } - ParticleStyleKind::NGon => { - let sigma = BLOB_SIGMA_PER_SIZE * size_world * px_scale; - let sides = props.ngon_sides; - let spike_period = std::f64::consts::TAU / sides; - let phase = std::f64::consts::FRAC_PI_2 + p.rot_z.to_radians(); - // Spike sharpness fitted to Fusion 21.1: alpha mass is 0.18/0.48/0.78 of a blob for 3/5/8 sides. - let sharpness = 4.5 * (3.0 / sides).powf(2.8); - draw_soft_particle(&mut accum, w, h, cx, cy, sigma, [cr, cg, cb, ca], |dx, dy| { - // Distance to the nearest spike, as a fraction of half the spike period. - let angle = (-dy).atan2(dx) - phase; - let off = angle.rem_euclid(spike_period); - let to_spike = off.min(spike_period - off); - (1.0 - to_spike / (0.5 * spike_period)).powf(sharpness) - }); - } - ParticleStyleKind::Brush => {} - } - } - - for (dst, &src) in out.iter_mut().zip(accum.iter()) { - *dst = (src.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - } -} - -#[allow(clippy::too_many_arguments)] -fn draw_bitmap_particle( - accum: &mut [f32], - w: usize, - h: usize, - cx: f64, - cy: f64, - draw_w: f64, - draw_h: f64, - rot_z_deg: f64, - tint: [f32; 4], - sprite: &SpriteImage, -) { - if draw_w < 0.5 || draw_h < 0.5 { - return; - } - - let hw = draw_w * 0.5; - let hh = draw_h * 0.5; - let theta = rot_z_deg.to_radians(); - let cos_t = theta.cos(); - let sin_t = theta.sin(); - - let rx = hw * cos_t.abs() + hh * sin_t.abs() + 1.0; - let ry = hw * sin_t.abs() + hh * cos_t.abs() + 1.0; - - let min_x = ((cx - rx).floor() as isize).max(0) as usize; - let max_x = ((cx + rx).ceil() as isize).min(w as isize - 1); - let min_y = ((cy - ry).floor() as isize).max(0) as usize; - let max_y = ((cy + ry).ceil() as isize).min(h as isize - 1); - if max_x < min_x as isize || max_y < min_y as isize { - return; - } - - let inv_dw = 1.0 / draw_w; - let inv_dh = 1.0 / draw_h; - let edge_u = inv_dw * 0.5; - let edge_v = inv_dh * 0.5; - let sw_i = sprite.size[0] as usize; - let sh_i = sprite.size[1] as usize; - - for py in min_y..=(max_y as usize) { - let dy = (py as f64 + 0.5) - cy; - let row_off = py * w * 4; - for px in min_x..=(max_x as usize) { - let dx = (px as f64 + 0.5) - cx; - // Inverse rotate into sprite local space (CCW in Y-up). - let lx = dx * cos_t - dy * sin_t; - let ly = dx * sin_t + dy * cos_t; - - let u = lx * inv_dw + 0.5; - let v = ly * inv_dh + 0.5; - if u <= -edge_u || u >= 1.0 + edge_u || v <= -edge_v || v >= 1.0 + edge_v { - continue; - } - - // Anti-aliased border coverage (0.5px feather at edges). - let cov_u = ((u + edge_u) / (2.0 * edge_u)) - .min((1.0 + edge_u - u) / (2.0 * edge_u)) - .clamp(0.0, 1.0); - let cov_v = ((v + edge_v) / (2.0 * edge_v)) - .min((1.0 + edge_v - v) / (2.0 * edge_v)) - .clamp(0.0, 1.0); - let cov = (cov_u * cov_v) as f32; - if cov <= 1e-4 { - continue; - } - - let sample = sample_sprite_bilinear( - &sprite.rgba, - sw_i, - sh_i, - u.clamp(0.0, 1.0), - v.clamp(0.0, 1.0), - ); - let alpha_scale = tint[3] * cov; - let pa = sample[3] * alpha_scale; - if pa <= 1e-5 { - continue; - } - let pr = sample[0] * tint[0] * alpha_scale; - let pg = sample[1] * tint[1] * alpha_scale; - let pb = sample[2] * tint[2] * alpha_scale; - - let idx = row_off + px * 4; - let inv_a = 1.0 - pa; - accum[idx] = pr + accum[idx] * inv_a; - accum[idx + 1] = pg + accum[idx + 1] * inv_a; - accum[idx + 2] = pb + accum[idx + 2] * inv_a; - accum[idx + 3] = pa + accum[idx + 3] * inv_a; - } - } -} - -#[inline] -fn sample_sprite_bilinear(rgba: &[u8], w: usize, h: usize, u: f64, v: f64) -> [f32; 4] { - let fx = (u * w as f64 - 0.5).clamp(0.0, (w - 1) as f64); - let fy = (v * h as f64 - 0.5).clamp(0.0, (h - 1) as f64); - let x0 = fx.floor() as usize; - let y0 = fy.floor() as usize; - let x1 = (x0 + 1).min(w - 1); - let y1 = (y0 + 1).min(h - 1); - let tx = (fx - x0 as f64) as f32; - let ty = (fy - y0 as f64) as f32; - - let i00 = (y0 * w + x0) * 4; - let i10 = (y0 * w + x1) * 4; - let i01 = (y1 * w + x0) * 4; - let i11 = (y1 * w + x1) * 4; - - let w00 = (1.0 - tx) * (1.0 - ty) * (1.0 / 255.0); - let w10 = tx * (1.0 - ty) * (1.0 / 255.0); - let w01 = (1.0 - tx) * ty * (1.0 / 255.0); - let w11 = tx * ty * (1.0 / 255.0); - - [ - rgba[i00] as f32 * w00 - + rgba[i10] as f32 * w10 - + rgba[i01] as f32 * w01 - + rgba[i11] as f32 * w11, - rgba[i00 + 1] as f32 * w00 - + rgba[i10 + 1] as f32 * w10 - + rgba[i01 + 1] as f32 * w01 - + rgba[i11 + 1] as f32 * w11, - rgba[i00 + 2] as f32 * w00 - + rgba[i10 + 2] as f32 * w10 - + rgba[i01 + 2] as f32 * w01 - + rgba[i11 + 2] as f32 * w11, - rgba[i00 + 3] as f32 * w00 - + rgba[i10 + 3] as f32 * w10 - + rgba[i01 + 3] as f32 * w01 - + rgba[i11 + 3] as f32 * w11, - ] -} - -/// Source-over blends one premultiplied-accumulator pixel; out-of-bounds coordinates are ignored. -#[inline] -fn blend_pixel(accum: &mut [f32], w: usize, h: usize, x: f64, y: f64, color: [f32; 4]) { - if x < 0.0 || y < 0.0 || x >= w as f64 || y >= h as f64 { - return; - } - let pa = color[3].clamp(0.0, 1.0); - if pa <= 1e-5 { - return; - } - let idx = (y as usize * w + x as usize) * 4; - let inv_a = 1.0 - pa; - accum[idx] = color[0] * pa + accum[idx] * inv_a; - accum[idx + 1] = color[1] * pa + accum[idx + 1] * inv_a; - accum[idx + 2] = color[2] * pa + accum[idx + 2] * inv_a; - accum[idx + 3] = pa + accum[idx + 3] * inv_a; -} - -/// Gaussian falloff sampled at pixel centers out to `4 sigma`, scaled by `shape(dx, dy)`. -#[allow(clippy::too_many_arguments)] -fn draw_soft_particle( - accum: &mut [f32], - w: usize, - h: usize, - cx: f64, - cy: f64, - sigma: f64, - color: [f32; 4], - shape: impl Fn(f64, f64) -> f64, -) { - let bound = 4.0 * sigma; - let min_x = ((cx - bound).floor() as isize).max(0); - let max_x = ((cx + bound).ceil() as isize).min(w as isize - 1); - let min_y = ((cy - bound).floor() as isize).max(0); - let max_y = ((cy + bound).ceil() as isize).min(h as isize - 1); - let inv_two_sigma_sq = 0.5 / (sigma * sigma); - for py in min_y..=max_y { - let dy = (py as f64 + 0.5) - cy; - for px in min_x..=max_x { - let dx = (px as f64 + 0.5) - cx; - let cov = ((-(dx * dx + dy * dy) * inv_two_sigma_sq).exp() * shape(dx, dy)) as f32; - blend_pixel(accum, w, h, px as f64, py as f64, [color[0], color[1], color[2], color[3] * cov]); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::path::Path; - use std::time::Instant; - - fn make_white_sprite(size: u32) -> SpriteImage { - SpriteImage { - size: [size, size], - rgba: vec![255u8; (size as usize) * (size as usize) * 4], - } - } - - fn count_nonzero_alpha(buf: &[u8]) -> usize { - buf.chunks_exact(4).filter(|px| px[3] > 0).count() - } - - #[test] - fn test_particle_emitter_and_point_force_deterministic() { - let comp_src = r#" -Composition { - GlobalRange = { 0, 100 }, - RenderRange = { 0, 100 }, - Tools = { - SpriteSrc = Background { - Inputs = { - Width = Input { Value = 32, }, - Height = Input { Value = 32, }, - }, - }, - pEmitter1SizeOverLife = LUTBezier { - KeyColorSplines = { - [0] = { - [0] = { 0.5, RH = { 0.333, 0.5 }, Flags = { Linear = true } }, - [1] = { 0.25, LH = { 0.667, 0.25 }, Flags = { Linear = true } } - } - }, - }, - pEmitter1 = pEmitter { - Inputs = { - RandomSeed = Input { Value = 42, }, - Number = Input { Value = 15, }, - Lifespan = Input { Value = 60, }, - Region = Input { Value = FuID { "RectRgn" }, }, - ["RectRgn.Width"] = Input { Value = 0.6, }, - ["RectRgn.Height"] = Input { Value = 0.4, }, - Style = Input { Value = FuID { "ParticleStyleBitmap" }, }, - ["ParticleStyleBitmap.DropToolsHere"] = Input { - SourceOp = "SpriteSrc", - Source = "Output", - }, - ["ParticleStyle.Red"] = Input { Value = 1, }, - ["ParticleStyle.Green"] = Input { Value = 0, }, - ["ParticleStyle.Blue"] = Input { Value = 0, }, - ["ParticleStyle.ColorVariance"] = Input { Value = 1, }, - ["ParticleStyle.GreenHigh"] = Input { Value = 1, }, - ["ParticleStyle.Size"] = Input { Value = 0.12, }, - ["ParticleStyle.SizeOverLife"] = Input { - SourceOp = "pEmitter1SizeOverLife", - Source = "Value", - }, - ["ParticleStyle.FadeIn"] = Input { Value = 0.1, }, - ["ParticleStyle.FadeOut"] = Input { Value = 0.1, }, - }, - }, - pPointForce1 = pPointForce { - Inputs = { - Strength = Input { Value = -3.0, }, - Power = Input { Value = 0.5, }, - ["Translate.X"] = Input { Value = 0.0, }, - ["Translate.Y"] = Input { Value = 0.0, }, - Input = Input { - SourceOp = "pEmitter1", - Source = "Output", - }, - }, - }, - pRender1 = pRender { - Inputs = { - Input = Input { - SourceOp = "pPointForce1", - Source = "Output", - }, - }, - }, - }, -} -"#; - - let comp = Comp::from_fusion_str(comp_src).expect("parse synthetic particle comp"); - let render_id = comp.node_by_name["pRender1"]; - let emitter_id = comp.node_by_name["pEmitter1"]; - let sprite_id = comp.node_by_name["SpriteSrc"]; - let force_id = comp.node_by_name["pPointForce1"]; - - // Verify bitmap source discovery. - let sources = collect_bitmap_sources(&comp, render_id); - assert_eq!(sources, vec![(emitter_id, sprite_id)]); - - let expr = ExprEngine::new(); - let mut sprites = HashMap::new(); - sprites.insert(emitter_id, make_white_sprite(16)); - - let dims = [160, 90]; - - // 1. Determinism: two fresh caches produce bit-identical buffers. - let mut cache_a = ParticleCache::default(); - let mut cache_b = ParticleCache::default(); - let img_a = render_particles_2d(&mut cache_a, &comp, render_id, 25.0, dims, &expr, &sprites); - let img_b = render_particles_2d(&mut cache_b, &comp, render_id, 25.0, dims, &expr, &sprites); - assert_eq!(img_a, img_b, "particle render must be bit-identical across runs"); - assert!( - count_nonzero_alpha(&img_a) > 50, - "expected non-empty rendered particles" - ); - - // 2. Force affects particle trajectories: bypassing pPointForce1 changes output. - let mut comp_no_force = comp.clone(); - comp_no_force.nodes[force_id.0].bypassed = true; - comp_no_force.revision += 1; - let mut cache_no_force = ParticleCache::default(); - let img_no_force = render_particles_2d( - &mut cache_no_force, - &comp_no_force, - render_id, - 25.0, - dims, - &expr, - &sprites, - ); - assert_ne!( - img_a, img_no_force, - "pPointForce must visibly change particle trajectories" - ); - - // 3. Cache consistency & sequential speedup: stepping 25 -> 26 matches fresh 0 -> 26. - let t_seq_start = Instant::now(); - let img_26_cached = - render_particles_2d(&mut cache_a, &comp, render_id, 26.0, dims, &expr, &sprites); - let seq_elapsed = t_seq_start.elapsed(); - - let mut fresh_cache = ParticleCache::default(); - let t_fresh_start = Instant::now(); - let img_26_fresh = render_particles_2d( - &mut fresh_cache, - &comp, - render_id, - 26.0, - dims, - &expr, - &sprites, - ); - let fresh_elapsed = t_fresh_start.elapsed(); - assert_eq!( - img_26_cached, img_26_fresh, - "cached sequential step must match fresh simulation" - ); - assert!( - seq_elapsed <= fresh_elapsed * 2 + std::time::Duration::from_millis(5), - "cached sequential step should be fast (seq={seq_elapsed:?}, fresh={fresh_elapsed:?})" - ); - - cache_a.clear(); - assert!(cache_a.entries.is_empty()); - } - - #[test] - fn test_01_intro_particles_if_present() { - let path = Path::new("/Volumes/Project/trees/fusion/01_intro.comp"); - if !path.exists() { - return; - } - - let comp = Comp::from_fusion_file(path).expect("parse 01_intro.comp"); - let render_id = comp.node_by_name["pRender1"]; - let emitter_id = comp.node_by_name["pEmitter1"]; - let bc4_id = comp.node_by_name["BrightnessContrast4"]; - - let sources = collect_bitmap_sources(&comp, render_id); - assert_eq!( - sources, - vec![(emitter_id, bc4_id)], - "01_intro.comp pEmitter1 bitmap source should be BrightnessContrast4" - ); - - let expr = ExprEngine::new(); - let mut sprites = HashMap::new(); - sprites.insert(emitter_id, make_white_sprite(32)); - - // In 01_intro.comp, TimeStretcher1 evaluates pRender1 at SourceTime = time / 25 - // (so comp f600 -> t=24, comp f1600 -> t=64). - let ts_node = &comp.nodes[comp.node_by_name["TimeStretcher1"].0]; - let t_f600 = comp.eval_number(ts_node, "SourceTime", 600.0, 24.0, &expr); - let t_f1600 = comp.eval_number(ts_node, "SourceTime", 1600.0, 64.0, &expr); - - let dims = [320, 180]; - let mut cache = ParticleCache::default(); - let start = Instant::now(); - let buf_600 = render_particles_2d(&mut cache, &comp, render_id, t_f600, dims, &expr, &sprites); - let buf_1600 = - render_particles_2d(&mut cache, &comp, render_id, t_f1600, dims, &expr, &sprites); - let elapsed = start.elapsed(); - - let nz_600 = count_nonzero_alpha(&buf_600); - assert!( - nz_600 > 0, - "expected non-zero alpha pixels at f600 (SourceTime={t_f600})" - ); - assert_eq!( - buf_1600.len(), - dims[0] as usize * dims[1] as usize * 4, - "f1600 SourceTime={t_f1600}" - ); - assert!( - elapsed.as_secs_f64() < 2.0, - "01_intro particle render should be fast, took {elapsed:?}" - ); - } - - #[test] - fn test_pbounce_reverses_velocity_and_applies_friction() { - let comp_src = r#" -Composition { - GlobalRange = { 0, 20 }, - RenderRange = { 0, 20 }, - Tools = { - pEmitter1 = pEmitter { - Inputs = { - Number = Input { Value = 1, }, - Lifespan = Input { Value = 50, }, - Velocity = Input { Value = 1.0, }, - Angle = Input { Value = -60, }, - ["SphereRgn.Size"] = Input { Value = 0, }, - ["SphereRgn.Translate.Y"] = Input { Value = 0.2, }, - }, - }, - pBounce1 = pBounce { - Inputs = { - Input = Input { SourceOp = "pEmitter1", Source = "Output", }, - Elasticity = Input { Value = 0.8, }, - Friction = Input { Value = 0.25, }, - Spin = Input { Value = 3.0, }, - Region = Input { Value = FuID { "CubeRgn" }, }, - ["CubeRgn.Translate.Y"] = Input { Value = -0.25, }, - ["CubeRgn.Width"] = Input { Value = 2.0, }, - ["CubeRgn.Height"] = Input { Value = 0.5, }, - ["CubeRgn.Depth"] = Input { Value = 2.0, }, - }, - }, - pRender1 = pRender { - Inputs = { - Input = Input { SourceOp = "pBounce1", Source = "Output", }, - }, - }, - }, -} -"#; - let comp = Comp::from_fusion_str(comp_src).expect("parse pBounce comp"); - let render_id = comp.node_by_name["pRender1"]; - let plan = build_particle_plan(&comp, render_id); - let expr = ExprEngine::new(); - let mut state = SimState::default(); - - // Step until the first emitted particle (born at f=0 at y=0.2, vy≈-0.0866, vx=0.05) - // crosses the floor at y=0.0 around frame 3. - for f in 0..=4 { - step_simulation(&mut state, &comp, &plan, f, &expr); - } - let first = state.particles.first().expect("particle emitted"); - let init_vx = 0.1 * (-60.0_f64).to_radians().cos(); - let init_vy = 0.1 * (-60.0_f64).to_radians().sin(); - assert!( - first.vel[1] > 0.0, - "pBounce should reverse downward Y velocity (got vy={})", - first.vel[1] - ); - assert!( - (first.vel[1] - (-init_vy * 0.8)).abs() < 1e-4, - "expected reflected vy={}, got {}", - -init_vy * 0.8, - first.vel[1] - ); - assert!( - (first.vel[0] - init_vx * 0.75).abs() < 1e-4, - "expected friction-damped vx={}, got {}", - init_vx * 0.75, - first.vel[0] - ); - assert!(first.spin_z.abs() > 0.5, "expected Spin impulse on bounce"); - assert!(first.pos[1] > 0.0, "bounced particle should be above floor y=0"); - } - - /// Single-particle comp: `Number` is a spline that is 1 at frame 0 and 0 afterwards. - fn single_particle_comp(emitter_inputs: &str, forces: &str, last_node: &str) -> Comp { - let src = format!( - r#" -Composition {{ - GlobalRange = {{ 0, 100 }}, - RenderRange = {{ 0, 100 }}, - Tools = {{ - EN = BezierSpline {{ - KeyFrames = {{ - [0] = {{ 1, Flags = {{ Linear = true }} }}, - [1] = {{ 0, Flags = {{ Linear = true }} }} - }} - }}, - pEmitter1 = pEmitter {{ - Inputs = {{ - Number = Input {{ SourceOp = "EN", Source = "Value", }}, - Lifespan = Input {{ Value = 100, }}, - ["SphereRgn.Size"] = Input {{ Value = 0, }}, - {emitter_inputs} - }}, - }}, - {forces} - pRender1 = pRender {{ - Inputs = {{ - Input = Input {{ SourceOp = "{last_node}", Source = "Output", }}, - }}, - }}, - }}, -}} -"# - ); - Comp::from_fusion_str(&src).expect("parse single-particle comp") - } - - fn render(comp: &Comp, time: f64, dims: [u32; 2], sprites: &HashMap) -> Vec { - let mut cache = ParticleCache::default(); - render_particles_2d(&mut cache, comp, comp.node_by_name["pRender1"], time, dims, &ExprEngine::new(), sprites) - } - - /// `(x, y, alpha)` of every pixel with non-zero alpha. - fn lit(buf: &[u8], width: usize) -> Vec<(usize, usize, u8)> { - buf.chunks_exact(4) - .enumerate() - .filter(|(_, px)| px[3] > 0) - .map(|(i, px)| (i % width, i / width, px[3])) - .collect() - } - - fn alpha_mass(buf: &[u8]) -> f64 { - buf.chunks_exact(4).map(|px| px[3] as f64 / 255.0).sum() - } - - #[test] - fn point_style_is_one_pixel_regardless_of_size() { - let comp = single_particle_comp(r#"["ParticleStyle.Size"] = Input { Value = 5, },"#, "", "pEmitter1"); - let buf = render(&comp, 0.0, [200, 100], &HashMap::new()); - assert_eq!(lit(&buf, 200), vec![(100, 50, 255)]); - } - - #[test] - fn blob_is_gaussian_with_sigma_per_size_unit() { - let comp = single_particle_comp( - r#"Style = Input { Value = FuID { "ParticleStyleBlob" }, }, ["ParticleStyle.Size"] = Input { Value = 2, },"#, - "", - "pEmitter1", - ); - // Fusion 21.1: Size 2 blob has alpha mass ~276 (= 2*pi*(2*3.316)^2). - let mass = alpha_mass(&render(&comp, 0.0, [256, 256], &HashMap::new())); - assert!((mass - 276.0).abs() < 8.0, "blob mass {mass}"); - } - - #[test] - fn newborn_moves_once_at_tenth_width_velocity() { - let comp = single_particle_comp( - r#"VelocityControls = Input { Value = 1, }, Velocity = Input { Value = 1, }, Angle = Input { Value = 0, },"#, - "", - "pEmitter1", - ); - let at = |t: f64| lit(&render(&comp, t, [200, 100], &HashMap::new()), 200)[0].0; - assert_eq!(at(0.0), 120); - assert_eq!(at(2.0), 160); - } - - #[test] - fn directional_force_accelerates_down_by_strength_over_one_hundred() { - let comp = single_particle_comp( - "", - r#"pDirectionalForce1 = pDirectionalForce { - Inputs = { - Strength = Input { Value = 1, }, - Input = Input { SourceOp = "pEmitter1", Source = "Output", }, - }, - },"#, - "pDirectionalForce1", - ); - // y(f) = 0.01 * f(f+1)/2 widths below the spawn point. - let buf = render(&comp, 4.0, [1000, 1000], &HashMap::new()); - assert_eq!(lit(&buf, 1000), vec![(500, 600, 255)]); - } - - #[test] - fn particle_lives_while_age_is_below_lifespan() { - let comp = single_particle_comp(r#"Lifespan = Input { Value = 3, },"#, "", "pEmitter1"); - let count = |t: f64| lit(&render(&comp, t, [64, 64], &HashMap::new()), 64).len(); - assert_eq!((count(0.0), count(2.0), count(3.0)), (1, 1, 0)); - } - - #[test] - fn fade_out_starts_at_fade_out_fraction_of_life() { - let comp = single_particle_comp( - r#"Lifespan = Input { Value = 20, }, Style = Input { Value = FuID { "ParticleStyleBlob" }, }, - ["ParticleStyle.Size"] = Input { Value = 2, }, ["ParticleStyle.FadeOut"] = Input { Value = 0.5, },"#, - "", - "pEmitter1", - ); - let mass = |t: f64| alpha_mass(&render(&comp, t, [256, 256], &HashMap::new())); - assert!((mass(15.0) / mass(10.0) - 0.5).abs() < 0.02); - } - - #[test] - fn bitmap_width_is_size_times_sprite_pixels() { - let comp = single_particle_comp( - r#"Style = Input { Value = FuID { "ParticleStyleBitmap" }, }, ["ParticleStyle.Size"] = Input { Value = 2, },"#, - "", - "pEmitter1", - ); - let mut sprites = HashMap::new(); - sprites.insert(comp.node_by_name["pEmitter1"], make_white_sprite(4)); - let pixels = lit(&render(&comp, 0.0, [200, 100], &sprites), 200); - let (min_x, max_x) = pixels.iter().fold((usize::MAX, 0), |(lo, hi), &(x, _, _)| (lo.min(x), hi.max(x))); - assert!((8..=9).contains(&(max_x - min_x + 1)), "bitmap width {}", max_x - min_x + 1); - } - - #[test] - fn default_region_is_sphere_of_diameter_one_tenth_width() { - let comp = Comp::from_fusion_str("Composition { Tools = { pEmitter1 = pEmitter { Inputs = { }, }, }, }") - .expect("parse bare emitter"); - let node = &comp.nodes[comp.node_by_name["pEmitter1"].0]; - match RegionSpec::from_node(&comp, node, 0.0, &ExprEngine::new()) { - RegionSpec::Sphere { radius, .. } => assert!((radius - 0.05).abs() < 1e-12), - _ => panic!("default region must be a sphere"), - } - } - - #[test] - fn depth_scales_screen_position_by_camera_distance() { - let comp = single_particle_comp( - r#"["SphereRgn.Translate.X"] = Input { Value = 0.2, }, ["SphereRgn.Translate.Z"] = Input { Value = 0.9722222222222222, },"#, - "", - "pEmitter1", - ); - // z equal to the camera distance halves the projected offset: x = (0.2 * 0.5 + 0.5) * 1000. - let buf = render(&comp, 0.0, [1000, 1000], &HashMap::new()); - assert_eq!(lit(&buf, 1000), vec![(600, 500, 255)]); - } - - #[test] - fn particle_cache_advances_past_600_incrementally_and_scrubs_with_snapshots() { - let comp_src = r#" -Composition { - GlobalRange = { 0, 800 }, - RenderRange = { 0, 800 }, - Tools = { - pEmitter1 = pEmitter { - Inputs = { - RandomSeed = Input { Value = 7, }, - Number = Input { Value = 2, }, - Lifespan = Input { Value = 25, }, - Velocity = Input { Value = 0.2, }, - VelocityVariance = Input { Value = 0.1, }, - AngleVariance = Input { Value = 180, }, - }, - }, - pRender1 = pRender { - Inputs = { - Input = Input { SourceOp = "pEmitter1", Source = "Output", }, - }, - }, - }, -} -"#; - let comp = Comp::from_fusion_str(comp_src).expect("parse particle comp"); - let render_id = comp.node_by_name["pRender1"]; - let expr = ExprEngine::new(); - let sprites = HashMap::new(); - let dims = [64, 64]; - - let mut cache = ParticleCache::default(); - let mut last_img = Vec::new(); - for f in 580..=625 { - last_img = render_particles_2d(&mut cache, &comp, render_id, f as f64, dims, &expr, &sprites); - } - - let key = ( - "pRender1".to_owned(), - particle_subgraph_hash(&comp, render_id, 0), - ); - let cached = cache.entries.get(&key).expect("cached entry"); - assert_eq!(cached.base_start, 0); - assert_eq!(cached.current_frame, 625); - assert!(cached.snapshots.contains_key(&600), "expected snapshot at frame 600"); - - // Scrubbing back to frame 605 restores snapshot 600 and matches direct render at 605. - let scrub_605 = render_particles_2d(&mut cache, &comp, render_id, 605.0, dims, &expr, &sprites); - let mut fresh_cache = ParticleCache::default(); - let fresh_605 = render_particles_2d(&mut fresh_cache, &comp, render_id, 605.0, dims, &expr, &sprites); - assert_eq!(scrub_605, fresh_605, "scrubbed frame 605 must match fresh simulation"); - - let mut fresh_625_cache = ParticleCache::default(); - let fresh_625 = render_particles_2d(&mut fresh_625_cache, &comp, render_id, 625.0, dims, &expr, &sprites); - assert_eq!(last_img, fresh_625, "incremental advance past 600 must match fresh simulation"); - } - - #[test] - fn particle_cache_ignores_unrelated_comp_edits_and_node_id_shifts() { - let with_unrelated = r#" -Composition { - GlobalRange = { 0, 100 }, - RenderRange = { 0, 100 }, - Tools = { - UnrelatedBg = Background { - Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, }, - }, - pEmitter1 = pEmitter { - Inputs = { - RandomSeed = Input { Value = 19, }, - Number = Input { Value = 8, }, - Lifespan = Input { Value = 40, }, - Velocity = Input { Value = 0.5, }, - VelocityVariance = Input { Value = 0.25, }, - AngleVariance = Input { Value = 180, }, - }, - }, - pRender1 = pRender { - Inputs = { - Input = Input { SourceOp = "pEmitter1", Source = "Output", }, - }, - }, - }, -} -"#; - let without_unrelated = r#" -Composition { - GlobalRange = { 0, 100 }, - RenderRange = { 0, 100 }, - Tools = { - pEmitter1 = pEmitter { - Inputs = { - RandomSeed = Input { Value = 19, }, - Number = Input { Value = 8, }, - Lifespan = Input { Value = 40, }, - Velocity = Input { Value = 0.5, }, - VelocityVariance = Input { Value = 0.25, }, - AngleVariance = Input { Value = 180, }, - }, - }, - pRender1 = pRender { - Inputs = { - Input = Input { SourceOp = "pEmitter1", Source = "Output", }, - }, - }, - }, -} -"#; - let mut comp_a = Comp::from_fusion_str(with_unrelated).expect("parse comp_a"); - let comp_b = Comp::from_fusion_str(without_unrelated).expect("parse comp_b"); - let ra = comp_a.node_by_name["pRender1"]; - let rb = comp_b.node_by_name["pRender1"]; - assert_ne!(ra, rb, "deleting UnrelatedBg should shift NodeIds"); - - let expr = ExprEngine::new(); - let sprites = HashMap::new(); - let dims = [64, 64]; - - let mut cache_a = ParticleCache::default(); - let img_a_20 = render_particles_2d(&mut cache_a, &comp_a, ra, 20.0, dims, &expr, &sprites); - - // Bumping comp.revision (simulating unrelated node edit) reuses cached simulation. - comp_a.revision += 99; - let hash_before = particle_subgraph_hash(&comp_a, ra, 0); - let hash_after_del = particle_subgraph_hash(&comp_b, rb, 0); - assert_eq!(hash_before, hash_after_del, "subgraph hash must ignore NodeId shifts and unrelated nodes"); - - let mut cache_b = ParticleCache::default(); - let img_b_20 = render_particles_2d(&mut cache_b, &comp_b, rb, 20.0, dims, &expr, &sprites); - assert_eq!(img_a_20, img_b_20, "deleting an unrelated node must not re-randomize particles"); - - // Stepping comp_b using cache_a (which has old NodeIds!) must still match fresh comp_b at frame 21. - let img_a_to_b_21 = render_particles_2d(&mut cache_a, &comp_b, rb, 21.0, dims, &expr, &sprites); - let mut fresh_b = ParticleCache::default(); - let img_b_21 = render_particles_2d(&mut fresh_b, &comp_b, rb, 21.0, dims, &expr, &sprites); - assert_eq!(img_a_to_b_21, img_b_21); - } - - #[test] - fn cyclic_expression_modifier_does_not_stack_overflow() { - let comp_src = r#" -Composition { - GlobalRange = { 0, 20 }, - RenderRange = { 0, 20 }, - Tools = ordered() { - Expr1 = Expression { - Inputs = { - n1 = Input { SourceOp = "Expr1", Source = "NumberResult", }, - NumberExpression = Input { Value = "n1 + 4", }, - }, - }, - pEmitter1 = pEmitter { - Inputs = { - RandomSeed = Input { Value = 7, }, - Number = Input { SourceOp = "Expr1", Source = "NumberResult", }, - Lifespan = Input { Value = 15, }, - Velocity = Input { Value = 0.2, }, - }, - }, - pRender1 = pRender { - Inputs = { - Input = Input { SourceOp = "pEmitter1", Source = "Output", }, - }, - }, - }, -} -"#; - let comp = Comp::from_fusion_str(comp_src).expect("parse cyclic Expr1 comp"); - assert!(comp.expression_modifiers.contains_key("Expr1")); - let pr = comp.find_node("pRender1").expect("find pRender1"); - let expr = ExprEngine::new(); - let sprites = HashMap::new(); - let mut cache = ParticleCache::default(); - - // Both subgraph hashing and particle evaluation must terminate cleanly without overflowing. - let h1 = particle_subgraph_hash(&comp, pr, 0); - let h2 = particle_subgraph_hash(&comp, pr, 0); - assert_eq!(h1, h2); - - let img = render_particles_2d(&mut cache, &comp, pr, 5.0, [64, 64], &expr, &sprites); - assert_eq!(img.len(), 64 * 64 * 4); - } -} diff --git a/crates/engine/src/particles/plan.rs b/crates/engine/src/particles/plan.rs new file mode 100644 index 0000000000000000000000000000000000000000..d298ed95e4a74a7692f182b7a15e1521676e9935 --- /dev/null +++ b/crates/engine/src/particles/plan.rs @@ -0,0 +1,395 @@ +//! Particle graph traversal, bitmap source discovery, and deterministic subgraph hashing. + +use std::collections::hash_map::DefaultHasher; +use std::collections::{HashMap, HashSet}; +use std::hash::{Hash, Hasher}; + +use model::{BezierSpline, Comp, Gradient, InputBinding, Node, NodeId, ParamValue}; + +use super::stable_name_hash; + +/// Returns true if `kind` is a Fusion particle stream operator. +pub(super) fn is_particle_node_kind(kind: &str) -> bool { + matches!( + kind, + "pRender" + | "pEmitter" + | "pPointForce" + | "pDirectionalForce" + | "pTurbulence" + | "pDrag" + | "pFriction" + | "pKill" + | "pMerge" + | "pBounce" + | "pVortex" + | "pFlock" + | "pAvoid" + | "pSpawn" + | "pChangeStyle" + | "pCustom" + | "pCustomForce" + | "pGradientForce" + | "pImageEmitter" + ) || (kind.starts_with('p') + && kind + .as_bytes() + .get(1) + .is_some_and(|b| b.is_ascii_uppercase())) +} + +/// Returns the particle stream input node IDs of `node` in deterministic order. +pub(super) fn particle_stream_inputs(comp: &Comp, node: &Node) -> Vec { + let mut ports: Vec<&str> = Vec::new(); + for key in node.inputs.keys() { + if key == "Input" + || key + .strip_prefix("Input") + .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit())) + { + ports.push(key.as_str()); + } + } + ports.sort_unstable(); + + let mut out = Vec::with_capacity(ports.len()); + for port in ports { + if let Some(src_name) = node.connected_node(port) { + if let Some(&src_id) = comp.node_by_name.get(src_name) { + out.push(src_id); + } + } + } + out +} + +/// Walks upstream from `render_node` through particle operators and returns every +/// `(emitter_node_id, sprite_source_node_id)` pair for `pEmitter` nodes whose +/// `ParticleStyleBitmap.DropToolsHere` input is connected. +pub fn collect_bitmap_sources(comp: &Comp, render_node: NodeId) -> Vec<(NodeId, NodeId)> { + let mut visited = HashSet::new(); + let mut out = Vec::new(); + collect_bitmap_sources_dfs(comp, render_node, &mut visited, &mut out); + out +} + +fn collect_bitmap_sources_dfs( + comp: &Comp, + node_id: NodeId, + visited: &mut HashSet, + out: &mut Vec<(NodeId, NodeId)>, +) { + if !visited.insert(node_id) { + return; + } + let Some(node) = comp.nodes.get(node_id.0) else { + return; + }; + if !is_particle_node_kind(&node.kind) { + return; + } + + if node.kind == "pEmitter" { + if let Some(src_name) = node.connected_node("ParticleStyleBitmap.DropToolsHere") { + if let Some(&src_id) = comp.node_by_name.get(src_name) { + out.push((node_id, src_id)); + } + } + } + + for up_id in particle_stream_inputs(comp, node) { + collect_bitmap_sources_dfs(comp, up_id, visited, out); + } +} + +/// Flattened, topologically-ordered particle graph upstream of a `pRender` node. +pub(super) struct ParticlePlan { + pub(super) emitters: Vec<(NodeId, u64)>, + /// Forces/modifiers in topological order along with the set of upstream + /// emitter name hashes whose particles flow through each modifier. + pub(super) modifiers: Vec<(NodeId, HashSet)>, + pub(super) emitter_nodes: HashMap, +} + +pub(super) fn build_particle_plan(comp: &Comp, render_node: NodeId) -> ParticlePlan { + let mut visited = HashSet::new(); + let mut emitters = Vec::new(); + let mut modifiers = Vec::new(); + let mut upstream_emitters: HashMap> = HashMap::new(); + let mut emitter_nodes = HashMap::new(); + + build_plan_dfs( + comp, + render_node, + &mut visited, + &mut emitters, + &mut modifiers, + &mut upstream_emitters, + &mut emitter_nodes, + ); + + ParticlePlan { + emitters, + modifiers, + emitter_nodes, + } +} + +fn build_plan_dfs( + comp: &Comp, + node_id: NodeId, + visited: &mut HashSet, + emitters: &mut Vec<(NodeId, u64)>, + modifiers: &mut Vec<(NodeId, HashSet)>, + upstream_emitters: &mut HashMap>, + emitter_nodes: &mut HashMap, +) -> HashSet { + if let Some(cached) = upstream_emitters.get(&node_id) { + return cached.clone(); + } + if !visited.insert(node_id) { + return HashSet::new(); + } + + let Some(node) = comp.nodes.get(node_id.0) else { + return HashSet::new(); + }; + if !is_particle_node_kind(&node.kind) { + return HashSet::new(); + } + + let mut scope = HashSet::new(); + for up_id in particle_stream_inputs(comp, node) { + let up_set = build_plan_dfs( + comp, + up_id, + visited, + emitters, + modifiers, + upstream_emitters, + emitter_nodes, + ); + scope.extend(up_set); + } + + if node.kind == "pEmitter" { + if !node.bypassed { + let emitter_hash = stable_name_hash(&node.name); + emitters.push((node_id, emitter_hash)); + emitter_nodes.insert(emitter_hash, node_id); + scope.insert(emitter_hash); + } + } else if !node.bypassed + && matches!( + node.kind.as_str(), + "pPointForce" + | "pDirectionalForce" + | "pTurbulence" + | "pDrag" + | "pFriction" + | "pKill" + | "pBounce" + ) + { + modifiers.push((node_id, scope.clone())); + } + + upstream_emitters.insert(node_id, scope.clone()); + scope +} + +fn hash_spline(spline: &BezierSpline, h: &mut DefaultHasher) { + spline.name.hash(h); + spline.keyframes.len().hash(h); + for kf in &spline.keyframes { + kf.time.to_bits().hash(h); + kf.value.to_bits().hash(h); + if let Some([lx, ly]) = kf.lh { + 1u8.hash(h); + lx.to_bits().hash(h); + ly.to_bits().hash(h); + } else { + 0u8.hash(h); + } + if let Some([rx, ry]) = kf.rh { + 1u8.hash(h); + rx.to_bits().hash(h); + ry.to_bits().hash(h); + } else { + 0u8.hash(h); + } + [ + kf.flags.linear, + kf.flags.step_in, + kf.flags.step_out, + kf.flags.loop_after, + kf.flags.loop_rel, + kf.flags.ping_pong, + kf.flags.locked_y, + ] + .hash(h); + (kf.handle_mode as u8).hash(h); + } +} + +fn hash_gradient(grad: &Gradient, h: &mut DefaultHasher) { + grad.stops.len().hash(h); + for stop in &grad.stops { + stop.pos.to_bits().hash(h); + for c in stop.rgba { + c.to_bits().hash(h); + } + } +} + +fn hash_input_binding( + comp: &Comp, + binding: &InputBinding, + visited_mods: &mut HashSet, + h: &mut DefaultHasher, +) { + binding.source_output.hash(h); + binding.expression.hash(h); + match &binding.value { + None => 0u8.hash(h), + Some(ParamValue::Number(v)) => { + 1u8.hash(h); + v.to_bits().hash(h); + } + Some(ParamValue::Point([x, y])) => { + 2u8.hash(h); + x.to_bits().hash(h); + y.to_bits().hash(h); + } + Some(ParamValue::Text(s)) => { + 3u8.hash(h); + s.hash(h); + } + Some(ParamValue::FuId(s)) => { + 4u8.hash(h); + s.hash(h); + } + Some(ParamValue::Gradient(g)) => { + 5u8.hash(h); + hash_gradient(g, h); + } + Some(ParamValue::Raw(raw)) => { + 6u8.hash(h); + format!("{raw:?}").hash(h); + } + } + binding.source_op.hash(h); + if let Some(op) = &binding.source_op { + if let Some(sp) = comp.splines.get(op) { + hash_spline(sp, h); + } + if let Some(pp) = comp.poly_paths.get(op) { + pp.name.hash(h); + pp.displacement_op.hash(h); + pp.displacement_value.to_bits().hash(h); + pp.closed.hash(h); + pp.points.len().hash(h); + for pt in &pp.points { + pt.x.to_bits().hash(h); + pt.y.to_bits().hash(h); + pt.lx.to_bits().hash(h); + pt.ly.to_bits().hash(h); + pt.rx.to_bits().hash(h); + pt.ry.to_bits().hash(h); + pt.linear.hash(h); + } + if let Some(disp_op) = &pp.displacement_op { + if let Some(sp) = comp.splines.get(disp_op) { + hash_spline(sp, h); + } + } + } + if let Some(sh) = comp.shakes.get(op) { + if visited_mods.insert(op.clone()) { + hash_sorted_inputs(comp, &sh.inputs, visited_mods, h); + visited_mods.remove(op); + } else { + 0xC1C1_u16.hash(h); + op.hash(h); + } + } + if let Some(ex) = comp.expression_modifiers.get(op) { + if visited_mods.insert(op.clone()) { + hash_sorted_inputs(comp, &ex.inputs, visited_mods, h); + visited_mods.remove(op); + } else { + 0xC1C2_u16.hash(h); + op.hash(h); + } + } + if let Some(gm) = comp.gradient_modifiers.get(op) { + gm.len().hash(h); + for (t, g) in gm { + t.to_bits().hash(h); + hash_gradient(g, h); + } + } + } +} + +fn hash_sorted_inputs( + comp: &Comp, + inputs: &HashMap, + visited_mods: &mut HashSet, + h: &mut DefaultHasher, +) { + let mut keys: Vec<&String> = inputs.keys().collect(); + keys.sort_unstable(); + keys.len().hash(h); + for k in keys { + k.hash(h); + hash_input_binding(comp, &inputs[k], visited_mods, h); + } +} + +/// Content hash of the particle simulation subgraph upstream of `render_node`. +/// Unrelated edits outside the particle branch leave this hash unchanged. +pub(super) fn particle_subgraph_hash(comp: &Comp, render_node: NodeId, base_start: i64) -> u64 { + fn dfs( + comp: &Comp, + node_id: NodeId, + is_root: bool, + visited: &mut HashSet, + visited_mods: &mut HashSet, + h: &mut DefaultHasher, + ) { + if !visited.insert(node_id) { + return; + } + let Some(node) = comp.nodes.get(node_id.0) else { + return; + }; + if !is_particle_node_kind(&node.kind) { + return; + } + node.name.hash(h); + node.kind.hash(h); + node.bypassed.hash(h); + + let mut keys: Vec<&String> = node.inputs.keys().collect(); + keys.sort_unstable(); + for k in keys { + // `pRender.Width` and bitmap drop target only affect rasterization, not simulation state. + if (is_root && k == "Width") || k == "ParticleStyleBitmap.DropToolsHere" { + continue; + } + k.hash(h); + hash_input_binding(comp, &node.inputs[k], visited_mods, h); + } + for up_id in particle_stream_inputs(comp, node) { + dfs(comp, up_id, false, visited, visited_mods, h); + } + } + + let mut h = DefaultHasher::new(); + base_start.hash(&mut h); + let mut visited = HashSet::new(); + let mut visited_mods = HashSet::new(); + dfs(comp, render_node, true, &mut visited, &mut visited_mods, &mut h); + h.finish() +} diff --git a/crates/engine/src/particles/raster.rs b/crates/engine/src/particles/raster.rs new file mode 100644 index 0000000000000000000000000000000000000000..bca9b5c76a0e48f1cafbb349e232c612545d9ef7 --- /dev/null +++ b/crates/engine/src/particles/raster.rs @@ -0,0 +1,430 @@ +//! 2D particle rasterization (points, blobs, NGons, and bilinear bitmap sprites). + +use std::collections::HashMap; + +use model::{Comp, ExprEngine, Gradient, Node, NodeId}; + +use super::{ + BLOB_SIGMA_PER_SIZE, CAMERA_DISTANCE, Particle, ParticleStyleKind, SpriteImage, +}; + +struct EmitterRenderProps<'a> { + emitter_id: NodeId, + style: ParticleStyleKind, + tiny_sprite: Option<([f64; 2], SpriteImage)>, + ngon_sides: f64, + size_over_life: Option<&'a model::BezierSpline>, + fade_in: f64, + fade_out: f64, + color_over_life: Option, +} + +fn collect_emitter_render_props<'a>( + comp: &'a Comp, + emitter_nodes: &HashMap, + particles: &[Particle], + time: f64, + expr: &ExprEngine, +) -> HashMap> { + let mut map = HashMap::new(); + for p in particles { + if map.contains_key(&p.emitter_hash) { + continue; + } + let Some(&emitter_id) = emitter_nodes.get(&p.emitter_hash) else { + continue; + }; + let Some(node) = comp.nodes.get(emitter_id.0) else { + continue; + }; + let style = match node.static_str("Style") { + Some("ParticleStyleBitmap") => ParticleStyleKind::Bitmap, + Some("ParticleStyleBlob") => ParticleStyleKind::Blob, + Some("ParticleStyleNGon") => ParticleStyleKind::NGon, + Some("ParticleStyleBrush") => ParticleStyleKind::Brush, + _ => ParticleStyleKind::Point, + }; + let size_over_life = node + .inputs + .get("ParticleStyle.SizeOverLife") + .and_then(|b| b.source_op.as_deref()) + .and_then(|src| comp.splines.get(src)); + let fade_in = comp + .eval_number(node, "ParticleStyle.FadeIn", time, 0.0, expr) + .clamp(0.0, 1.0); + let fade_out = comp + .eval_number(node, "ParticleStyle.FadeOut", time, 1.0, expr) + .clamp(0.0, 1.0); + let color_over_life_on = + comp.eval_number(node, "ParticleStyle.ColorOverLifeControls", time, 0.0, expr) > 0.5; + let color_over_life = if color_over_life_on { + comp.eval_gradient(node, "ParticleStyle.ColorOverLife", time) + } else { + None + }; + map.insert( + p.emitter_hash, + EmitterRenderProps { + emitter_id, + style, + tiny_sprite: tiny_background_sprite(comp, node, time, expr), + ngon_sides: comp.eval_number(node, "ParticleStyleNGon.NGonSides", time, 5.0, expr).round().max(3.0), + size_over_life, + fade_in, + fade_out, + color_over_life, + }, + ); + } + map +} + +/// Solid sprite for a `Background` tool narrower than 16 px. +/// +/// The engine evaluates such tools at comp size, so the particle uses the tool's nominal +/// `Width`/`Height` and its flat color directly. +fn tiny_background_sprite( + comp: &Comp, + emitter: &Node, + t: f64, + expr: &ExprEngine, +) -> Option<([f64; 2], SpriteImage)> { + let src = emitter + .connected_node("ParticleStyleBitmap.DropToolsHere") + .and_then(|name| comp.find_node(name)) + .map(|id| &comp.nodes[id.0]) + .filter(|n| n.kind == "Background")?; + let w = comp.eval_number(src, "Width", t, 0.0, expr); + let h = comp.eval_number(src, "Height", t, 0.0, expr); + if !(w >= 1.0 && h >= 1.0 && (w < 16.0 || h < 16.0)) { + return None; + } + let channel = |name: &str, default: f64| comp.eval_number(src, name, t, default, expr).clamp(0.0, 1.0); + let a = channel("TopLeftAlpha", 1.0); + let px = |c: f64| (c * a * 255.0 + 0.5) as u8; + let rgba = vec![ + px(channel("TopLeftRed", 0.0)), + px(channel("TopLeftGreen", 0.0)), + px(channel("TopLeftBlue", 0.0)), + (a * 255.0 + 0.5) as u8, + ]; + Some(([w, h], SpriteImage { size: [1, 1], rgba })) +} + +#[allow(clippy::too_many_arguments)] +pub(super) fn rasterize_particles( + out: &mut [u8], + dims: [u32; 2], + px_scale: f64, + comp: &Comp, + emitter_nodes: &HashMap, + particles: &[Particle], + time: f64, + expr: &ExprEngine, + sprites: &HashMap, +) { + if particles.is_empty() { + return; + } + + let props_map = collect_emitter_render_props(comp, emitter_nodes, particles, time, expr); + let w = dims[0] as usize; + let h = dims[1] as usize; + let w_f = w as f64; + let h_f = h as f64; + + // Accumulate in linear-ish float premultiplied RGBA for clean blending, then pack to u8. + let mut accum = vec![0.0f32; w * h * 4]; + + for p in particles { + if !p.alive { + continue; + } + let Some(props) = props_map.get(&p.emitter_hash) else { + continue; + }; + + let life_frac = (p.age / p.lifespan.max(1.0)).clamp(0.0, 1.0); + // Fusion's SizeOverLife LUT maps 0.5 -> 1.0x (0.0 -> 0x, 1.0 -> 2x). + let size_mult = props + .size_over_life + .map(|sp| (2.0 * sp.eval(life_frac)).max(0.0)) + .unwrap_or(1.0); + let depth_scale = CAMERA_DISTANCE / (CAMERA_DISTANCE + p.pos[2]); + if !(depth_scale > 0.0) { + continue; + } + let size_world = p.size * size_mult * depth_scale; + if size_world <= 1e-6 { + continue; + } + + let mut fade = 1.0f64; + if props.fade_in > 1e-6 && life_frac < props.fade_in { + fade *= life_frac / props.fade_in; + } + if props.fade_out < 1.0 - 1e-6 && life_frac > props.fade_out { + fade *= ((1.0 - life_frac) / (1.0 - props.fade_out)).max(0.0); + } + + let mut cr = p.color[0]; + let mut cg = p.color[1]; + let mut cb = p.color[2]; + let mut ca = p.color[3] * fade as f32; + if let Some(grad) = &props.color_over_life { + let g = grad.sample(life_frac); + cr *= g[0]; + cg *= g[1]; + cb *= g[2]; + ca *= g[3]; + } + ca = ca.clamp(0.0, 1.0); + if ca <= 1e-4 { + continue; + } + + // Fusion 2D particle coordinates: X in [-0.5, +0.5], Y-up with same unit scale as X. + let cx = (p.pos[0] * depth_scale + 0.5) * w_f; + let cy = h_f * 0.5 - p.pos[1] * depth_scale * w_f; + + if props.style == ParticleStyleKind::Bitmap { + let (sprite, nominal) = match &props.tiny_sprite { + Some((nominal, sprite)) => (Some(sprite), *nominal), + None => { + let sprite = sprites.get(&props.emitter_id); + (sprite, sprite.map_or([0.0; 2], |s| [s.size[0] as f64, s.size[1] as f64])) + } + }; + if let Some(sprite) = sprite.filter(|s| { + s.size[0] > 0 + && s.size[1] > 0 + && s.rgba.len() >= (s.size[0] as usize).saturating_mul(s.size[1] as usize).saturating_mul(4) + }) { + draw_bitmap_particle( + &mut accum, + w, + h, + cx, + cy, + size_world * nominal[0] * px_scale, + size_world * nominal[1] * px_scale, + p.rot_z, + [cr, cg, cb, ca], + sprite, + ); + continue; + } + } + + match props.style { + ParticleStyleKind::Point => { + blend_pixel(&mut accum, w, h, cx.floor(), cy.floor(), [cr, cg, cb, ca]); + } + ParticleStyleKind::Blob | ParticleStyleKind::Bitmap => { + let sigma = BLOB_SIGMA_PER_SIZE * size_world * px_scale; + draw_soft_particle(&mut accum, w, h, cx, cy, sigma, [cr, cg, cb, ca], |_, _| 1.0); + } + ParticleStyleKind::NGon => { + let sigma = BLOB_SIGMA_PER_SIZE * size_world * px_scale; + let sides = props.ngon_sides; + let spike_period = std::f64::consts::TAU / sides; + let phase = std::f64::consts::FRAC_PI_2 + p.rot_z.to_radians(); + // Spike sharpness fitted to Fusion 21.1: alpha mass is 0.18/0.48/0.78 of a blob for 3/5/8 sides. + let sharpness = 4.5 * (3.0 / sides).powf(2.8); + draw_soft_particle(&mut accum, w, h, cx, cy, sigma, [cr, cg, cb, ca], |dx, dy| { + // Distance to the nearest spike, as a fraction of half the spike period. + let angle = (-dy).atan2(dx) - phase; + let off = angle.rem_euclid(spike_period); + let to_spike = off.min(spike_period - off); + (1.0 - to_spike / (0.5 * spike_period)).powf(sharpness) + }); + } + ParticleStyleKind::Brush => {} + } + } + + for (dst, &src) in out.iter_mut().zip(accum.iter()) { + *dst = (src.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + } +} + +#[allow(clippy::too_many_arguments)] +fn draw_bitmap_particle( + accum: &mut [f32], + w: usize, + h: usize, + cx: f64, + cy: f64, + draw_w: f64, + draw_h: f64, + rot_z_deg: f64, + tint: [f32; 4], + sprite: &SpriteImage, +) { + if draw_w < 0.5 || draw_h < 0.5 { + return; + } + + let hw = draw_w * 0.5; + let hh = draw_h * 0.5; + let theta = rot_z_deg.to_radians(); + let cos_t = theta.cos(); + let sin_t = theta.sin(); + + let rx = hw * cos_t.abs() + hh * sin_t.abs() + 1.0; + let ry = hw * sin_t.abs() + hh * cos_t.abs() + 1.0; + + let min_x = ((cx - rx).floor() as isize).max(0) as usize; + let max_x = ((cx + rx).ceil() as isize).min(w as isize - 1); + let min_y = ((cy - ry).floor() as isize).max(0) as usize; + let max_y = ((cy + ry).ceil() as isize).min(h as isize - 1); + if max_x < min_x as isize || max_y < min_y as isize { + return; + } + + let inv_dw = 1.0 / draw_w; + let inv_dh = 1.0 / draw_h; + let edge_u = inv_dw * 0.5; + let edge_v = inv_dh * 0.5; + let sw_i = sprite.size[0] as usize; + let sh_i = sprite.size[1] as usize; + + for py in min_y..=(max_y as usize) { + let dy = (py as f64 + 0.5) - cy; + let row_off = py * w * 4; + for px in min_x..=(max_x as usize) { + let dx = (px as f64 + 0.5) - cx; + // Inverse rotate into sprite local space (CCW in Y-up). + let lx = dx * cos_t - dy * sin_t; + let ly = dx * sin_t + dy * cos_t; + + let u = lx * inv_dw + 0.5; + let v = ly * inv_dh + 0.5; + if u <= -edge_u || u >= 1.0 + edge_u || v <= -edge_v || v >= 1.0 + edge_v { + continue; + } + + // Anti-aliased border coverage (0.5px feather at edges). + let cov_u = ((u + edge_u) / (2.0 * edge_u)) + .min((1.0 + edge_u - u) / (2.0 * edge_u)) + .clamp(0.0, 1.0); + let cov_v = ((v + edge_v) / (2.0 * edge_v)) + .min((1.0 + edge_v - v) / (2.0 * edge_v)) + .clamp(0.0, 1.0); + let cov = (cov_u * cov_v) as f32; + if cov <= 1e-4 { + continue; + } + + let sample = sample_sprite_bilinear( + &sprite.rgba, + sw_i, + sh_i, + u.clamp(0.0, 1.0), + v.clamp(0.0, 1.0), + ); + let alpha_scale = tint[3] * cov; + let pa = sample[3] * alpha_scale; + if pa <= 1e-5 { + continue; + } + let pr = sample[0] * tint[0] * alpha_scale; + let pg = sample[1] * tint[1] * alpha_scale; + let pb = sample[2] * tint[2] * alpha_scale; + + let idx = row_off + px * 4; + let inv_a = 1.0 - pa; + accum[idx] = pr + accum[idx] * inv_a; + accum[idx + 1] = pg + accum[idx + 1] * inv_a; + accum[idx + 2] = pb + accum[idx + 2] * inv_a; + accum[idx + 3] = pa + accum[idx + 3] * inv_a; + } + } +} + +#[inline] +fn sample_sprite_bilinear(rgba: &[u8], w: usize, h: usize, u: f64, v: f64) -> [f32; 4] { + let fx = (u * w as f64 - 0.5).clamp(0.0, (w - 1) as f64); + let fy = (v * h as f64 - 0.5).clamp(0.0, (h - 1) as f64); + let x0 = fx.floor() as usize; + let y0 = fy.floor() as usize; + let x1 = (x0 + 1).min(w - 1); + let y1 = (y0 + 1).min(h - 1); + let tx = (fx - x0 as f64) as f32; + let ty = (fy - y0 as f64) as f32; + + let i00 = (y0 * w + x0) * 4; + let i10 = (y0 * w + x1) * 4; + let i01 = (y1 * w + x0) * 4; + let i11 = (y1 * w + x1) * 4; + + let w00 = (1.0 - tx) * (1.0 - ty) * (1.0 / 255.0); + let w10 = tx * (1.0 - ty) * (1.0 / 255.0); + let w01 = (1.0 - tx) * ty * (1.0 / 255.0); + let w11 = tx * ty * (1.0 / 255.0); + + [ + rgba[i00] as f32 * w00 + + rgba[i10] as f32 * w10 + + rgba[i01] as f32 * w01 + + rgba[i11] as f32 * w11, + rgba[i00 + 1] as f32 * w00 + + rgba[i10 + 1] as f32 * w10 + + rgba[i01 + 1] as f32 * w01 + + rgba[i11 + 1] as f32 * w11, + rgba[i00 + 2] as f32 * w00 + + rgba[i10 + 2] as f32 * w10 + + rgba[i01 + 2] as f32 * w01 + + rgba[i11 + 2] as f32 * w11, + rgba[i00 + 3] as f32 * w00 + + rgba[i10 + 3] as f32 * w10 + + rgba[i01 + 3] as f32 * w01 + + rgba[i11 + 3] as f32 * w11, + ] +} + +/// Source-over blends one premultiplied-accumulator pixel; out-of-bounds coordinates are ignored. +#[inline] +fn blend_pixel(accum: &mut [f32], w: usize, h: usize, x: f64, y: f64, color: [f32; 4]) { + if x < 0.0 || y < 0.0 || x >= w as f64 || y >= h as f64 { + return; + } + let pa = color[3].clamp(0.0, 1.0); + if pa <= 1e-5 { + return; + } + let idx = (y as usize * w + x as usize) * 4; + let inv_a = 1.0 - pa; + accum[idx] = color[0] * pa + accum[idx] * inv_a; + accum[idx + 1] = color[1] * pa + accum[idx + 1] * inv_a; + accum[idx + 2] = color[2] * pa + accum[idx + 2] * inv_a; + accum[idx + 3] = pa + accum[idx + 3] * inv_a; +} + +/// Gaussian falloff sampled at pixel centers out to `4 sigma`, scaled by `shape(dx, dy)`. +#[allow(clippy::too_many_arguments)] +fn draw_soft_particle( + accum: &mut [f32], + w: usize, + h: usize, + cx: f64, + cy: f64, + sigma: f64, + color: [f32; 4], + shape: impl Fn(f64, f64) -> f64, +) { + let bound = 4.0 * sigma; + let min_x = ((cx - bound).floor() as isize).max(0); + let max_x = ((cx + bound).ceil() as isize).min(w as isize - 1); + let min_y = ((cy - bound).floor() as isize).max(0); + let max_y = ((cy + bound).ceil() as isize).min(h as isize - 1); + let inv_two_sigma_sq = 0.5 / (sigma * sigma); + for py in min_y..=max_y { + let dy = (py as f64 + 0.5) - cy; + for px in min_x..=max_x { + let dx = (px as f64 + 0.5) - cx; + let cov = ((-(dx * dx + dy * dy) * inv_two_sigma_sq).exp() * shape(dx, dy)) as f32; + blend_pixel(accum, w, h, px as f64, py as f64, [color[0], color[1], color[2], color[3] * cov]); + } + } +} diff --git a/crates/engine/src/particles/sim.rs b/crates/engine/src/particles/sim.rs new file mode 100644 index 0000000000000000000000000000000000000000..2d8e2202e8c1015eb9183cae5efd86ffad87bc00 --- /dev/null +++ b/crates/engine/src/particles/sim.rs @@ -0,0 +1,889 @@ +//! Per-frame particle emission, regions, forces, collisions, and simulation stepping. + +use std::collections::HashSet; + +use model::{Comp, ExprEngine, Node}; + +use super::plan::ParticlePlan; +use super::{ + MAX_PARTICLES, POINT_FORCE_SCALE, Particle, SimState, SplitMix64, TURBULENCE_SCALE, + VELOCITY_SCALE, +}; + +/// Advances the particle simulation by a single integer frame `frame`. +pub(super) fn step_simulation( + state: &mut SimState, + comp: &Comp, + plan: &ParticlePlan, + frame: i64, + expr: &ExprEngine, +) { + let t = frame as f64; + + // 1. Apply forces & kills to existing live particles, then integrate motion and age. + if !state.particles.is_empty() { + for (mod_id, scope) in &plan.modifiers { + let Some(node) = comp.nodes.get(mod_id.0) else { + continue; + }; + apply_modifier(&mut state.particles, comp, node, scope, t, expr); + } + + for p in &mut state.particles { + if !p.alive { + continue; + } + p.pos[0] += p.vel[0]; + p.pos[1] += p.vel[1]; + p.pos[2] += p.vel[2]; + p.rot_z += p.spin_z; + p.age += 1.0; + if p.age >= p.lifespan { + p.alive = false; + } + } + state.particles.retain(|p| p.alive); + } + + // 2. Emit new particles for `frame` (born with `age = 0.0` at their spawn region). + let first_new = state.particles.len(); + for &(emitter_id, emitter_hash) in &plan.emitters { + if state.particles.len() >= MAX_PARTICLES { + break; + } + let Some(node) = comp.nodes.get(emitter_id.0) else { + continue; + }; + emit_particles(state, comp, node, emitter_hash, frame, t, expr); + } + + // A newborn is damped by friction and then integrated once on its birth frame; other forces + // only start acting next frame. + for (mod_id, scope) in &plan.modifiers { + let Some(node) = comp.nodes.get(mod_id.0) else { + continue; + }; + if matches!(node.kind.as_str(), "pDrag" | "pFriction") { + apply_modifier(&mut state.particles[first_new..], comp, node, scope, t, expr); + } + } + for p in &mut state.particles[first_new..] { + for axis in 0..3 { + p.pos[axis] += p.vel[axis]; + } + p.rot_z += p.spin_z; + } +} + +fn emit_particles( + state: &mut SimState, + comp: &Comp, + node: &Node, + emitter_hash: u64, + frame: i64, + t: f64, + expr: &ExprEngine, +) { + let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; + let mut rng = SplitMix64::from_parts(seed, frame, &node.name); + + let number = comp.eval_number(node, "Number", t, 10.0, expr).max(0.0); + let number_var = comp + .eval_number(node, "NumberVariance", t, 0.0, expr) + .max(0.0); + + let rate = (number + rng.signed() * number_var).max(0.0); + let accum = state.emit_accum.entry(emitter_hash).or_insert(0.0); + *accum += rate; + let mut emit_count = accum.floor() as usize; + *accum -= emit_count as f64; + + if emit_count == 0 { + return; + } + let remaining_cap = MAX_PARTICLES.saturating_sub(state.particles.len()); + if emit_count > remaining_cap { + emit_count = remaining_cap; + } + + let lifespan_base = comp.eval_number(node, "Lifespan", t, 100.0, expr).max(1.0); + let lifespan_var = comp + .eval_number(node, "LifespanVariance", t, 0.0, expr) + .max(0.0); + let pos_var = comp + .eval_number(node, "PositionVariance", t, 0.0, expr) + .max(0.0); + + let vel_base = comp.eval_number(node, "Velocity", t, 0.0, expr); + let vel_var = comp + .eval_number(node, "VelocityVariance", t, 0.0, expr) + .max(0.0); + let angle_base = comp.eval_number(node, "Angle", t, 0.0, expr); + let angle_var = comp + .eval_number(node, "AngleVariance", t, 0.0, expr) + .max(0.0); + let angle_z_base = comp.eval_number(node, "AngleZ", t, 0.0, expr); + let angle_z_var = comp + .eval_number(node, "AngleZVariance", t, 0.0, expr) + .max(0.0); + + let rot_z_base = comp.eval_number(node, "RotationZ", t, 0.0, expr); + let rot_z_var = comp + .eval_number(node, "RotationZVariance", t, 0.0, expr) + .max(0.0); + let spin_z_base = comp.eval_number(node, "SpinZ", t, 0.0, expr); + let spin_z_var = comp + .eval_number(node, "SpinZVariance", t, 0.0, expr) + .max(0.0); + + let base_r = comp.eval_number(node, "ParticleStyle.Red", t, 1.0, expr); + let base_g = comp.eval_number(node, "ParticleStyle.Green", t, 1.0, expr); + let base_b = comp.eval_number(node, "ParticleStyle.Blue", t, 1.0, expr); + let base_a = comp.eval_number(node, "ParticleStyle.Alpha", t, 1.0, expr); + + let color_var = comp.eval_number(node, "ParticleStyle.ColorVariance", t, 0.0, expr) > 0.5; + let r_lo = (base_r + comp.eval_number(node, "ParticleStyle.RedLow", t, 0.0, expr)).clamp(0.0, 1.0); + let r_hi = (base_r + comp.eval_number(node, "ParticleStyle.RedHigh", t, 0.0, expr)).clamp(0.0, 1.0); + let g_lo = (base_g + comp.eval_number(node, "ParticleStyle.GreenLow", t, 0.0, expr)).clamp(0.0, 1.0); + let g_hi = (base_g + comp.eval_number(node, "ParticleStyle.GreenHigh", t, 0.0, expr)).clamp(0.0, 1.0); + let b_lo = (base_b + comp.eval_number(node, "ParticleStyle.BlueLow", t, 0.0, expr)).clamp(0.0, 1.0); + let b_hi = (base_b + comp.eval_number(node, "ParticleStyle.BlueHigh", t, 0.0, expr)).clamp(0.0, 1.0); + let a_lo = (base_a + comp.eval_number(node, "ParticleStyle.AlphaLow", t, 0.0, expr)).clamp(0.0, 1.0); + let a_hi = (base_a + comp.eval_number(node, "ParticleStyle.AlphaHigh", t, 0.0, expr)).clamp(0.0, 1.0); + + let size_base = comp + .eval_number(node, "ParticleStyle.Size", t, 1.0, expr) + .max(0.0); + let size_var = comp + .eval_number(node, "ParticleStyle.SizeVariance", t, 0.0, expr) + .max(0.0); + + let region = RegionSpec::from_node(comp, node, t, expr); + + for _ in 0..emit_count { + let mut pos = region.sample(&mut rng); + if pos_var > 0.0 { + pos[0] += rng.signed() * pos_var; + pos[1] += rng.signed() * pos_var; + pos[2] += rng.signed() * pos_var; + } + + let speed = (vel_base + rng.signed() * vel_var) * VELOCITY_SCALE; + let ang = (angle_base + rng.signed() * angle_var).to_radians(); + let ang_z = (angle_z_base + rng.signed() * angle_z_var).to_radians(); + let cos_z = ang_z.cos(); + let vel = [ + speed * ang.cos() * cos_z, + speed * ang.sin() * cos_z, + speed * ang_z.sin(), + ]; + + let rot_z = rot_z_base + rng.signed() * rot_z_var; + let spin_z = spin_z_base + rng.signed() * spin_z_var; + let lifespan = (lifespan_base + rng.signed() * lifespan_var).max(1.0); + let size = (size_base + rng.signed() * size_var).max(0.0); + + let color = if color_var { + [ + rng.range(r_lo, r_hi) as f32, + rng.range(g_lo, g_hi) as f32, + rng.range(b_lo, b_hi) as f32, + rng.range(a_lo, a_hi) as f32, + ] + } else { + [ + base_r.clamp(0.0, 1.0) as f32, + base_g.clamp(0.0, 1.0) as f32, + base_b.clamp(0.0, 1.0) as f32, + base_a.clamp(0.0, 1.0) as f32, + ] + }; + + state.particles.push(Particle { + emitter_hash, + pos, + vel, + rot_z, + spin_z, + age: 0.0, + lifespan, + size, + color, + alive: true, + }); + } +} + +#[derive(Clone, Copy)] +pub(super) enum RegionSpec { + Point { + center: [f64; 3], + }, + Rect { + center: [f64; 3], + width: f64, + height: f64, + }, + Sphere { + center: [f64; 3], + radius: f64, + }, + Cube { + center: [f64; 3], + width: f64, + height: f64, + depth: f64, + }, + Line { + start: [f64; 3], + end: [f64; 3], + }, + All, +} + +impl RegionSpec { + pub(super) fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self { + let region_name = node.static_str("Region").unwrap_or("SphereRgn"); + match region_name { + "RectRgn" => Self::Rect { + center: [ + comp.eval_number(node, "RectRgn.Translate.X", t, 0.0, expr), + comp.eval_number(node, "RectRgn.Translate.Y", t, 0.0, expr), + comp.eval_number(node, "RectRgn.Translate.Z", t, 0.0, expr), + ], + width: comp.eval_number(node, "RectRgn.Width", t, 0.1, expr).abs(), + height: comp.eval_number(node, "RectRgn.Height", t, 0.1, expr).abs(), + }, + "SphereRgn" => Self::Sphere { + center: [ + comp.eval_number(node, "SphereRgn.Translate.X", t, 0.0, expr), + comp.eval_number(node, "SphereRgn.Translate.Y", t, 0.0, expr), + comp.eval_number(node, "SphereRgn.Translate.Z", t, 0.0, expr), + ], + radius: comp.eval_number(node, "SphereRgn.Size", t, 0.1, expr).abs() * 0.5, + }, + "CubeRgn" => Self::Cube { + center: [ + comp.eval_number(node, "CubeRgn.Translate.X", t, 0.0, expr), + comp.eval_number(node, "CubeRgn.Translate.Y", t, 0.0, expr), + comp.eval_number(node, "CubeRgn.Translate.Z", t, 0.0, expr), + ], + width: comp.eval_number(node, "CubeRgn.Width", t, 0.1, expr).abs(), + height: comp.eval_number(node, "CubeRgn.Height", t, 0.1, expr).abs(), + depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.1, expr).abs(), + }, + "LineRgn" => { + let tx = comp.eval_number(node, "LineRgn.Translate.X", t, 0.0, expr); + let ty = comp.eval_number(node, "LineRgn.Translate.Y", t, 0.0, expr); + let tz = comp.eval_number(node, "LineRgn.Translate.Z", t, 0.0, expr); + Self::Line { + start: [ + tx + comp.eval_number(node, "LineRgn.Start.X", t, -0.5, expr), + ty + comp.eval_number(node, "LineRgn.Start.Y", t, 0.0, expr), + tz + comp.eval_number(node, "LineRgn.Start.Z", t, 0.0, expr), + ], + end: [ + tx + comp.eval_number(node, "LineRgn.End.X", t, 0.5, expr), + ty + comp.eval_number(node, "LineRgn.End.Y", t, 0.0, expr), + tz + comp.eval_number(node, "LineRgn.End.Z", t, 0.0, expr), + ], + } + } + "AllRgn" | "All" => Self::All, + _ => Self::Point { + center: [ + comp.eval_number(node, "Point.Translate.X", t, 0.0, expr), + comp.eval_number(node, "Point.Translate.Y", t, 0.0, expr), + comp.eval_number(node, "Point.Translate.Z", t, 0.0, expr), + ], + }, + } + } + + fn sample(&self, rng: &mut SplitMix64) -> [f64; 3] { + match *self { + Self::Point { center } => center, + Self::Rect { + center, + width, + height, + } => [ + center[0] + (rng.next_f64() - 0.5) * width, + center[1] + (rng.next_f64() - 0.5) * height, + center[2], + ], + Self::Sphere { center, radius } => { + let u = rng.next_f64(); + let v = rng.next_f64(); + let w = rng.next_f64(); + let theta = u * std::f64::consts::TAU; + let cos_phi = 2.0 * v - 1.0; + let sin_phi = (1.0 - cos_phi * cos_phi).max(0.0).sqrt(); + let r = radius * w.cbrt(); + [ + center[0] + r * sin_phi * theta.cos(), + center[1] + r * sin_phi * theta.sin(), + center[2] + r * cos_phi, + ] + } + Self::Cube { + center, + width, + height, + depth, + } => [ + center[0] + (rng.next_f64() - 0.5) * width, + center[1] + (rng.next_f64() - 0.5) * height, + center[2] + (rng.next_f64() - 0.5) * depth, + ], + Self::Line { start, end } => { + let u = rng.next_f64(); + [ + start[0] + (end[0] - start[0]) * u, + start[1] + (end[1] - start[1]) * u, + start[2] + (end[2] - start[2]) * u, + ] + } + Self::All => [0.0, 0.0, 0.0], + } + } + + fn contains(&self, p: [f64; 3]) -> bool { + match *self { + Self::All => true, + Self::Point { center } => { + let dx = p[0] - center[0]; + let dy = p[1] - center[1]; + let dz = p[2] - center[2]; + dx * dx + dy * dy + dz * dz <= 1e-4 + } + Self::Rect { + center, + width, + height, + } => { + (p[0] - center[0]).abs() <= width * 0.5 + && (p[1] - center[1]).abs() <= height * 0.5 + } + Self::Sphere { center, radius } => { + let dx = p[0] - center[0]; + let dy = p[1] - center[1]; + let dz = p[2] - center[2]; + dx * dx + dy * dy + dz * dz <= radius * radius + } + Self::Cube { + center, + width, + height, + depth, + } => { + (p[0] - center[0]).abs() <= width * 0.5 + && (p[1] - center[1]).abs() <= height * 0.5 + && (p[2] - center[2]).abs() <= depth * 0.5 + } + Self::Line { start, end } => { + let vx = end[0] - start[0]; + let vy = end[1] - start[1]; + let vz = end[2] - start[2]; + let len_sq = vx * vx + vy * vy + vz * vz; + let u = if len_sq > 1e-9 { + (((p[0] - start[0]) * vx + (p[1] - start[1]) * vy + (p[2] - start[2]) * vz) + / len_sq) + .clamp(0.0, 1.0) + } else { + 0.0 + }; + let cx = start[0] + vx * u; + let cy = start[1] + vy * u; + let cz = start[2] + vz * u; + let dx = p[0] - cx; + let dy = p[1] - cy; + let dz = p[2] - cz; + dx * dx + dy * dy + dz * dz <= 1e-3 + } + } + } + + /// Parses a `pBounce` region (supports `LineRgn`, `RectRgn`, `CubeRgn`, `SphereRgn`, + /// `MeshRegion`, and `Transform3DOp.Translate` fallback). + fn from_bounce_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self { + let tx = comp.eval_number(node, "Transform3DOp.Translate.X", t, 0.0, expr); + let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", t, 0.0, expr); + let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", t, 0.0, expr); + match node.static_str("Region") { + Some("RectRgn") => Self::Rect { + center: [ + comp.eval_number(node, "RectRgn.Translate.X", t, tx, expr), + comp.eval_number(node, "RectRgn.Translate.Y", t, ty, expr), + comp.eval_number(node, "RectRgn.Translate.Z", t, tz, expr), + ], + width: comp.eval_number(node, "RectRgn.Width", t, 0.1, expr).abs(), + height: comp.eval_number(node, "RectRgn.Height", t, 0.1, expr).abs(), + }, + Some("SphereRgn") => Self::Sphere { + center: [ + comp.eval_number(node, "SphereRgn.Translate.X", t, tx, expr), + comp.eval_number(node, "SphereRgn.Translate.Y", t, ty, expr), + comp.eval_number(node, "SphereRgn.Translate.Z", t, tz, expr), + ], + radius: comp.eval_number(node, "SphereRgn.Size", t, 0.5, expr).abs() * 0.5, + }, + Some("CubeRgn") => Self::Cube { + center: [ + comp.eval_number(node, "CubeRgn.Translate.X", t, tx, expr), + comp.eval_number(node, "CubeRgn.Translate.Y", t, ty, expr), + comp.eval_number(node, "CubeRgn.Translate.Z", t, tz, expr), + ], + width: comp.eval_number(node, "CubeRgn.Width", t, 0.1, expr).abs(), + height: comp.eval_number(node, "CubeRgn.Height", t, 0.1, expr).abs(), + depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.1, expr).abs(), + }, + Some("LineRgn") => { + let lx = comp.eval_number(node, "LineRgn.Translate.X", t, tx, expr); + let ly = comp.eval_number(node, "LineRgn.Translate.Y", t, ty, expr); + let lz = comp.eval_number(node, "LineRgn.Translate.Z", t, tz, expr); + Self::Line { + start: [ + lx + comp.eval_number(node, "LineRgn.Start.X", t, -0.5, expr), + ly + comp.eval_number(node, "LineRgn.Start.Y", t, 0.0, expr), + lz + comp.eval_number(node, "LineRgn.Start.Z", t, 0.0, expr), + ], + end: [ + lx + comp.eval_number(node, "LineRgn.End.X", t, 0.5, expr), + ly + comp.eval_number(node, "LineRgn.End.Y", t, 0.0, expr), + lz + comp.eval_number(node, "LineRgn.End.Z", t, 0.0, expr), + ], + } + } + Some("MeshRegion") | None => Self::Point { center: [tx, ty, tz] }, + _ => Self::from_node(comp, node, t, expr), + } + } + + /// Checks whether a particle stepping `pos -> pos + vel` collides with this bounce region. + /// Returns `(contact_pos, outward_unit_normal)` when a reflection should occur. + fn bounce_collision(&self, pos: [f64; 3], vel: [f64; 3]) -> Option<([f64; 3], [f64; 3])> { + let next = [pos[0] + vel[0], pos[1] + vel[1], pos[2] + vel[2]]; + match *self { + Self::Line { start, end } => { + let sx = end[0] - start[0]; + let sy = end[1] - start[1]; + let len_sq = sx * sx + sy * sy; + let len = len_sq.sqrt(); + if len < 1e-9 { + return None; + } + let mut n = [-sy / len, sx / len, 0.0]; + let d0 = (pos[0] - start[0]) * n[0] + (pos[1] - start[1]) * n[1]; + let d1 = (next[0] - start[0]) * n[0] + (next[1] - start[1]) * n[1]; + let crosses = (d0 * d1 <= 0.0 && (d0.abs() > 1e-12 || d1.abs() > 1e-12)) + || d1.abs() <= 1e-4; + if !crosses { + return None; + } + let alpha = if (d0 - d1).abs() > 1e-12 { + (d0 / (d0 - d1)).clamp(0.0, 1.0) + } else { + 1.0 + }; + let hit = [ + pos[0] + vel[0] * alpha, + pos[1] + vel[1] * alpha, + pos[2] + vel[2] * alpha, + ]; + let u = ((hit[0] - start[0]) * sx + (hit[1] - start[1]) * sy) / len_sq; + if !(-1e-4..=1.0 + 1e-4).contains(&u) { + return None; + } + let vn = vel[0] * n[0] + vel[1] * n[1]; + if vn > 0.0 { + n[0] = -n[0]; + n[1] = -n[1]; + } + if vel[0] * n[0] + vel[1] * n[1] >= -1e-12 { + return None; + } + Some(([hit[0] + n[0] * 1e-5, hit[1] + n[1] * 1e-5, hit[2]], n)) + } + Self::Sphere { center, radius } => { + if radius < 1e-6 { + return None; + } + let dp = [pos[0] - center[0], pos[1] - center[1], pos[2] - center[2]]; + let dn = [next[0] - center[0], next[1] - center[1], next[2] - center[2]]; + let r_pos = (dp[0] * dp[0] + dp[1] * dp[1] + dp[2] * dp[2]).sqrt(); + let r_next = (dn[0] * dn[0] + dn[1] * dn[1] + dn[2] * dn[2]).sqrt(); + if r_pos > radius && r_next > radius { + return None; + } + let ref_v = if r_pos > 1e-9 { dp } else if r_next > 1e-9 { dn } else { [0.0, 1.0, 0.0] }; + 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); + let mut n = [ref_v[0] / r_len, ref_v[1] / r_len, ref_v[2] / r_len]; + if r_pos < radius && r_next >= radius { + // Particle hitting sphere wall from inside + n = [-n[0], -n[1], -n[2]]; + let pushed = [ + center[0] - n[0] * (radius - 1e-5).max(0.0), + center[1] - n[1] * (radius - 1e-5).max(0.0), + center[2] - n[2] * (radius - 1e-5).max(0.0), + ]; + return Some((pushed, n)); + } + let pushed = [ + center[0] + n[0] * (radius + 1e-5), + center[1] + n[1] * (radius + 1e-5), + center[2] + n[2] * (radius + 1e-5), + ]; + Some((pushed, n)) + } + Self::Rect { center, width, height } => { + let hx = width * 0.5; + let hy = height * 0.5; + if hy < 1e-6 { + let line = Self::Line { + start: [center[0] - hx, center[1], center[2]], + end: [center[0] + hx, center[1], center[2]], + }; + return line.bounce_collision(pos, vel); + } + if hx < 1e-6 { + let line = Self::Line { + start: [center[0], center[1] - hy, center[2]], + end: [center[0], center[1] + hy, center[2]], + }; + return line.bounce_collision(pos, vel); + } + bounce_aabb(pos, vel, center, [hx, hy, 1e6], false) + } + Self::Cube { center, width, height, depth } => { + bounce_aabb(pos, vel, center, [width * 0.5, height * 0.5, depth * 0.5], true) + } + Self::Point { center } => { + let cy = center[1]; + let d0 = pos[1] - cy; + let d1 = next[1] - cy; + if d0 * d1 <= 0.0 || d1.abs() <= 1e-5 { + let ny = if vel[1] < 0.0 { 1.0 } else if vel[1] > 0.0 { -1.0 } else { return None }; + let alpha = if (d0 - d1).abs() > 1e-12 { + (d0 / (d0 - d1)).clamp(0.0, 1.0) + } else { + 1.0 + }; + let hit = [ + pos[0] + vel[0] * alpha, + cy + ny * 1e-5, + pos[2] + vel[2] * alpha, + ]; + return Some((hit, [0.0, ny, 0.0])); + } + None + } + Self::All => None, + } + } +} + +/// Slab-method segment-vs-AABB bounce helper (2D when `check_z == false`, 3D when `check_z == true`). +fn bounce_aabb( + pos: [f64; 3], + vel: [f64; 3], + center: [f64; 3], + half: [f64; 3], + check_z: bool, +) -> Option<([f64; 3], [f64; 3])> { + let axes = if check_z { 3 } else { 2 }; + let mut inside_pos = true; + for a in 0..axes { + if (pos[a] - center[a]).abs() > half[a] { + inside_pos = false; + break; + } + } + + if inside_pos { + // Already inside: push out through the closest face + let mut best_axis = 0usize; + let mut best_pen = f64::INFINITY; + let mut best_sign = 1.0f64; + for a in 0..axes { + let delta = pos[a] - center[a]; + let pen = half[a] - delta.abs(); + if pen < best_pen { + best_pen = pen; + best_axis = a; + best_sign = if delta >= 0.0 { 1.0 } else { -1.0 }; + } + } + let mut n = [0.0; 3]; + n[best_axis] = best_sign; + let mut pushed = pos; + pushed[best_axis] = center[best_axis] + best_sign * (half[best_axis] + 1e-5); + return Some((pushed, n)); + } + + let mut t_min = 0.0_f64; + let mut t_max = 1.0_f64; + let mut hit_axis = 0usize; + let mut hit_sign = 1.0_f64; + + for a in 0..axes { + let min_b = center[a] - half[a]; + let max_b = center[a] + half[a]; + if vel[a].abs() < 1e-12 { + if pos[a] < min_b || pos[a] > max_b { + return None; + } + } else { + let inv = 1.0 / vel[a]; + let mut t1 = (min_b - pos[a]) * inv; + let mut t2 = (max_b - pos[a]) * inv; + let mut s = -1.0; + if t1 > t2 { + std::mem::swap(&mut t1, &mut t2); + s = 1.0; + } + if t1 > t_min { + t_min = t1; + hit_axis = a; + hit_sign = s; + } + t_max = t_max.min(t2); + if t_min > t_max { + return None; + } + } + } + + let mut n = [0.0; 3]; + n[hit_axis] = hit_sign; + let hit = [ + pos[0] + vel[0] * t_min + n[0] * 1e-5, + pos[1] + vel[1] * t_min + n[1] * 1e-5, + pos[2] + vel[2] * t_min + n[2] * 1e-5, + ]; + Some((hit, n)) +} + +fn apply_modifier( + particles: &mut [Particle], + comp: &Comp, + node: &Node, + scope: &HashSet, + t: f64, + expr: &ExprEngine, +) { + match node.kind.as_str() { + "pPointForce" => { + let strength = comp.eval_number(node, "Strength", t, 0.0, expr); + if strength.abs() < 1e-12 { + return; + } + let power = comp.eval_number(node, "Power", t, 2.0, expr); + let tx = comp.eval_number(node, "Translate.X", t, 0.0, expr); + let ty = comp.eval_number(node, "Translate.Y", t, 0.0, expr); + let tz = comp.eval_number(node, "Translate.Z", t, 0.0, expr); + + for p in particles.iter_mut() { + if !p.alive || !scope.contains(&p.emitter_hash) { + continue; + } + let dx = tx - p.pos[0]; + let dy = ty - p.pos[1]; + let dz = tz - p.pos[2]; + let dist = (dx * dx + dy * dy + dz * dz).sqrt(); + if dist < 1e-7 { + continue; + } + let falloff = dist.max(0.005).powf(power); + let mag = (strength * POINT_FORCE_SCALE / falloff).clamp(-0.25, 0.25); + let inv_d = 1.0 / dist; + p.vel[0] += dx * inv_d * mag; + p.vel[1] += dy * inv_d * mag; + p.vel[2] += dz * inv_d * mag; + } + } + "pDirectionalForce" => { + let strength = comp.eval_number(node, "Strength", t, 0.1, expr); + if strength.abs() < 1e-12 { + return; + } + let dir = comp + .eval_number(node, "Direction", t, -90.0, expr) + .to_radians(); + let dir_z = comp + .eval_number(node, "DirectionZ", t, 0.0, expr) + .to_radians(); + let mag = strength * VELOCITY_SCALE * VELOCITY_SCALE; + let ax = mag * dir.cos() * dir_z.cos(); + let ay = mag * dir.sin() * dir_z.cos(); + let az = mag * dir_z.sin(); + + for p in particles.iter_mut() { + if !p.alive || !scope.contains(&p.emitter_hash) { + continue; + } + p.vel[0] += ax; + p.vel[1] += ay; + p.vel[2] += az; + } + } + "pDrag" | "pFriction" => { + let damp = if node.kind == "pFriction" { + 1.0 - comp.eval_number(node, "VelocityFriction", t, 0.05, expr) + } else { + 1.0 - comp.eval_number(node, "Drag", t, 0.05, expr) + } + .clamp(0.0, 1.0); + let spin_damp = if node.kind == "pFriction" { + 1.0 - comp.eval_number(node, "SpinFriction", t, 0.05, expr).clamp(0.0, 1.0) + } else { + 1.0 + }; + for p in particles.iter_mut() { + if !p.alive || !scope.contains(&p.emitter_hash) { + continue; + } + p.vel[0] *= damp; + p.vel[1] *= damp; + p.vel[2] *= damp; + p.spin_z *= spin_damp; + } + } + "pTurbulence" => { + let sx = comp.eval_number(node, "XStrength", t, 0.1, expr); + let sy = comp.eval_number(node, "YStrength", t, 0.1, expr); + let sz = comp.eval_number(node, "ZStrength", t, 0.0, expr); + if sx.abs() < 1e-12 && sy.abs() < 1e-12 && sz.abs() < 1e-12 { + return; + } + let density = comp.eval_number(node, "Density", t, 1.0, expr).max(0.01); + let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as u64; + let time_shift = t * 0.03; + + for p in particles.iter_mut() { + if !p.alive || !scope.contains(&p.emitter_hash) { + continue; + } + let qx = p.pos[0] * density + time_shift; + let qy = p.pos[1] * density - time_shift * 0.7; + let qz = p.pos[2] * density; + let nx = value_noise_3d(qx, qy, qz, seed); + let ny = value_noise_3d(qx + 31.7, qy + 17.3, qz + 47.1, seed ^ 0x517C_C1B7_2722_0A95); + let nz = value_noise_3d(qx - 19.4, qy + 53.9, qz - 11.2, seed ^ 0x9E37_79B9_7F4A_7C15); + p.vel[0] += nx * sx * TURBULENCE_SCALE; + p.vel[1] += ny * sy * TURBULENCE_SCALE; + p.vel[2] += nz * sz * TURBULENCE_SCALE; + } + } + "pKill" => { + let region = if node.static_str("Region").is_some() { + RegionSpec::from_node(comp, node, t, expr) + } else { + RegionSpec::All + }; + let kill_outside = matches!( + node.static_str("RegionMode"), + Some("Outside") | Some("Leaving") + ); + for p in particles.iter_mut() { + if !p.alive || !scope.contains(&p.emitter_hash) { + continue; + } + let inside = region.contains(p.pos); + if (!kill_outside && inside) || (kill_outside && !inside) { + p.alive = false; + } + } + } + "pBounce" => { + let region = RegionSpec::from_bounce_node(comp, node, t, expr); + let elasticity = comp.eval_number(node, "Elasticity", t, 1.0, expr).clamp(0.0, 2.0); + let variance = comp.eval_number(node, "Variance", t, 0.0, expr).max(0.0); + let friction = comp.eval_number(node, "Friction", t, 0.0, expr).clamp(0.0, 1.0); + let roughness = comp.eval_number(node, "Roughness", t, 0.0, expr).max(0.0); + let spin = comp.eval_number(node, "Spin", t, 0.0, expr); + let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; + let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); + + for p in particles.iter_mut() { + if !p.alive || !scope.contains(&p.emitter_hash) { + continue; + } + let Some((pushed_pos, n)) = region.bounce_collision(p.pos, p.vel) else { + continue; + }; + let vn = p.vel[0] * n[0] + p.vel[1] * n[1] + p.vel[2] * n[2]; + if vn < 0.0 { + let e = (elasticity * (1.0 + rng.signed() * variance)).clamp(0.0, 2.0); + let t_damp = (1.0 - friction).clamp(0.0, 1.0); + let vnx = vn * n[0]; + let vny = vn * n[1]; + let vnz = vn * n[2]; + let vtx = p.vel[0] - vnx; + let vty = p.vel[1] - vny; + let vtz = p.vel[2] - vnz; + p.vel[0] = vtx * t_damp - vnx * e; + p.vel[1] = vty * t_damp - vny * e; + p.vel[2] = vtz * t_damp - vnz * e; + if roughness > 1e-6 { + let scatter = roughness * 0.01 * vn.abs(); + p.vel[0] += rng.signed() * scatter; + p.vel[1] += rng.signed() * scatter; + p.vel[2] += rng.signed() * scatter; + } + if spin.abs() > 1e-9 { + p.spin_z += spin * (1.0 + 0.5 * rng.signed()); + } + p.pos = pushed_pos; + } + } + } + _ => {} + } +} + +/// Smooth deterministic 3D value noise in `[-1.0, 1.0]`. +fn value_noise_3d(x: f64, y: f64, z: f64, seed: u64) -> f64 { + let xi = x.floor() as i64; + let yi = y.floor() as i64; + let zi = z.floor() as i64; + let xf = x - xi as f64; + let yf = y - yi as f64; + let zf = z - zi as f64; + + let u = xf * xf * (3.0 - 2.0 * xf); + let v = yf * yf * (3.0 - 2.0 * yf); + let w = zf * zf * (3.0 - 2.0 * zf); + + let n000 = lattice_hash(xi, yi, zi, seed); + let n100 = lattice_hash(xi + 1, yi, zi, seed); + let n010 = lattice_hash(xi, yi + 1, zi, seed); + let n110 = lattice_hash(xi + 1, yi + 1, zi, seed); + let n001 = lattice_hash(xi, yi, zi + 1, seed); + let n101 = lattice_hash(xi + 1, yi, zi + 1, seed); + let n011 = lattice_hash(xi, yi + 1, zi + 1, seed); + let n111 = lattice_hash(xi + 1, yi + 1, zi + 1, seed); + + let nx00 = n000 + (n100 - n000) * u; + let nx10 = n010 + (n110 - n010) * u; + let nx01 = n001 + (n101 - n001) * u; + let nx11 = n011 + (n111 - n011) * u; + + let nxy0 = nx00 + (nx10 - nx00) * v; + let nxy1 = nx01 + (nx11 - nx01) * v; + + nxy0 + (nxy1 - nxy0) * w +} + +#[inline] +fn lattice_hash(x: i64, y: i64, z: i64, seed: u64) -> f64 { + let mut h = seed + ^ (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) + ^ (y as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9) + ^ (z as u64).wrapping_mul(0x94D0_49BB_1331_11EB); + h = (h ^ (h >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + h = (h ^ (h >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + h ^= h >> 31; + let unit = (h >> 11) as f64 * (1.0 / ((1u64 << 53) as f64)); + unit * 2.0 - 1.0 +} diff --git a/crates/engine/src/particles/tests.rs b/crates/engine/src/particles/tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..62e5f8d40c81208e682ca73bdae0788dbdb39e75 --- /dev/null +++ b/crates/engine/src/particles/tests.rs @@ -0,0 +1,631 @@ +use super::plan::{build_particle_plan, particle_subgraph_hash}; +use super::sim::{RegionSpec, step_simulation}; +use super::*; +use std::path::Path; +use std::time::Instant; + +fn make_white_sprite(size: u32) -> SpriteImage { + SpriteImage { + size: [size, size], + rgba: vec![255u8; (size as usize) * (size as usize) * 4], + } +} + +fn count_nonzero_alpha(buf: &[u8]) -> usize { + buf.chunks_exact(4).filter(|px| px[3] > 0).count() +} + +#[test] +fn test_particle_emitter_and_point_force_deterministic() { + let comp_src = r#" +Composition { + GlobalRange = { 0, 100 }, + RenderRange = { 0, 100 }, + Tools = { + SpriteSrc = Background { + Inputs = { + Width = Input { Value = 32, }, + Height = Input { Value = 32, }, + }, + }, + pEmitter1SizeOverLife = LUTBezier { + KeyColorSplines = { + [0] = { + [0] = { 0.5, RH = { 0.333, 0.5 }, Flags = { Linear = true } }, + [1] = { 0.25, LH = { 0.667, 0.25 }, Flags = { Linear = true } } + } + }, + }, + pEmitter1 = pEmitter { + Inputs = { + RandomSeed = Input { Value = 42, }, + Number = Input { Value = 15, }, + Lifespan = Input { Value = 60, }, + Region = Input { Value = FuID { "RectRgn" }, }, + ["RectRgn.Width"] = Input { Value = 0.6, }, + ["RectRgn.Height"] = Input { Value = 0.4, }, + Style = Input { Value = FuID { "ParticleStyleBitmap" }, }, + ["ParticleStyleBitmap.DropToolsHere"] = Input { + SourceOp = "SpriteSrc", + Source = "Output", + }, + ["ParticleStyle.Red"] = Input { Value = 1, }, + ["ParticleStyle.Green"] = Input { Value = 0, }, + ["ParticleStyle.Blue"] = Input { Value = 0, }, + ["ParticleStyle.ColorVariance"] = Input { Value = 1, }, + ["ParticleStyle.GreenHigh"] = Input { Value = 1, }, + ["ParticleStyle.Size"] = Input { Value = 0.12, }, + ["ParticleStyle.SizeOverLife"] = Input { + SourceOp = "pEmitter1SizeOverLife", + Source = "Value", + }, + ["ParticleStyle.FadeIn"] = Input { Value = 0.1, }, + ["ParticleStyle.FadeOut"] = Input { Value = 0.1, }, + }, + }, + pPointForce1 = pPointForce { + Inputs = { + Strength = Input { Value = -3.0, }, + Power = Input { Value = 0.5, }, + ["Translate.X"] = Input { Value = 0.0, }, + ["Translate.Y"] = Input { Value = 0.0, }, + Input = Input { + SourceOp = "pEmitter1", + Source = "Output", + }, + }, + }, + pRender1 = pRender { + Inputs = { + Input = Input { + SourceOp = "pPointForce1", + Source = "Output", + }, + }, + }, + }, +} +"#; + + let comp = Comp::from_fusion_str(comp_src).expect("parse synthetic particle comp"); + let render_id = comp.node_by_name["pRender1"]; + let emitter_id = comp.node_by_name["pEmitter1"]; + let sprite_id = comp.node_by_name["SpriteSrc"]; + let force_id = comp.node_by_name["pPointForce1"]; + + // Verify bitmap source discovery. + let sources = collect_bitmap_sources(&comp, render_id); + assert_eq!(sources, vec![(emitter_id, sprite_id)]); + + let expr = ExprEngine::new(); + let mut sprites = HashMap::new(); + sprites.insert(emitter_id, make_white_sprite(16)); + + let dims = [160, 90]; + + // 1. Determinism: two fresh caches produce bit-identical buffers. + let mut cache_a = ParticleCache::default(); + let mut cache_b = ParticleCache::default(); + let img_a = render_particles_2d(&mut cache_a, &comp, render_id, 25.0, dims, &expr, &sprites); + let img_b = render_particles_2d(&mut cache_b, &comp, render_id, 25.0, dims, &expr, &sprites); + assert_eq!(img_a, img_b, "particle render must be bit-identical across runs"); + assert!( + count_nonzero_alpha(&img_a) > 50, + "expected non-empty rendered particles" + ); + + // 2. Force affects particle trajectories: bypassing pPointForce1 changes output. + let mut comp_no_force = comp.clone(); + comp_no_force.nodes[force_id.0].bypassed = true; + comp_no_force.revision += 1; + let mut cache_no_force = ParticleCache::default(); + let img_no_force = render_particles_2d( + &mut cache_no_force, + &comp_no_force, + render_id, + 25.0, + dims, + &expr, + &sprites, + ); + assert_ne!( + img_a, img_no_force, + "pPointForce must visibly change particle trajectories" + ); + + // 3. Cache consistency & sequential speedup: stepping 25 -> 26 matches fresh 0 -> 26. + let t_seq_start = Instant::now(); + let img_26_cached = + render_particles_2d(&mut cache_a, &comp, render_id, 26.0, dims, &expr, &sprites); + let seq_elapsed = t_seq_start.elapsed(); + + let mut fresh_cache = ParticleCache::default(); + let t_fresh_start = Instant::now(); + let img_26_fresh = render_particles_2d( + &mut fresh_cache, + &comp, + render_id, + 26.0, + dims, + &expr, + &sprites, + ); + let fresh_elapsed = t_fresh_start.elapsed(); + assert_eq!( + img_26_cached, img_26_fresh, + "cached sequential step must match fresh simulation" + ); + assert!( + seq_elapsed <= fresh_elapsed * 2 + std::time::Duration::from_millis(5), + "cached sequential step should be fast (seq={seq_elapsed:?}, fresh={fresh_elapsed:?})" + ); + + cache_a.clear(); + assert!(cache_a.entries.is_empty()); +} + +#[test] +fn test_01_intro_particles_if_present() { + let path = Path::new("/Volumes/Project/trees/fusion/01_intro.comp"); + if !path.exists() { + return; + } + + let comp = Comp::from_fusion_file(path).expect("parse 01_intro.comp"); + let render_id = comp.node_by_name["pRender1"]; + let emitter_id = comp.node_by_name["pEmitter1"]; + let bc4_id = comp.node_by_name["BrightnessContrast4"]; + + let sources = collect_bitmap_sources(&comp, render_id); + assert_eq!( + sources, + vec![(emitter_id, bc4_id)], + "01_intro.comp pEmitter1 bitmap source should be BrightnessContrast4" + ); + + let expr = ExprEngine::new(); + let mut sprites = HashMap::new(); + sprites.insert(emitter_id, make_white_sprite(32)); + + // In 01_intro.comp, TimeStretcher1 evaluates pRender1 at SourceTime = time / 25 + // (so comp f600 -> t=24, comp f1600 -> t=64). + let ts_node = &comp.nodes[comp.node_by_name["TimeStretcher1"].0]; + let t_f600 = comp.eval_number(ts_node, "SourceTime", 600.0, 24.0, &expr); + let t_f1600 = comp.eval_number(ts_node, "SourceTime", 1600.0, 64.0, &expr); + + let dims = [320, 180]; + let mut cache = ParticleCache::default(); + let start = Instant::now(); + let buf_600 = render_particles_2d(&mut cache, &comp, render_id, t_f600, dims, &expr, &sprites); + let buf_1600 = + render_particles_2d(&mut cache, &comp, render_id, t_f1600, dims, &expr, &sprites); + let elapsed = start.elapsed(); + + let nz_600 = count_nonzero_alpha(&buf_600); + assert!( + nz_600 > 0, + "expected non-zero alpha pixels at f600 (SourceTime={t_f600})" + ); + assert_eq!( + buf_1600.len(), + dims[0] as usize * dims[1] as usize * 4, + "f1600 SourceTime={t_f1600}" + ); + assert!( + elapsed.as_secs_f64() < 2.0, + "01_intro particle render should be fast, took {elapsed:?}" + ); +} + +#[test] +fn test_pbounce_reverses_velocity_and_applies_friction() { + let comp_src = r#" +Composition { + GlobalRange = { 0, 20 }, + RenderRange = { 0, 20 }, + Tools = { + pEmitter1 = pEmitter { + Inputs = { + Number = Input { Value = 1, }, + Lifespan = Input { Value = 50, }, + Velocity = Input { Value = 1.0, }, + Angle = Input { Value = -60, }, + ["SphereRgn.Size"] = Input { Value = 0, }, + ["SphereRgn.Translate.Y"] = Input { Value = 0.2, }, + }, + }, + pBounce1 = pBounce { + Inputs = { + Input = Input { SourceOp = "pEmitter1", Source = "Output", }, + Elasticity = Input { Value = 0.8, }, + Friction = Input { Value = 0.25, }, + Spin = Input { Value = 3.0, }, + Region = Input { Value = FuID { "CubeRgn" }, }, + ["CubeRgn.Translate.Y"] = Input { Value = -0.25, }, + ["CubeRgn.Width"] = Input { Value = 2.0, }, + ["CubeRgn.Height"] = Input { Value = 0.5, }, + ["CubeRgn.Depth"] = Input { Value = 2.0, }, + }, + }, + pRender1 = pRender { + Inputs = { + Input = Input { SourceOp = "pBounce1", Source = "Output", }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse pBounce comp"); + let render_id = comp.node_by_name["pRender1"]; + let plan = build_particle_plan(&comp, render_id); + let expr = ExprEngine::new(); + let mut state = SimState::default(); + + // Step until the first emitted particle (born at f=0 at y=0.2, vy≈-0.0866, vx=0.05) + // crosses the floor at y=0.0 around frame 3. + for f in 0..=4 { + step_simulation(&mut state, &comp, &plan, f, &expr); + } + let first = state.particles.first().expect("particle emitted"); + let init_vx = 0.1 * (-60.0_f64).to_radians().cos(); + let init_vy = 0.1 * (-60.0_f64).to_radians().sin(); + assert!( + first.vel[1] > 0.0, + "pBounce should reverse downward Y velocity (got vy={})", + first.vel[1] + ); + assert!( + (first.vel[1] - (-init_vy * 0.8)).abs() < 1e-4, + "expected reflected vy={}, got {}", + -init_vy * 0.8, + first.vel[1] + ); + assert!( + (first.vel[0] - init_vx * 0.75).abs() < 1e-4, + "expected friction-damped vx={}, got {}", + init_vx * 0.75, + first.vel[0] + ); + assert!(first.spin_z.abs() > 0.5, "expected Spin impulse on bounce"); + assert!(first.pos[1] > 0.0, "bounced particle should be above floor y=0"); +} + +/// Single-particle comp: `Number` is a spline that is 1 at frame 0 and 0 afterwards. +fn single_particle_comp(emitter_inputs: &str, forces: &str, last_node: &str) -> Comp { + let src = format!( + r#" +Composition {{ + GlobalRange = {{ 0, 100 }}, + RenderRange = {{ 0, 100 }}, + Tools = {{ + EN = BezierSpline {{ + KeyFrames = {{ + [0] = {{ 1, Flags = {{ Linear = true }} }}, + [1] = {{ 0, Flags = {{ Linear = true }} }} + }} + }}, + pEmitter1 = pEmitter {{ + Inputs = {{ + Number = Input {{ SourceOp = "EN", Source = "Value", }}, + Lifespan = Input {{ Value = 100, }}, + ["SphereRgn.Size"] = Input {{ Value = 0, }}, + {emitter_inputs} + }}, + }}, + {forces} + pRender1 = pRender {{ + Inputs = {{ + Input = Input {{ SourceOp = "{last_node}", Source = "Output", }}, + }}, + }}, + }}, +}} +"# + ); + Comp::from_fusion_str(&src).expect("parse single-particle comp") +} + +fn render(comp: &Comp, time: f64, dims: [u32; 2], sprites: &HashMap) -> Vec { + let mut cache = ParticleCache::default(); + render_particles_2d(&mut cache, comp, comp.node_by_name["pRender1"], time, dims, &ExprEngine::new(), sprites) +} + +/// `(x, y, alpha)` of every pixel with non-zero alpha. +fn lit(buf: &[u8], width: usize) -> Vec<(usize, usize, u8)> { + buf.chunks_exact(4) + .enumerate() + .filter(|(_, px)| px[3] > 0) + .map(|(i, px)| (i % width, i / width, px[3])) + .collect() +} + +fn alpha_mass(buf: &[u8]) -> f64 { + buf.chunks_exact(4).map(|px| px[3] as f64 / 255.0).sum() +} + +#[test] +fn point_style_is_one_pixel_regardless_of_size() { + let comp = single_particle_comp(r#"["ParticleStyle.Size"] = Input { Value = 5, },"#, "", "pEmitter1"); + let buf = render(&comp, 0.0, [200, 100], &HashMap::new()); + assert_eq!(lit(&buf, 200), vec![(100, 50, 255)]); +} + +#[test] +fn blob_is_gaussian_with_sigma_per_size_unit() { + let comp = single_particle_comp( + r#"Style = Input { Value = FuID { "ParticleStyleBlob" }, }, ["ParticleStyle.Size"] = Input { Value = 2, },"#, + "", + "pEmitter1", + ); + // Fusion 21.1: Size 2 blob has alpha mass ~276 (= 2*pi*(2*3.316)^2). + let mass = alpha_mass(&render(&comp, 0.0, [256, 256], &HashMap::new())); + assert!((mass - 276.0).abs() < 8.0, "blob mass {mass}"); +} + +#[test] +fn newborn_moves_once_at_tenth_width_velocity() { + let comp = single_particle_comp( + r#"VelocityControls = Input { Value = 1, }, Velocity = Input { Value = 1, }, Angle = Input { Value = 0, },"#, + "", + "pEmitter1", + ); + let at = |t: f64| lit(&render(&comp, t, [200, 100], &HashMap::new()), 200)[0].0; + assert_eq!(at(0.0), 120); + assert_eq!(at(2.0), 160); +} + +#[test] +fn directional_force_accelerates_down_by_strength_over_one_hundred() { + let comp = single_particle_comp( + "", + r#"pDirectionalForce1 = pDirectionalForce { + Inputs = { + Strength = Input { Value = 1, }, + Input = Input { SourceOp = "pEmitter1", Source = "Output", }, + }, + },"#, + "pDirectionalForce1", + ); + // y(f) = 0.01 * f(f+1)/2 widths below the spawn point. + let buf = render(&comp, 4.0, [1000, 1000], &HashMap::new()); + assert_eq!(lit(&buf, 1000), vec![(500, 600, 255)]); +} + +#[test] +fn particle_lives_while_age_is_below_lifespan() { + let comp = single_particle_comp(r#"Lifespan = Input { Value = 3, },"#, "", "pEmitter1"); + let count = |t: f64| lit(&render(&comp, t, [64, 64], &HashMap::new()), 64).len(); + assert_eq!((count(0.0), count(2.0), count(3.0)), (1, 1, 0)); +} + +#[test] +fn fade_out_starts_at_fade_out_fraction_of_life() { + let comp = single_particle_comp( + r#"Lifespan = Input { Value = 20, }, Style = Input { Value = FuID { "ParticleStyleBlob" }, }, + ["ParticleStyle.Size"] = Input { Value = 2, }, ["ParticleStyle.FadeOut"] = Input { Value = 0.5, },"#, + "", + "pEmitter1", + ); + let mass = |t: f64| alpha_mass(&render(&comp, t, [256, 256], &HashMap::new())); + assert!((mass(15.0) / mass(10.0) - 0.5).abs() < 0.02); +} + +#[test] +fn bitmap_width_is_size_times_sprite_pixels() { + let comp = single_particle_comp( + r#"Style = Input { Value = FuID { "ParticleStyleBitmap" }, }, ["ParticleStyle.Size"] = Input { Value = 2, },"#, + "", + "pEmitter1", + ); + let mut sprites = HashMap::new(); + sprites.insert(comp.node_by_name["pEmitter1"], make_white_sprite(4)); + let pixels = lit(&render(&comp, 0.0, [200, 100], &sprites), 200); + let (min_x, max_x) = pixels.iter().fold((usize::MAX, 0), |(lo, hi), &(x, _, _)| (lo.min(x), hi.max(x))); + assert!((8..=9).contains(&(max_x - min_x + 1)), "bitmap width {}", max_x - min_x + 1); +} + +#[test] +fn default_region_is_sphere_of_diameter_one_tenth_width() { + let comp = Comp::from_fusion_str("Composition { Tools = { pEmitter1 = pEmitter { Inputs = { }, }, }, }") + .expect("parse bare emitter"); + let node = &comp.nodes[comp.node_by_name["pEmitter1"].0]; + match RegionSpec::from_node(&comp, node, 0.0, &ExprEngine::new()) { + RegionSpec::Sphere { radius, .. } => assert!((radius - 0.05).abs() < 1e-12), + _ => panic!("default region must be a sphere"), + } +} + +#[test] +fn depth_scales_screen_position_by_camera_distance() { + let comp = single_particle_comp( + r#"["SphereRgn.Translate.X"] = Input { Value = 0.2, }, ["SphereRgn.Translate.Z"] = Input { Value = 0.9722222222222222, },"#, + "", + "pEmitter1", + ); + // z equal to the camera distance halves the projected offset: x = (0.2 * 0.5 + 0.5) * 1000. + let buf = render(&comp, 0.0, [1000, 1000], &HashMap::new()); + assert_eq!(lit(&buf, 1000), vec![(600, 500, 255)]); +} + +#[test] +fn particle_cache_advances_past_600_incrementally_and_scrubs_with_snapshots() { + let comp_src = r#" +Composition { + GlobalRange = { 0, 800 }, + RenderRange = { 0, 800 }, + Tools = { + pEmitter1 = pEmitter { + Inputs = { + RandomSeed = Input { Value = 7, }, + Number = Input { Value = 2, }, + Lifespan = Input { Value = 25, }, + Velocity = Input { Value = 0.2, }, + VelocityVariance = Input { Value = 0.1, }, + AngleVariance = Input { Value = 180, }, + }, + }, + pRender1 = pRender { + Inputs = { + Input = Input { SourceOp = "pEmitter1", Source = "Output", }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse particle comp"); + let render_id = comp.node_by_name["pRender1"]; + let expr = ExprEngine::new(); + let sprites = HashMap::new(); + let dims = [64, 64]; + + let mut cache = ParticleCache::default(); + let mut last_img = Vec::new(); + for f in 580..=625 { + last_img = render_particles_2d(&mut cache, &comp, render_id, f as f64, dims, &expr, &sprites); + } + + let key = ( + "pRender1".to_owned(), + particle_subgraph_hash(&comp, render_id, 0), + ); + let cached = cache.entries.get(&key).expect("cached entry"); + assert_eq!(cached.base_start, 0); + assert_eq!(cached.current_frame, 625); + assert!(cached.snapshots.contains_key(&600), "expected snapshot at frame 600"); + + // Scrubbing back to frame 605 restores snapshot 600 and matches direct render at 605. + let scrub_605 = render_particles_2d(&mut cache, &comp, render_id, 605.0, dims, &expr, &sprites); + let mut fresh_cache = ParticleCache::default(); + let fresh_605 = render_particles_2d(&mut fresh_cache, &comp, render_id, 605.0, dims, &expr, &sprites); + assert_eq!(scrub_605, fresh_605, "scrubbed frame 605 must match fresh simulation"); + + let mut fresh_625_cache = ParticleCache::default(); + let fresh_625 = render_particles_2d(&mut fresh_625_cache, &comp, render_id, 625.0, dims, &expr, &sprites); + assert_eq!(last_img, fresh_625, "incremental advance past 600 must match fresh simulation"); +} + +#[test] +fn particle_cache_ignores_unrelated_comp_edits_and_node_id_shifts() { + let with_unrelated = r#" +Composition { + GlobalRange = { 0, 100 }, + RenderRange = { 0, 100 }, + Tools = { + UnrelatedBg = Background { + Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, }, + }, + pEmitter1 = pEmitter { + Inputs = { + RandomSeed = Input { Value = 19, }, + Number = Input { Value = 8, }, + Lifespan = Input { Value = 40, }, + Velocity = Input { Value = 0.5, }, + VelocityVariance = Input { Value = 0.25, }, + AngleVariance = Input { Value = 180, }, + }, + }, + pRender1 = pRender { + Inputs = { + Input = Input { SourceOp = "pEmitter1", Source = "Output", }, + }, + }, + }, +} +"#; + let without_unrelated = r#" +Composition { + GlobalRange = { 0, 100 }, + RenderRange = { 0, 100 }, + Tools = { + pEmitter1 = pEmitter { + Inputs = { + RandomSeed = Input { Value = 19, }, + Number = Input { Value = 8, }, + Lifespan = Input { Value = 40, }, + Velocity = Input { Value = 0.5, }, + VelocityVariance = Input { Value = 0.25, }, + AngleVariance = Input { Value = 180, }, + }, + }, + pRender1 = pRender { + Inputs = { + Input = Input { SourceOp = "pEmitter1", Source = "Output", }, + }, + }, + }, +} +"#; + let mut comp_a = Comp::from_fusion_str(with_unrelated).expect("parse comp_a"); + let comp_b = Comp::from_fusion_str(without_unrelated).expect("parse comp_b"); + let ra = comp_a.node_by_name["pRender1"]; + let rb = comp_b.node_by_name["pRender1"]; + assert_ne!(ra, rb, "deleting UnrelatedBg should shift NodeIds"); + + let expr = ExprEngine::new(); + let sprites = HashMap::new(); + let dims = [64, 64]; + + let mut cache_a = ParticleCache::default(); + let img_a_20 = render_particles_2d(&mut cache_a, &comp_a, ra, 20.0, dims, &expr, &sprites); + + // Bumping comp.revision (simulating unrelated node edit) reuses cached simulation. + comp_a.revision += 99; + let hash_before = particle_subgraph_hash(&comp_a, ra, 0); + let hash_after_del = particle_subgraph_hash(&comp_b, rb, 0); + assert_eq!(hash_before, hash_after_del, "subgraph hash must ignore NodeId shifts and unrelated nodes"); + + let mut cache_b = ParticleCache::default(); + let img_b_20 = render_particles_2d(&mut cache_b, &comp_b, rb, 20.0, dims, &expr, &sprites); + assert_eq!(img_a_20, img_b_20, "deleting an unrelated node must not re-randomize particles"); + + // Stepping comp_b using cache_a (which has old NodeIds!) must still match fresh comp_b at frame 21. + let img_a_to_b_21 = render_particles_2d(&mut cache_a, &comp_b, rb, 21.0, dims, &expr, &sprites); + let mut fresh_b = ParticleCache::default(); + let img_b_21 = render_particles_2d(&mut fresh_b, &comp_b, rb, 21.0, dims, &expr, &sprites); + assert_eq!(img_a_to_b_21, img_b_21); +} + +#[test] +fn cyclic_expression_modifier_does_not_stack_overflow() { + let comp_src = r#" +Composition { + GlobalRange = { 0, 20 }, + RenderRange = { 0, 20 }, + Tools = ordered() { + Expr1 = Expression { + Inputs = { + n1 = Input { SourceOp = "Expr1", Source = "NumberResult", }, + NumberExpression = Input { Value = "n1 + 4", }, + }, + }, + pEmitter1 = pEmitter { + Inputs = { + RandomSeed = Input { Value = 7, }, + Number = Input { SourceOp = "Expr1", Source = "NumberResult", }, + Lifespan = Input { Value = 15, }, + Velocity = Input { Value = 0.2, }, + }, + }, + pRender1 = pRender { + Inputs = { + Input = Input { SourceOp = "pEmitter1", Source = "Output", }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse cyclic Expr1 comp"); + assert!(comp.expression_modifiers.contains_key("Expr1")); + let pr = comp.find_node("pRender1").expect("find pRender1"); + let expr = ExprEngine::new(); + let sprites = HashMap::new(); + let mut cache = ParticleCache::default(); + + // Both subgraph hashing and particle evaluation must terminate cleanly without overflowing. + let h1 = particle_subgraph_hash(&comp, pr, 0); + let h2 = particle_subgraph_hash(&comp, pr, 0); + assert_eq!(h1, h2); + + let img = render_particles_2d(&mut cache, &comp, pr, 5.0, [64, 64], &expr, &sprites); + assert_eq!(img.len(), 64 * 64 * 4); +}