diff --git a/crates/engine/src/particles.rs b/crates/engine/src/particles.rs index ac9439538174e079a510d2ee0d4a8fdc9d4e88b9..be514beb8557d0c294624ccc137a3605ca0921fb 100644 --- a/crates/engine/src/particles.rs +++ b/crates/engine/src/particles.rs @@ -4,8 +4,6 @@ //! `pDrag` / `pFriction`, `pKill`, `pBounce`, `pMerge`, and `pRender` (2D mode). mod plan; -mod raster; -mod sim; #[cfg(test)] mod tests; @@ -55,7 +53,7 @@ pub struct SpriteImage { pub rgba: Vec, } -/// Persistent frame-to-frame cache for deterministic particle simulations. +/// Persistent frame-to-frame cache for deterministic particle simulations and scratch raster buffers. /// /// Keyed by `(render_node_name, subgraph_hash)`. Advancing sequentially `f -> f+1` /// only steps 1 frame even past `MAX_SIM_WINDOW`, while periodic snapshots every @@ -63,11 +61,17 @@ pub struct SpriteImage { #[derive(Default)] pub struct ParticleCache { entries: HashMap<(String, u64), CachedSim>, + /// Reusable premultiplied RGBA32F accumulation canvas (kept zeroed between calls). + scratch_accum: Vec, + /// Reusable draw-command list to avoid per-frame allocations. + scratch_cmds: Vec, } impl ParticleCache { pub fn clear(&mut self) { self.entries.clear(); + self.scratch_accum.clear(); + self.scratch_cmds.clear(); } } @@ -216,6 +220,12 @@ pub fn render_particles_2d( return out; } + let pre_gen = comp + .eval_number(rnode, "PreGenerateFrames", time, 0.0, expr) + .round() + .clamp(0.0, MAX_SIM_WINDOW as f64) as i64; + let sim_origin = base_start - pre_gen; + let subgraph_hash = particle_subgraph_hash(comp, render_node, base_start); let key = (rnode.name.clone(), subgraph_hash); // Evict stale subgraph hashes for this render node while keeping other pRender entries. @@ -223,10 +233,10 @@ pub fn render_particles_2d( .entries .retain(|(name, h), _| name != &key.0 || *h == subgraph_hash); - let cold_sim_start = |target: i64| base_start.max(target - MAX_SIM_WINDOW); + let cold_sim_start = |target: i64| sim_origin.max(target - MAX_SIM_WINDOW); let need_cold_init = match cache.entries.get_mut(&key) { - Some(cached) if cached.base_start == base_start => { + Some(cached) if cached.base_start == sim_origin => { if target_frame == cached.current_frame { false } else if target_frame > cached.current_frame { @@ -259,7 +269,7 @@ pub fn render_particles_2d( if need_cold_init { let sim_start = cold_sim_start(target_frame); let mut sim = CachedSim { - base_start, + base_start: sim_origin, current_frame: target_frame, state: SimState::default(), snapshots: BTreeMap::new(), @@ -271,21 +281,2159 @@ pub fn render_particles_2d( cache.entries.insert(key.clone(), sim); } - let Some(cached) = cache.entries.get(&key) else { - return out; - }; - let render_width = comp.eval_number(rnode, "Width", time, dims[0] as f64, expr).max(1.0); - rasterize_particles( - &mut out, - dims, - dims[0] as f64 / render_width, - comp, - &plan.emitter_nodes, - &cached.state.particles, - time, - expr, - sprites, - ); + let particles_len = cache.entries.get(&key).map_or(0, |c| c.state.particles.len()); + if particles_len == 0 { + return out; + } + + // Temporarily take `entries` out so `scratch_accum` and `scratch_cmds` can be borrowed mutably. + let entries = std::mem::take(&mut cache.entries); + if let Some(cached) = entries.get(&key) { + rasterize_particles( + &mut out, + &mut cache.scratch_accum, + &mut cache.scratch_cmds, + dims, + dims[0] as f64 / render_width, + comp, + &plan.emitter_nodes, + &cached.state.particles, + time, + expr, + sprites, + ); + } + cache.entries = entries; out } + +/// Per-frame particle emission, regions, forces, collisions, and simulation stepping. +mod sim { + 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 red_lo_off = comp.eval_number(node, "ParticleStyle.RedLow", t, 0.0, expr); + let red_hi_off = comp.eval_number(node, "ParticleStyle.RedHigh", t, 0.0, expr); + let green_lo_off = comp.eval_number(node, "ParticleStyle.GreenLow", t, 0.0, expr); + let green_hi_off = comp.eval_number(node, "ParticleStyle.GreenHigh", t, 0.0, expr); + let blue_lo_off = comp.eval_number(node, "ParticleStyle.BlueLow", t, 0.0, expr); + let blue_hi_off = comp.eval_number(node, "ParticleStyle.BlueHigh", t, 0.0, expr); + let alpha_lo_off = comp.eval_number(node, "ParticleStyle.AlphaLow", t, 0.0, expr); + let alpha_hi_off = comp.eval_number(node, "ParticleStyle.AlphaHigh", t, 0.0, expr); + + let color_var = comp.eval_number(node, "ParticleStyle.ColorVariance", t, 0.0, expr) > 0.5 + || red_lo_off.abs() > 1e-9 + || red_hi_off.abs() > 1e-9 + || green_lo_off.abs() > 1e-9 + || green_hi_off.abs() > 1e-9 + || blue_lo_off.abs() > 1e-9 + || blue_hi_off.abs() > 1e-9 + || alpha_lo_off.abs() > 1e-9 + || alpha_hi_off.abs() > 1e-9; + + let r_lo = (base_r + red_lo_off).clamp(0.0, 1.0); + let r_hi = (base_r + red_hi_off).clamp(0.0, 1.0); + let g_lo = (base_g + green_lo_off).clamp(0.0, 1.0); + let g_hi = (base_g + green_hi_off).clamp(0.0, 1.0); + let b_lo = (base_b + blue_lo_off).clamp(0.0, 1.0); + let b_hi = (base_b + blue_hi_off).clamp(0.0, 1.0); + let a_lo = (base_a + alpha_lo_off).clamp(0.0, 1.0); + let a_hi = (base_a + alpha_hi_off).clamp(0.0, 1.0); + + // Fusion's ParticleStyle.Size defaults to 0.1 across all styles. + let size_base = comp + .eval_number(node, "ParticleStyle.Size", t, 0.1, 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); + state.particles.reserve(emit_count); + + 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 { + 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 { + 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.1, 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 vel_fric = if node.kind == "pFriction" || !node.inputs.contains_key("Drag") { + comp.eval_number(node, "VelocityFriction", t, 0.05, expr) + } else { + comp.eval_number(node, "Drag", t, 0.05, expr) + }; + let damp = (1.0 - vel_fric).clamp(0.0, 1.0); + let spin_damp = if node.kind == "pFriction" || node.inputs.contains_key("SpinFriction") { + (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.1, expr); + if sx.abs() < 1e-12 && sy.abs() < 1e-12 && sz.abs() < 1e-12 { + return; + } + let density = comp.eval_number(node, "Density", t, 10.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 + } +} + +/// Optimized 2D particle rasterization (points, separable Gaussian blobs, NGons, and bitmap sprites). +mod raster { + use std::collections::HashMap; + + use model::{Comp, ExprEngine, Gradient, Node, NodeId}; + + use super::{ + BLOB_SIGMA_PER_SIZE, CAMERA_DISTANCE, Particle, ParticleStyleKind, SpriteImage, + }; + + const INV_255: f32 = 1.0 / 255.0; + + pub(super) struct DrawCmd { + min_x: usize, + max_x: usize, + min_y: usize, + max_y: usize, + color: [f32; 4], + shape: DrawShape, + } + + enum DrawShape { + Point, + Blob { + cx: f64, + cy: f64, + inv_two_sigma_sq: f64, + }, + NGon { + cx: f64, + cy: f64, + inv_two_sigma_sq: f64, + inv_half_period: f64, + spike_period: f64, + phase: f64, + sharpness: f64, + }, + Bitmap { + emitter_idx: usize, + cx: f64, + cy: f64, + draw_w: f64, + draw_h: f64, + rot_z_deg: f64, + }, + } + + struct EmitterRenderProps<'a> { + emitter_hash: u64, + style: ParticleStyleKind, + /// Owned 1x1 tiny-background sprite, if applicable. + tiny_sprite: Option<([f64; 2], SpriteImage)>, + /// External sprite reference + nominal dimensions when not a tiny background. + ext_sprite: Option<(&'a SpriteImage, [f64; 2])>, + ngon_sides: f64, + size_over_life: Option<&'a model::BezierSpline>, + fade_in: f64, + fade_out: f64, + color_over_life: Option, + } + + impl<'a> EmitterRenderProps<'a> { + #[inline] + fn resolved_sprite(&self) -> Option<(&SpriteImage, [f64; 2])> { + match &self.tiny_sprite { + Some((nominal, sprite)) => Some((sprite, *nominal)), + None => self.ext_sprite, + } + } + } + + fn collect_emitter_render_props<'a>( + comp: &'a Comp, + emitter_nodes: &HashMap, + time: f64, + expr: &ExprEngine, + sprites: &'a HashMap, + ) -> Vec> { + let mut list = Vec::with_capacity(emitter_nodes.len()); + for (&emitter_hash, &emitter_id) in emitter_nodes { + 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 + }; + let tiny_sprite = tiny_background_sprite(comp, node, time, expr); + let ext_sprite = if tiny_sprite.is_none() && style == ParticleStyleKind::Bitmap { + sprites + .get(&emitter_id) + .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) + }) + .map(|s| (s, [s.size[0] as f64, s.size[1] as f64])) + } else { + None + }; + list.push(EmitterRenderProps { + emitter_hash, + style, + tiny_sprite, + ext_sprite, + 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, + }); + } + list + } + + /// Solid sprite for a `Background` tool narrower than 16 px. + 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 })) + } + + /// Clamps a floating-point `[lo, hi]` interval to `[0, limit - 1]`, returning `None` if empty. + #[inline] + fn clip_bounds(lo: f64, hi: f64, limit: usize) -> Option<(usize, usize)> { + if limit == 0 || !lo.is_finite() || !hi.is_finite() { + return None; + } + let max_i = (limit - 1) as isize; + let a = lo.floor() as isize; + let b = hi.ceil() as isize; + if b < 0 || a > max_i { + return None; + } + let min_u = a.max(0) as usize; + let max_u = b.min(max_i) as usize; + (min_u <= max_u).then_some((min_u, max_u)) + } + + #[allow(clippy::too_many_arguments)] + pub(super) fn rasterize_particles( + out: &mut [u8], + scratch_accum: &mut Vec, + scratch_cmds: &mut Vec, + 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 w = dims[0] as usize; + let h = dims[1] as usize; + if w == 0 || h == 0 { + return; + } + let w_f = w as f64; + let h_f = h as f64; + + let props_list = collect_emitter_render_props(comp, emitter_nodes, time, expr, sprites); + if props_list.is_empty() { + return; + } + + scratch_cmds.clear(); + if scratch_cmds.capacity() < particles.len() { + scratch_cmds.reserve(particles.len() - scratch_cmds.capacity()); + } + + let mut dirty_y0 = h; + let mut dirty_y1 = 0usize; + let mut last_hash = u64::MAX; + let mut last_idx = usize::MAX; + + for p in particles { + if !p.alive { + continue; + } + let props_idx = if p.emitter_hash == last_hash && last_idx < props_list.len() { + last_idx + } else { + let Some(idx) = props_list.iter().position(|pr| pr.emitter_hash == p.emitter_hash) + else { + continue; + }; + last_hash = p.emitter_hash; + last_idx = idx; + idx + }; + let props = &props_list[props_idx]; + + let life_frac = (p.age / p.lifespan.max(1.0)).clamp(0.0, 1.0); + 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; + } + + 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 { + if let Some((_, nominal)) = props.resolved_sprite() { + let draw_w = size_world * nominal[0] * px_scale; + let draw_h = size_world * nominal[1] * px_scale; + if draw_w < 0.5 || draw_h < 0.5 { + continue; + } + let hw = draw_w * 0.5; + let hh = draw_h * 0.5; + let (rx, ry) = if p.rot_z.abs() <= 1e-6 { + (hw + 1.0, hh + 1.0) + } else { + let theta = p.rot_z.to_radians(); + let ca_t = theta.cos().abs(); + let sa_t = theta.sin().abs(); + (hw * ca_t + hh * sa_t + 1.0, hw * sa_t + hh * ca_t + 1.0) + }; + let Some((min_x, max_x)) = clip_bounds(cx - rx, cx + rx, w) else { + continue; + }; + let Some((min_y, max_y)) = clip_bounds(cy - ry, cy + ry, h) else { + continue; + }; + dirty_y0 = dirty_y0.min(min_y); + dirty_y1 = dirty_y1.max(max_y + 1); + scratch_cmds.push(DrawCmd { + min_x, + max_x, + min_y, + max_y, + color: [cr, cg, cb, ca], + shape: DrawShape::Bitmap { + emitter_idx: props_idx, + cx, + cy, + draw_w, + draw_h, + rot_z_deg: p.rot_z, + }, + }); + continue; + } + } + + match props.style { + ParticleStyleKind::Point => { + let ix = cx.floor() as isize; + let iy = cy.floor() as isize; + if ix < 0 || iy < 0 || ix >= w as isize || iy >= h as isize { + continue; + } + let ux = ix as usize; + let uy = iy as usize; + dirty_y0 = dirty_y0.min(uy); + dirty_y1 = dirty_y1.max(uy + 1); + scratch_cmds.push(DrawCmd { + min_x: ux, + max_x: ux, + min_y: uy, + max_y: uy, + color: [cr, cg, cb, ca], + shape: DrawShape::Point, + }); + } + ParticleStyleKind::Blob | ParticleStyleKind::Bitmap => { + let sigma = BLOB_SIGMA_PER_SIZE * size_world * px_scale; + if sigma <= 1e-6 { + continue; + } + let inv_two_sigma_sq = 0.5 / (sigma * sigma); + let bound = (4.0 * sigma).min((((ca as f64) * 1.0e5).ln().max(0.0) / inv_two_sigma_sq).sqrt()); + let Some((min_x, max_x)) = clip_bounds(cx - bound, cx + bound, w) else { + continue; + }; + let Some((min_y, max_y)) = clip_bounds(cy - bound, cy + bound, h) else { + continue; + }; + dirty_y0 = dirty_y0.min(min_y); + dirty_y1 = dirty_y1.max(max_y + 1); + scratch_cmds.push(DrawCmd { + min_x, + max_x, + min_y, + max_y, + color: [cr, cg, cb, ca], + shape: DrawShape::Blob { + cx, + cy, + inv_two_sigma_sq, + }, + }); + } + ParticleStyleKind::NGon => { + let sigma = BLOB_SIGMA_PER_SIZE * size_world * px_scale; + if sigma <= 1e-6 { + continue; + } + let inv_two_sigma_sq = 0.5 / (sigma * sigma); + let bound = (4.0 * sigma).min((((ca as f64) * 1.0e5).ln().max(0.0) / inv_two_sigma_sq).sqrt()); + let Some((min_x, max_x)) = clip_bounds(cx - bound, cx + bound, w) else { + continue; + }; + let Some((min_y, max_y)) = clip_bounds(cy - bound, cy + bound, h) else { + continue; + }; + 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(); + let sharpness = 4.5 * (3.0 / sides).powf(2.8); + dirty_y0 = dirty_y0.min(min_y); + dirty_y1 = dirty_y1.max(max_y + 1); + scratch_cmds.push(DrawCmd { + min_x, + max_x, + min_y, + max_y, + color: [cr, cg, cb, ca], + shape: DrawShape::NGon { + cx, + cy, + inv_two_sigma_sq, + inv_half_period: 2.0 / spike_period, + spike_period, + phase, + sharpness, + }, + }); + } + ParticleStyleKind::Brush => {} + } + } + + if scratch_cmds.is_empty() || dirty_y0 >= dirty_y1 { + return; + } + + let needed_floats = w * h * 4; + if scratch_accum.len() < needed_floats { + scratch_accum.resize(needed_floats, 0.0); + } + + rasterize_bands( + out, + &mut scratch_accum[..needed_floats], + w, + dirty_y0, + dirty_y1, + scratch_cmds, + &props_list, + ); + } + + fn rasterize_bands( + out: &mut [u8], + accum: &mut [f32], + w: usize, + dirty_y0: usize, + dirty_y1: usize, + cmds: &[DrawCmd], + props_list: &[EmitterRenderProps<'_>], + ) { + #[cfg(not(target_arch = "wasm32"))] + { + let dirty_rows = dirty_y1 - dirty_y0; + let dirty_pixels = dirty_rows * w; + if dirty_pixels >= 120_000 && dirty_rows >= 32 && cmds.len() >= 16 { + let workers = std::thread::available_parallelism() + .map(|n| n.get()) + .unwrap_or(1) + .min(8) + .min(dirty_rows / 16); + if workers > 1 { + let stride = w * 4; + let rows_per_band = dirty_rows.div_ceil(workers); + let accum_dirty = &mut accum[dirty_y0 * stride..dirty_y1 * stride]; + let out_dirty = &mut out[dirty_y0 * stride..dirty_y1 * stride]; + std::thread::scope(|scope| { + let mut a_rest = accum_dirty; + let mut o_rest = out_dirty; + let mut band_y0 = dirty_y0; + while band_y0 < dirty_y1 { + let take_rows = rows_per_band.min(dirty_y1 - band_y0); + let take_elems = take_rows * stride; + let (a_band, a_next) = a_rest.split_at_mut(take_elems); + let (o_band, o_next) = o_rest.split_at_mut(take_elems); + a_rest = a_next; + o_rest = o_next; + let band_y1 = band_y0 + take_rows; + scope.spawn(move || { + rasterize_single_band( + o_band, + a_band, + w, + band_y0, + band_y1, + cmds, + props_list, + ); + }); + band_y0 = band_y1; + } + }); + return; + } + } + } + + let stride = w * 4; + let start = dirty_y0 * stride; + let end = dirty_y1 * stride; + rasterize_single_band( + &mut out[start..end], + &mut accum[start..end], + w, + dirty_y0, + dirty_y1, + cmds, + props_list, + ); + } + + fn rasterize_single_band( + out_band: &mut [u8], + accum_band: &mut [f32], + w: usize, + band_y0: usize, + band_y1: usize, + cmds: &[DrawCmd], + props_list: &[EmitterRenderProps<'_>], + ) { + let stride = w * 4; + let mut wx_heap: Vec = Vec::new(); + let mut wx_stack = [0.0f32; 64]; + + for cmd in cmds { + if cmd.max_y < band_y0 || cmd.min_y >= band_y1 { + continue; + } + let y_lo = cmd.min_y.max(band_y0); + let y_hi = cmd.max_y.min(band_y1 - 1); + let x_lo = cmd.min_x; + let x_hi = cmd.max_x; + + match cmd.shape { + DrawShape::Point => { + let pa = cmd.color[3]; + let off = (y_lo - band_y0) * stride + x_lo * 4; + let dst = &mut accum_band[off..off + 4]; + if pa >= 1.0 - 1e-5 { + dst[0] = cmd.color[0]; + dst[1] = cmd.color[1]; + dst[2] = cmd.color[2]; + dst[3] = 1.0; + } else { + let inv_a = 1.0 - pa; + dst[0] = cmd.color[0] * pa + dst[0] * inv_a; + dst[1] = cmd.color[1] * pa + dst[1] * inv_a; + dst[2] = cmd.color[2] * pa + dst[2] * inv_a; + dst[3] = pa + dst[3] * inv_a; + } + } + DrawShape::Blob { + cx, + cy, + inv_two_sigma_sq, + } => { + let span_x = x_hi - x_lo + 1; + let wx: &mut [f32] = if span_x <= wx_stack.len() { + &mut wx_stack[..span_x] + } else { + wx_heap.resize(span_x, 0.0); + &mut wx_heap[..span_x] + }; + for (i, w_slot) in wx.iter_mut().enumerate() { + let dx = (x_lo + i) as f64 + 0.5 - cx; + *w_slot = (-(dx * dx) * inv_two_sigma_sq).exp() as f32; + } + + let sa = cmd.color[3]; + let sr = cmd.color[0] * sa; + let sg = cmd.color[1] * sa; + let sb = cmd.color[2] * sa; + let row_x_start = x_lo * 4; + let row_x_end = (x_hi + 1) * 4; + + for py in y_lo..=y_hi { + let dy = py as f64 + 0.5 - cy; + let wy = (-(dy * dy) * inv_two_sigma_sq).exp() as f32; + let row_a = sa * wy; + if row_a <= 1e-5 { + continue; + } + let row_r = sr * wy; + let row_g = sg * wy; + let row_b = sb * wy; + let row_off = (py - band_y0) * stride; + let row_pixels = &mut accum_band[row_off + row_x_start..row_off + row_x_end]; + for (dst, &gx) in row_pixels.chunks_exact_mut(4).zip(wx.iter()) { + let pa = row_a * gx; + if pa <= 1e-5 { + continue; + } + let inv_a = 1.0 - pa; + dst[0] = row_r * gx + dst[0] * inv_a; + dst[1] = row_g * gx + dst[1] * inv_a; + dst[2] = row_b * gx + dst[2] * inv_a; + dst[3] = pa + dst[3] * inv_a; + } + } + } + DrawShape::NGon { + cx, + cy, + inv_two_sigma_sq, + inv_half_period, + spike_period, + phase, + sharpness, + } => { + let span_x = x_hi - x_lo + 1; + let wx: &mut [f32] = if span_x <= wx_stack.len() { + &mut wx_stack[..span_x] + } else { + wx_heap.resize(span_x, 0.0); + &mut wx_heap[..span_x] + }; + for (i, w_slot) in wx.iter_mut().enumerate() { + let dx = (x_lo + i) as f64 + 0.5 - cx; + *w_slot = (-(dx * dx) * inv_two_sigma_sq).exp() as f32; + } + + let sa = cmd.color[3]; + let cr = cmd.color[0]; + let cg = cmd.color[1]; + let cb = cmd.color[2]; + let row_x_start = x_lo * 4; + let row_x_end = (x_hi + 1) * 4; + + for py in y_lo..=y_hi { + let dy = py as f64 + 0.5 - cy; + let wy = (-(dy * dy) * inv_two_sigma_sq).exp() as f32; + let row_a = sa * wy; + if row_a <= 1e-5 { + continue; + } + let row_off = (py - band_y0) * stride; + let row_pixels = &mut accum_band[row_off + row_x_start..row_off + row_x_end]; + for (i, dst) in row_pixels.chunks_exact_mut(4).enumerate() { + let env_a = row_a * wx[i]; + if env_a <= 1e-5 { + continue; + } + let dx = (x_lo + i) as f64 + 0.5 - cx; + let angle = (-dy).atan2(dx) - phase; + let off = angle.rem_euclid(spike_period); + let to_spike = off.min(spike_period - off); + let shape_w = (1.0 - to_spike * inv_half_period).powf(sharpness) as f32; + let pa = env_a * shape_w; + if pa <= 1e-5 { + continue; + } + let inv_a = 1.0 - pa; + dst[0] = cr * pa + dst[0] * inv_a; + dst[1] = cg * pa + dst[1] * inv_a; + dst[2] = cb * pa + dst[2] * inv_a; + dst[3] = pa + dst[3] * inv_a; + } + } + } + DrawShape::Bitmap { + emitter_idx, + cx, + cy, + draw_w, + draw_h, + rot_z_deg, + } => { + let Some((sprite, _)) = props_list[emitter_idx].resolved_sprite() else { + continue; + }; + draw_bitmap_band( + accum_band, + stride, + band_y0, + y_lo, + y_hi, + x_lo, + x_hi, + cx, + cy, + draw_w, + draw_h, + rot_z_deg, + cmd.color, + sprite, + ); + } + } + } + + // Pack premultiplied f32 -> u8 and simultaneously reset `accum_band` to 0.0 + // while the cache lines are hot so `scratch_accum` stays zeroed for the next frame. + for (dst, src) in out_band.iter_mut().zip(accum_band.iter_mut()) { + let v = *src; + *src = 0.0; + *dst = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + } + } + + #[allow(clippy::too_many_arguments)] + #[inline] + fn draw_bitmap_band( + accum_band: &mut [f32], + stride: usize, + band_y0: usize, + y_lo: usize, + y_hi: usize, + x_lo: usize, + x_hi: usize, + cx: f64, + cy: f64, + draw_w: f64, + draw_h: f64, + rot_z_deg: f64, + tint: [f32; 4], + sprite: &SpriteImage, + ) { + 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 inv_2edge_u = 1.0 / (2.0 * edge_u); + let inv_2edge_v = 1.0 / (2.0 * edge_v); + let sw_i = sprite.size[0] as usize; + let sh_i = sprite.size[1] as usize; + let row_x_start = x_lo * 4; + let row_x_end = (x_hi + 1) * 4; + + // Fast path: axis-aligned (unrotated) sprite. + if rot_z_deg.abs() <= 1e-6 { + let u0 = (x_lo as f64 + 0.5 - cx) * inv_dw + 0.5; + if sw_i == 1 && sh_i == 1 { + let s0 = sprite.rgba[0] as f32 * INV_255 * tint[0] * tint[3]; + let s1 = sprite.rgba[1] as f32 * INV_255 * tint[1] * tint[3]; + let s2 = sprite.rgba[2] as f32 * INV_255 * tint[2] * tint[3]; + let s3 = sprite.rgba[3] as f32 * INV_255 * tint[3]; + if s3 <= 1e-5 { + return; + } + for py in y_lo..=y_hi { + let v = (py as f64 + 0.5 - cy) * inv_dh + 0.5; + if v <= -edge_v || v >= 1.0 + edge_v { + continue; + } + let cov_v = ((v + edge_v) * inv_2edge_v) + .min((1.0 + edge_v - v) * inv_2edge_v) + .clamp(0.0, 1.0); + if cov_v <= 1e-4 { + continue; + } + let cov_vf = cov_v as f32; + let row_off = (py - band_y0) * stride; + let row_pixels = &mut accum_band[row_off + row_x_start..row_off + row_x_end]; + let mut u = u0; + for dst in row_pixels.chunks_exact_mut(4) { + if u > -edge_u && u < 1.0 + edge_u { + let cov_u = ((u + edge_u) * inv_2edge_u) + .min((1.0 + edge_u - u) * inv_2edge_u) + .clamp(0.0, 1.0); + let cov = cov_u as f32 * cov_vf; + if cov > 1e-4 { + let pa = s3 * cov; + if pa > 1e-5 { + let inv_a = 1.0 - pa; + dst[0] = s0 * cov + dst[0] * inv_a; + dst[1] = s1 * cov + dst[1] * inv_a; + dst[2] = s2 * cov + dst[2] * inv_a; + dst[3] = pa + dst[3] * inv_a; + } + } + } + u += inv_dw; + } + } + return; + } + + let sw_f = sw_i as f64; + let sh_f = sh_i as f64; + let sw_max = (sw_i - 1) as f64; + let sh_max = (sh_i - 1) as f64; + let tr = tint[0] * INV_255; + let tg = tint[1] * INV_255; + let tb = tint[2] * INV_255; + let ta = tint[3] * INV_255; + + for py in y_lo..=y_hi { + let v = (py as f64 + 0.5 - cy) * inv_dh + 0.5; + if v <= -edge_v || v >= 1.0 + edge_v { + continue; + } + let cov_v = ((v + edge_v) * inv_2edge_v) + .min((1.0 + edge_v - v) * inv_2edge_v) + .clamp(0.0, 1.0); + if cov_v <= 1e-4 { + continue; + } + let fy = (v.clamp(0.0, 1.0) * sh_f - 0.5).clamp(0.0, sh_max); + let y0 = fy.floor() as usize; + let y1 = (y0 + 1).min(sh_i - 1); + let ty = (fy - y0 as f64) as f32; + let one_minus_ty = 1.0 - ty; + let row0 = y0 * sw_i; + let row1 = y1 * sw_i; + let cov_vf = cov_v as f32; + + let row_off = (py - band_y0) * stride; + let row_pixels = &mut accum_band[row_off + row_x_start..row_off + row_x_end]; + let mut u = u0; + for dst in row_pixels.chunks_exact_mut(4) { + if u > -edge_u && u < 1.0 + edge_u { + let cov_u = ((u + edge_u) * inv_2edge_u) + .min((1.0 + edge_u - u) * inv_2edge_u) + .clamp(0.0, 1.0); + let cov = cov_u as f32 * cov_vf; + if cov > 1e-4 { + let fx = (u.clamp(0.0, 1.0) * sw_f - 0.5).clamp(0.0, sw_max); + let x0 = fx.floor() as usize; + let x1 = (x0 + 1).min(sw_i - 1); + let tx = (fx - x0 as f64) as f32; + let omt = 1.0 - tx; + + let w00 = omt * one_minus_ty; + let w10 = tx * one_minus_ty; + let w01 = omt * ty; + let w11 = tx * ty; + + let i00 = (row0 + x0) * 4; + let i10 = (row0 + x1) * 4; + let i01 = (row1 + x0) * 4; + let i11 = (row1 + x1) * 4; + + let s_a = sprite.rgba[i00 + 3] as f32 * w00 + + sprite.rgba[i10 + 3] as f32 * w10 + + sprite.rgba[i01 + 3] as f32 * w01 + + sprite.rgba[i11 + 3] as f32 * w11; + let pa = s_a * ta * cov; + if pa > 1e-5 { + let s_r = sprite.rgba[i00] as f32 * w00 + + sprite.rgba[i10] as f32 * w10 + + sprite.rgba[i01] as f32 * w01 + + sprite.rgba[i11] as f32 * w11; + let s_g = sprite.rgba[i00 + 1] as f32 * w00 + + sprite.rgba[i10 + 1] as f32 * w10 + + sprite.rgba[i01 + 1] as f32 * w01 + + sprite.rgba[i11 + 1] as f32 * w11; + let s_b = sprite.rgba[i00 + 2] as f32 * w00 + + sprite.rgba[i10 + 2] as f32 * w10 + + sprite.rgba[i01 + 2] as f32 * w01 + + sprite.rgba[i11 + 2] as f32 * w11; + let inv_a = 1.0 - pa; + dst[0] = s_r * (tr * cov * tint[3]) + dst[0] * inv_a; + dst[1] = s_g * (tg * cov * tint[3]) + dst[1] * inv_a; + dst[2] = s_b * (tb * cov * tint[3]) + dst[2] * inv_a; + dst[3] = pa + dst[3] * inv_a; + } + } + } + u += inv_dw; + } + } + return; + } + + // General rotated bitmap path with incremental scanline UV stepping. + let theta = rot_z_deg.to_radians(); + let cos_t = theta.cos(); + let sin_t = theta.sin(); + let du_dx = cos_t * inv_dw; + let dv_dx = sin_t * inv_dh; + let dx0 = (x_lo as f64 + 0.5) - cx; + let sw_f = sw_i as f64; + let sh_f = sh_i as f64; + let sw_max = (sw_i - 1) as f64; + let sh_max = (sh_i - 1) as f64; + let tr = tint[0] * tint[3] * INV_255; + let tg = tint[1] * tint[3] * INV_255; + let tb = tint[2] * tint[3] * INV_255; + let ta = tint[3] * INV_255; + + for py in y_lo..=y_hi { + let dy = (py as f64 + 0.5) - cy; + let mut u = (dx0 * cos_t - dy * sin_t) * inv_dw + 0.5; + let mut v = (dx0 * sin_t + dy * cos_t) * inv_dh + 0.5; + let row_off = (py - band_y0) * stride; + let row_pixels = &mut accum_band[row_off + row_x_start..row_off + row_x_end]; + + for dst in row_pixels.chunks_exact_mut(4) { + if u > -edge_u && u < 1.0 + edge_u && v > -edge_v && v < 1.0 + edge_v { + let cov_u = ((u + edge_u) * inv_2edge_u) + .min((1.0 + edge_u - u) * inv_2edge_u) + .clamp(0.0, 1.0); + let cov_v = ((v + edge_v) * inv_2edge_v) + .min((1.0 + edge_v - v) * inv_2edge_v) + .clamp(0.0, 1.0); + let cov = (cov_u * cov_v) as f32; + if cov > 1e-4 { + let fx = (u.clamp(0.0, 1.0) * sw_f - 0.5).clamp(0.0, sw_max); + let fy = (v.clamp(0.0, 1.0) * sh_f - 0.5).clamp(0.0, sh_max); + let x0 = fx.floor() as usize; + let y0 = fy.floor() as usize; + let x1 = (x0 + 1).min(sw_i - 1); + let y1 = (y0 + 1).min(sh_i - 1); + let tx = (fx - x0 as f64) as f32; + let ty = (fy - y0 as f64) as f32; + + let w00 = (1.0 - tx) * (1.0 - ty); + let w10 = tx * (1.0 - ty); + let w01 = (1.0 - tx) * ty; + let w11 = tx * ty; + + let i00 = (y0 * sw_i + x0) * 4; + let i10 = (y0 * sw_i + x1) * 4; + let i01 = (y1 * sw_i + x0) * 4; + let i11 = (y1 * sw_i + x1) * 4; + + let s_a = sprite.rgba[i00 + 3] as f32 * w00 + + sprite.rgba[i10 + 3] as f32 * w10 + + sprite.rgba[i01 + 3] as f32 * w01 + + sprite.rgba[i11 + 3] as f32 * w11; + let pa = s_a * ta * cov; + if pa > 1e-5 { + let s_r = sprite.rgba[i00] as f32 * w00 + + sprite.rgba[i10] as f32 * w10 + + sprite.rgba[i01] as f32 * w01 + + sprite.rgba[i11] as f32 * w11; + let s_g = sprite.rgba[i00 + 1] as f32 * w00 + + sprite.rgba[i10 + 1] as f32 * w10 + + sprite.rgba[i01 + 1] as f32 * w01 + + sprite.rgba[i11 + 1] as f32 * w11; + let s_b = sprite.rgba[i00 + 2] as f32 * w00 + + sprite.rgba[i10 + 2] as f32 * w10 + + sprite.rgba[i01 + 2] as f32 * w01 + + sprite.rgba[i11 + 2] as f32 * w11; + let inv_a = 1.0 - pa; + dst[0] = s_r * (tr * cov) + dst[0] * inv_a; + dst[1] = s_g * (tg * cov) + dst[1] * inv_a; + dst[2] = s_b * (tb * cov) + dst[2] * inv_a; + dst[3] = pa + dst[3] * inv_a; + } + } + } + u += du_dx; + v += dv_dx; + } + } + } +} + +#[cfg(test)] +mod w26c_tests { + use super::*; + + #[test] + fn default_size_is_one_tenth_and_pregenerate_frames_emits_preroll() { + let comp_src = r#" +Composition { + GlobalRange = { 0, 20 }, + RenderRange = { 0, 20 }, + Tools = { + E = pEmitter { + Inputs = { + RandomSeed = Input { Value = 42, }, + Style = Input { Value = FuID { "ParticleStyleBlob" }, }, + Number = Input { Value = 10, }, + Velocity = Input { Value = 0.05, }, + }, + }, + R_default = pRender { + Inputs = { + Width = Input { Value = 256, }, + Height = Input { Value = 256, }, + Input = Input { SourceOp = "E", Source = "Output", }, + }, + }, + R_pre = pRender { + Inputs = { + Width = Input { Value = 256, }, + Height = Input { Value = 256, }, + PreGenerateFrames = Input { Value = 20, }, + Input = Input { SourceOp = "E", Source = "Output", }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); + let expr = ExprEngine::new(); + let sprites = HashMap::new(); + + let mut cache = ParticleCache::default(); + let img_default = render_particles_2d( + &mut cache, + &comp, + comp.node_by_name["R_default"], + 0.0, + [256, 256], + &expr, + &sprites, + ); + // Default Size = 0.1 produces compact ~0.33px-sigma blobs (~7 alpha mass for 10 blobs). + let alpha_mass_default: f64 = img_default + .chunks_exact(4) + .map(|px| px[3] as f64 / 255.0) + .sum(); + assert!( + alpha_mass_default > 3.0 && alpha_mass_default < 15.0, + "expected Size=0.1 alpha mass in (3, 15), got {alpha_mass_default}" + ); + assert!( + cache.scratch_accum.iter().all(|&x| x == 0.0), + "scratch_accum must be zeroed after render" + ); + + let img_pre = render_particles_2d( + &mut cache, + &comp, + comp.node_by_name["R_pre"], + 0.0, + [256, 256], + &expr, + &sprites, + ); + let alpha_mass_pre: f64 = img_pre + .chunks_exact(4) + .map(|px| px[3] as f64 / 255.0) + .sum(); + assert!( + alpha_mass_pre > alpha_mass_default * 8.0, + "PreGenerateFrames=20 should accumulate ~21x particles (default={alpha_mass_default}, pre={alpha_mass_pre})" + ); + assert!( + cache.scratch_accum.iter().all(|&x| x == 0.0), + "scratch_accum must stay zeroed after PreGenerateFrames render" + ); + } + + #[test] + fn scratch_buffer_reuse_and_parallel_band_determinism() { + let comp_src = r#" +Composition { + GlobalRange = { 0, 50 }, + RenderRange = { 0, 50 }, + Tools = { + E_blob = pEmitter { + Inputs = { + RandomSeed = Input { Value = 11, }, + Style = Input { Value = FuID { "ParticleStyleBlob" }, }, + Number = Input { Value = 40, }, + Velocity = Input { Value = 0.4, }, + AngleVariance = Input { Value = 180, }, + ["ParticleStyle.Size"] = Input { Value = 0.6, }, + ["ParticleStyle.RedHigh"] = Input { Value = -0.5, }, + }, + }, + E_ngon = pEmitter { + Inputs = { + RandomSeed = Input { Value = 22, }, + Style = Input { Value = FuID { "ParticleStyleNGon" }, }, + Number = Input { Value = 25, }, + Velocity = Input { Value = 0.3, }, + AngleVariance = Input { Value = 180, }, + RotationZVariance = Input { Value = 180, }, + ["ParticleStyle.Size"] = Input { Value = 0.5, }, + }, + }, + E_bmp = pEmitter { + Inputs = { + RandomSeed = Input { Value = 33, }, + Style = Input { Value = FuID { "ParticleStyleBitmap" }, }, + Number = Input { Value = 25, }, + Velocity = Input { Value = 0.35, }, + AngleVariance = Input { Value = 180, }, + RotationZVariance = Input { Value = 45, }, + ["ParticleStyle.Size"] = Input { Value = 1.2, }, + }, + }, + M1 = pMerge { + Inputs = { + Input1 = Input { SourceOp = "E_blob", Source = "Output", }, + Input2 = Input { SourceOp = "E_ngon", Source = "Output", }, + }, + }, + M2 = pMerge { + Inputs = { + Input1 = Input { SourceOp = "M1", Source = "Output", }, + Input2 = Input { SourceOp = "E_bmp", Source = "Output", }, + }, + }, + R = pRender { + Inputs = { + Width = Input { Value = 640, }, + Height = Input { Value = 360, }, + Input = Input { SourceOp = "M2", Source = "Output", }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse multi-style comp"); + let render_id = comp.node_by_name["R"]; + let bmp_id = comp.node_by_name["E_bmp"]; + let expr = ExprEngine::new(); + let mut sprites = HashMap::new(); + let mut sprite_rgba = vec![0u8; 8 * 8 * 4]; + for (i, px) in sprite_rgba.chunks_exact_mut(4).enumerate() { + px[0] = ((i * 37) % 256) as u8; + px[1] = 200; + px[2] = 120; + px[3] = 220; + } + sprites.insert(bmp_id, SpriteImage { size: [8, 8], rgba: sprite_rgba }); + + // Render at 640x360 (triggers parallel band rasterizer) twice with separate caches: must be bit-identical. + let mut cache_a = ParticleCache::default(); + let mut cache_b = ParticleCache::default(); + let buf_a = render_particles_2d(&mut cache_a, &comp, render_id, 15.0, [640, 360], &expr, &sprites); + let buf_b = render_particles_2d(&mut cache_b, &comp, render_id, 15.0, [640, 360], &expr, &sprites); + assert_eq!(buf_a, buf_b, "multi-style 640x360 render must be bit-for-bit deterministic"); + assert!(buf_a.chunks_exact(4).any(|px| px[3] > 0)); + assert!(cache_a.scratch_accum.iter().all(|&x| x == 0.0)); + + // Reusing the same cache at smaller and larger resolutions must not leak stale scratch pixels. + let small = render_particles_2d(&mut cache_a, &comp, render_id, 16.0, [120, 80], &expr, &sprites); + let mut fresh_small = ParticleCache::default(); + let small_ref = render_particles_2d(&mut fresh_small, &comp, render_id, 16.0, [120, 80], &expr, &sprites); + assert_eq!(small, small_ref); + + let large = render_particles_2d(&mut cache_a, &comp, render_id, 17.0, [720, 405], &expr, &sprites); + let mut fresh_large = ParticleCache::default(); + let large_ref = render_particles_2d(&mut fresh_large, &comp, render_id, 17.0, [720, 405], &expr, &sprites); + assert_eq!(large, large_ref); + assert!(cache_a.scratch_accum.iter().all(|&x| x == 0.0)); + } + + #[test] + fn fast_path_unrotated_and_1x1_bitmap_match_bounds_and_clipping() { + let comp_src = r#" +Composition { + GlobalRange = { 0, 10 }, + RenderRange = { 0, 10 }, + Tools = { + EN = BezierSpline { + KeyFrames = { + [0] = { 1, Flags = { Linear = true } }, + [1] = { 0, Flags = { Linear = true } } + } + }, + BG1x1 = Background { + Inputs = { + Width = Input { Value = 4, }, + Height = Input { Value = 4, }, + TopLeftRed = Input { Value = 0.5, }, + TopLeftGreen = Input { Value = 0.25, }, + TopLeftBlue = Input { Value = 1.0, }, + TopLeftAlpha = Input { Value = 0.8, }, + }, + }, + E = pEmitter { + Inputs = { + Number = Input { SourceOp = "EN", Source = "Value", }, + Lifespan = Input { Value = 10, }, + ["SphereRgn.Size"] = Input { Value = 0, }, + ["SphereRgn.Translate.X"] = Input { Value = -0.49, }, + Style = Input { Value = FuID { "ParticleStyleBitmap" }, }, + ["ParticleStyleBitmap.DropToolsHere"] = Input { SourceOp = "BG1x1", Source = "Output", }, + ["ParticleStyle.Size"] = Input { Value = 2, }, + }, + }, + R = pRender { + Inputs = { + Width = Input { Value = 100, }, + Height = Input { Value = 100, }, + Input = Input { SourceOp = "E", Source = "Output", }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse 1x1 bitmap comp"); + let mut cache = ParticleCache::default(); + let img = render_particles_2d( + &mut cache, + &comp, + comp.node_by_name["R"], + 0.0, + [100, 100], + &ExprEngine::new(), + &HashMap::new(), + ); + // Particle centered at x = 1 px with 8 px width must clip cleanly at left edge (x=0) without wrapping. + let lit_cols: Vec = (0..100) + .filter(|&x| img[(50 * 100 + x) * 4 + 3] > 0) + .collect(); + assert_eq!(lit_cols, vec![0, 1, 2, 3, 4]); + assert_eq!(img[(50 * 100 + 99) * 4 + 3], 0, "must not wrap to right edge"); + } +}