authoravatarclover caruso<git@paperclover.net>2026-11-30 18:34:12-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 19:14:04-08:00
log70d3b873a073d0d88aeca1b79cee99b90743ea4a
treeb38d70cf87f97ac17bb236bf9aacead50958217a
parent2f0d9d6103df077ffa2f3d6d1919e43c86055a69
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Calibrate pEmitter and pRender particle system parity against Fusion 21.1 (#39)

Black-box probes on Fusion 21.1 (probes/w5_39) pin down the particle model: - Point style is a single pixel; Blob is exp(-r^2/2s^2) with s = 3.316 * Size px; NGon is a spiked star; Bitmap width is Size * sprite pixels (not render width). - Velocity moves 0.1 widths/frame, force acceleration is 0.01 * Strength (directional) and 1e-4 * Strength / d^Power (point); newborns integrate once on their birth frame. - pFriction multiplies velocity by 1 - friction (default 0.05), including on birth. - FadeOut is the life fraction at which the fade-out begins. - Default region is SphereRgn of diameter 0.1; Cube/Rect default extents 0.1. - Particles project through a 35mm/36mm film-back camera, so z scales screen position. - Sub-16px Background sprites use their nominal size and flat color. Assisted-by: claude-sonnet-5.5

1 files changed, 352 insertions(+), 117 deletions(-)

crates/engine/src/particles.rs+352-117
...@@ -14,13 +14,18 @@ const MAX_PARTICLES: usize = 20_000;...@@ -14,13 +14,18 @@ const MAX_PARTICLES: usize = 20_000;
14/// Maximum lookback frames from `target_frame` when `sim_start` is far earlier.14/// Maximum lookback frames from `target_frame` when `sim_start` is far earlier.
15const MAX_SIM_WINDOW: i64 = 600;15const MAX_SIM_WINDOW: i64 = 600;
1616
17/// Fusion internal acceleration scale for `pPointForce`.17/// Particle integration step: `Velocity` moves `0.1` render widths per frame and
18/// Matches Fusion Studio's particle-space scaling where `Strength = -2..-4`18/// forces accelerate by `0.1^2` per unit of `Strength`.
19/// gently disperses particles over ~85-100 frames in `[-0.5, +0.5]` space.19const VELOCITY_SCALE: f64 = 0.1;
20const POINT_FORCE_SCALE: f64 = 2.0e-5;
2120
22/// Fusion internal acceleration scale for `pDirectionalForce`.21/// `pPointForce` acceleration is `Strength * 1e-4 / distance^Power` (render widths per frame^2).
23const DIRECTIONAL_FORCE_SCALE: f64 = 2.0e-3;22const POINT_FORCE_SCALE: f64 = 1.0e-4;
23
24/// Default render camera distance in render widths (35mm lens on a 36mm film back).
25const CAMERA_DISTANCE: f64 = 35.0 / 36.0;
26
27/// Blob particle falloff is `exp(-r^2 / (2 sigma^2))` with `sigma = BLOB_SIGMA_PER_SIZE * Size` pixels.
28const BLOB_SIGMA_PER_SIZE: f64 = 3.316;
2429
25/// Fusion internal acceleration scale for `pTurbulence`.30/// Fusion internal acceleration scale for `pTurbulence`.
26const TURBULENCE_SCALE: f64 = 2.0e-3;31const TURBULENCE_SCALE: f64 = 2.0e-3;
...@@ -79,7 +84,9 @@ struct Particle {...@@ -79,7 +84,9 @@ struct Particle {
79enum ParticleStyleKind {84enum ParticleStyleKind {
80 Point,85 Point,
81 Blob,86 Blob,
87 NGon,
82 Bitmap,88 Bitmap,
89 Brush,
83}90}
8491
85/// Deterministic SplitMix64 PRNG.92/// Deterministic SplitMix64 PRNG.
...@@ -389,9 +396,11 @@ pub fn render_particles_2d(...@@ -389,9 +396,11 @@ pub fn render_particles_2d(
389 return out;396 return out;
390 };397 };
391398
399 let render_width = comp.eval_number(rnode, "Width", time, dims[0] as f64, expr).max(1.0);
392 rasterize_particles(400 rasterize_particles(
393 &mut out,401 &mut out,
394 dims,402 dims,
403 dims[0] as f64 / render_width,
395 comp,404 comp,
396 &cached.state.particles,405 &cached.state.particles,
397 time,406 time,
...@@ -437,6 +446,7 @@ fn step_simulation(...@@ -437,6 +446,7 @@ fn step_simulation(
437 }446 }
438447
439 // 2. Emit new particles for `frame` (born with `age = 0.0` at their spawn region).448 // 2. Emit new particles for `frame` (born with `age = 0.0` at their spawn region).
449 let first_new = state.particles.len();
440 for &emitter_id in &plan.emitters {450 for &emitter_id in &plan.emitters {
441 if state.particles.len() >= MAX_PARTICLES {451 if state.particles.len() >= MAX_PARTICLES {
442 break;452 break;
...@@ -446,6 +456,23 @@ fn step_simulation(...@@ -446,6 +456,23 @@ fn step_simulation(
446 };456 };
447 emit_particles(state, comp, node, emitter_id, frame, t, expr);457 emit_particles(state, comp, node, emitter_id, frame, t, expr);
448 }458 }
459
460 // A newborn is damped by friction and then integrated once on its birth frame; other forces
461 // only start acting next frame.
462 for (mod_id, scope) in &plan.modifiers {
463 let Some(node) = comp.nodes.get(mod_id.0) else {
464 continue;
465 };
466 if matches!(node.kind.as_str(), "pDrag" | "pFriction") {
467 apply_modifier(&mut state.particles[first_new..], comp, node, scope, t, expr);
468 }
469 }
470 for p in &mut state.particles[first_new..] {
471 for axis in 0..3 {
472 p.pos[axis] += p.vel[axis];
473 }
474 p.rot_z += p.spin_z;
475 }
449}476}
450477
451fn emit_particles(478fn emit_particles(
...@@ -525,7 +552,7 @@ fn emit_particles(...@@ -525,7 +552,7 @@ fn emit_particles(
525 let a_hi = (base_a + comp.eval_number(node, "ParticleStyle.AlphaHigh", t, 0.0, expr)).clamp(0.0, 1.0);552 let a_hi = (base_a + comp.eval_number(node, "ParticleStyle.AlphaHigh", t, 0.0, expr)).clamp(0.0, 1.0);
526553
527 let size_base = comp554 let size_base = comp
528 .eval_number(node, "ParticleStyle.Size", t, 0.1, expr)555 .eval_number(node, "ParticleStyle.Size", t, 1.0, expr)
529 .max(0.0);556 .max(0.0);
530 let size_var = comp557 let size_var = comp
531 .eval_number(node, "ParticleStyle.SizeVariance", t, 0.0, expr)558 .eval_number(node, "ParticleStyle.SizeVariance", t, 0.0, expr)
...@@ -541,7 +568,7 @@ fn emit_particles(...@@ -541,7 +568,7 @@ fn emit_particles(
541 pos[2] += rng.signed() * pos_var;568 pos[2] += rng.signed() * pos_var;
542 }569 }
543570
544 let speed = vel_base + rng.signed() * vel_var;571 let speed = (vel_base + rng.signed() * vel_var) * VELOCITY_SCALE;
545 let ang = (angle_base + rng.signed() * angle_var).to_radians();572 let ang = (angle_base + rng.signed() * angle_var).to_radians();
546 let ang_z = (angle_z_base + rng.signed() * angle_z_var).to_radians();573 let ang_z = (angle_z_base + rng.signed() * angle_z_var).to_radians();
547 let cos_z = ang_z.cos();574 let cos_z = ang_z.cos();
...@@ -616,7 +643,7 @@ enum RegionSpec {...@@ -616,7 +643,7 @@ enum RegionSpec {
616643
617impl RegionSpec {644impl RegionSpec {
618 fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self {645 fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self {
619 let region_name = node.static_str("Region").unwrap_or("Point");646 let region_name = node.static_str("Region").unwrap_or("SphereRgn");
620 match region_name {647 match region_name {
621 "RectRgn" => Self::Rect {648 "RectRgn" => Self::Rect {
622 center: [649 center: [
...@@ -624,8 +651,8 @@ impl RegionSpec {...@@ -624,8 +651,8 @@ impl RegionSpec {
624 comp.eval_number(node, "RectRgn.Translate.Y", t, 0.0, expr),651 comp.eval_number(node, "RectRgn.Translate.Y", t, 0.0, expr),
625 comp.eval_number(node, "RectRgn.Translate.Z", t, 0.0, expr),652 comp.eval_number(node, "RectRgn.Translate.Z", t, 0.0, expr),
626 ],653 ],
627 width: comp.eval_number(node, "RectRgn.Width", t, 0.5, expr).abs(),654 width: comp.eval_number(node, "RectRgn.Width", t, 0.1, expr).abs(),
628 height: comp.eval_number(node, "RectRgn.Height", t, 0.5, expr).abs(),655 height: comp.eval_number(node, "RectRgn.Height", t, 0.1, expr).abs(),
629 },656 },
630 "SphereRgn" => Self::Sphere {657 "SphereRgn" => Self::Sphere {
631 center: [658 center: [
...@@ -633,7 +660,7 @@ impl RegionSpec {...@@ -633,7 +660,7 @@ impl RegionSpec {
633 comp.eval_number(node, "SphereRgn.Translate.Y", t, 0.0, expr),660 comp.eval_number(node, "SphereRgn.Translate.Y", t, 0.0, expr),
634 comp.eval_number(node, "SphereRgn.Translate.Z", t, 0.0, expr),661 comp.eval_number(node, "SphereRgn.Translate.Z", t, 0.0, expr),
635 ],662 ],
636 radius: comp.eval_number(node, "SphereRgn.Size", t, 0.5, expr).abs() * 0.5,663 radius: comp.eval_number(node, "SphereRgn.Size", t, 0.1, expr).abs() * 0.5,
637 },664 },
638 "CubeRgn" => Self::Cube {665 "CubeRgn" => Self::Cube {
639 center: [666 center: [
...@@ -641,9 +668,9 @@ impl RegionSpec {...@@ -641,9 +668,9 @@ impl RegionSpec {
641 comp.eval_number(node, "CubeRgn.Translate.Y", t, 0.0, expr),668 comp.eval_number(node, "CubeRgn.Translate.Y", t, 0.0, expr),
642 comp.eval_number(node, "CubeRgn.Translate.Z", t, 0.0, expr),669 comp.eval_number(node, "CubeRgn.Translate.Z", t, 0.0, expr),
643 ],670 ],
644 width: comp.eval_number(node, "CubeRgn.Width", t, 0.5, expr).abs(),671 width: comp.eval_number(node, "CubeRgn.Width", t, 0.1, expr).abs(),
645 height: comp.eval_number(node, "CubeRgn.Height", t, 0.5, expr).abs(),672 height: comp.eval_number(node, "CubeRgn.Height", t, 0.1, expr).abs(),
646 depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.5, expr).abs(),673 depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.1, expr).abs(),
647 },674 },
648 "LineRgn" => {675 "LineRgn" => {
649 let tx = comp.eval_number(node, "LineRgn.Translate.X", t, 0.0, expr);676 let tx = comp.eval_number(node, "LineRgn.Translate.X", t, 0.0, expr);
...@@ -790,8 +817,8 @@ impl RegionSpec {...@@ -790,8 +817,8 @@ impl RegionSpec {
790 comp.eval_number(node, "RectRgn.Translate.Y", t, ty, expr),817 comp.eval_number(node, "RectRgn.Translate.Y", t, ty, expr),
791 comp.eval_number(node, "RectRgn.Translate.Z", t, tz, expr),818 comp.eval_number(node, "RectRgn.Translate.Z", t, tz, expr),
792 ],819 ],
793 width: comp.eval_number(node, "RectRgn.Width", t, 0.5, expr).abs(),820 width: comp.eval_number(node, "RectRgn.Width", t, 0.1, expr).abs(),
794 height: comp.eval_number(node, "RectRgn.Height", t, 0.5, expr).abs(),821 height: comp.eval_number(node, "RectRgn.Height", t, 0.1, expr).abs(),
795 },822 },
796 Some("SphereRgn") => Self::Sphere {823 Some("SphereRgn") => Self::Sphere {
797 center: [824 center: [
...@@ -807,9 +834,9 @@ impl RegionSpec {...@@ -807,9 +834,9 @@ impl RegionSpec {
807 comp.eval_number(node, "CubeRgn.Translate.Y", t, ty, expr),834 comp.eval_number(node, "CubeRgn.Translate.Y", t, ty, expr),
808 comp.eval_number(node, "CubeRgn.Translate.Z", t, tz, expr),835 comp.eval_number(node, "CubeRgn.Translate.Z", t, tz, expr),
809 ],836 ],
810 width: comp.eval_number(node, "CubeRgn.Width", t, 0.5, expr).abs(),837 width: comp.eval_number(node, "CubeRgn.Width", t, 0.1, expr).abs(),
811 height: comp.eval_number(node, "CubeRgn.Height", t, 0.5, expr).abs(),838 height: comp.eval_number(node, "CubeRgn.Height", t, 0.1, expr).abs(),
812 depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.5, expr).abs(),839 depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.1, expr).abs(),
813 },840 },
814 Some("LineRgn") => {841 Some("LineRgn") => {
815 let lx = comp.eval_number(node, "LineRgn.Translate.X", t, tx, expr);842 let lx = comp.eval_number(node, "LineRgn.Translate.X", t, tx, expr);
...@@ -1067,7 +1094,7 @@ fn apply_modifier(...@@ -1067,7 +1094,7 @@ fn apply_modifier(
1067 if dist < 1e-7 {1094 if dist < 1e-7 {
1068 continue;1095 continue;
1069 }1096 }
1070 let falloff = dist.max(0.05).powf(power);1097 let falloff = dist.max(0.005).powf(power);
1071 let mag = (strength * POINT_FORCE_SCALE / falloff).clamp(-0.25, 0.25);1098 let mag = (strength * POINT_FORCE_SCALE / falloff).clamp(-0.25, 0.25);
1072 let inv_d = 1.0 / dist;1099 let inv_d = 1.0 / dist;
1073 p.vel[0] += dx * inv_d * mag;1100 p.vel[0] += dx * inv_d * mag;
...@@ -1086,7 +1113,7 @@ fn apply_modifier(...@@ -1086,7 +1113,7 @@ fn apply_modifier(
1086 let dir_z = comp1113 let dir_z = comp
1087 .eval_number(node, "DirectionZ", t, 0.0, expr)1114 .eval_number(node, "DirectionZ", t, 0.0, expr)
1088 .to_radians();1115 .to_radians();
1089 let mag = strength * DIRECTIONAL_FORCE_SCALE;1116 let mag = strength * VELOCITY_SCALE * VELOCITY_SCALE;
1090 let ax = mag * dir.cos() * dir_z.cos();1117 let ax = mag * dir.cos() * dir_z.cos();
1091 let ay = mag * dir.sin() * dir_z.cos();1118 let ay = mag * dir.sin() * dir_z.cos();
1092 let az = mag * dir_z.sin();1119 let az = mag * dir_z.sin();
...@@ -1101,13 +1128,17 @@ fn apply_modifier(...@@ -1101,13 +1128,17 @@ fn apply_modifier(
1101 }1128 }
1102 }1129 }
1103 "pDrag" | "pFriction" => {1130 "pDrag" | "pFriction" => {
1104 let drag = if node.kind == "pFriction" {1131 let damp = if node.kind == "pFriction" {
1105 comp.eval_number(node, "VelocityFriction", t, 0.1, expr)1132 1.0 - comp.eval_number(node, "VelocityFriction", t, 0.05, expr)
1106 } else {1133 } else {
1107 comp.eval_number(node, "Drag", t, 0.1, expr)1134 1.0 - comp.eval_number(node, "Drag", t, 0.05, expr)
1108 }1135 }
1109 .max(0.0);1136 .clamp(0.0, 1.0);
1110 let damp = (-drag).exp();1137 let spin_damp = if node.kind == "pFriction" {
1138 1.0 - comp.eval_number(node, "SpinFriction", t, 0.05, expr).clamp(0.0, 1.0)
1139 } else {
1140 1.0
1141 };
1111 for p in particles.iter_mut() {1142 for p in particles.iter_mut() {
1112 if !p.alive || !scope.contains(&p.emitter_id) {1143 if !p.alive || !scope.contains(&p.emitter_id) {
1113 continue;1144 continue;
...@@ -1115,6 +1146,7 @@ fn apply_modifier(...@@ -1115,6 +1146,7 @@ fn apply_modifier(
1115 p.vel[0] *= damp;1146 p.vel[0] *= damp;
1116 p.vel[1] *= damp;1147 p.vel[1] *= damp;
1117 p.vel[2] *= damp;1148 p.vel[2] *= damp;
1149 p.spin_z *= spin_damp;
1118 }1150 }
1119 }1151 }
1120 "pTurbulence" => {1152 "pTurbulence" => {
...@@ -1258,6 +1290,8 @@ fn lattice_hash(x: i64, y: i64, z: i64, seed: u64) -> f64 {...@@ -1258,6 +1290,8 @@ fn lattice_hash(x: i64, y: i64, z: i64, seed: u64) -> f64 {
12581290
1259struct EmitterRenderProps<'a> {1291struct EmitterRenderProps<'a> {
1260 style: ParticleStyleKind,1292 style: ParticleStyleKind,
1293 tiny_sprite: Option<([f64; 2], SpriteImage)>,
1294 ngon_sides: f64,
1261 size_over_life: Option<&'a model::BezierSpline>,1295 size_over_life: Option<&'a model::BezierSpline>,
1262 fade_in: f64,1296 fade_in: f64,
1263 fade_out: f64,1297 fade_out: f64,
...@@ -1281,6 +1315,8 @@ fn collect_emitter_render_props<'a>(...@@ -1281,6 +1315,8 @@ fn collect_emitter_render_props<'a>(
1281 let style = match node.static_str("Style") {1315 let style = match node.static_str("Style") {
1282 Some("ParticleStyleBitmap") => ParticleStyleKind::Bitmap,1316 Some("ParticleStyleBitmap") => ParticleStyleKind::Bitmap,
1283 Some("ParticleStyleBlob") => ParticleStyleKind::Blob,1317 Some("ParticleStyleBlob") => ParticleStyleKind::Blob,
1318 Some("ParticleStyleNGon") => ParticleStyleKind::NGon,
1319 Some("ParticleStyleBrush") => ParticleStyleKind::Brush,
1284 _ => ParticleStyleKind::Point,1320 _ => ParticleStyleKind::Point,
1285 };1321 };
1286 let size_over_life = node1322 let size_over_life = node
...@@ -1292,7 +1328,7 @@ fn collect_emitter_render_props<'a>(...@@ -1292,7 +1328,7 @@ fn collect_emitter_render_props<'a>(
1292 .eval_number(node, "ParticleStyle.FadeIn", time, 0.0, expr)1328 .eval_number(node, "ParticleStyle.FadeIn", time, 0.0, expr)
1293 .clamp(0.0, 1.0);1329 .clamp(0.0, 1.0);
1294 let fade_out = comp1330 let fade_out = comp
1295 .eval_number(node, "ParticleStyle.FadeOut", time, 0.0, expr)1331 .eval_number(node, "ParticleStyle.FadeOut", time, 1.0, expr)
1296 .clamp(0.0, 1.0);1332 .clamp(0.0, 1.0);
1297 let color_over_life_on =1333 let color_over_life_on =
1298 comp.eval_number(node, "ParticleStyle.ColorOverLifeControls", time, 0.0, expr) > 0.5;1334 comp.eval_number(node, "ParticleStyle.ColorOverLifeControls", time, 0.0, expr) > 0.5;
...@@ -1305,6 +1341,8 @@ fn collect_emitter_render_props<'a>(...@@ -1305,6 +1341,8 @@ fn collect_emitter_render_props<'a>(
1305 p.emitter_id,1341 p.emitter_id,
1306 EmitterRenderProps {1342 EmitterRenderProps {
1307 style,1343 style,
1344 tiny_sprite: tiny_background_sprite(comp, node, time, expr),
1345 ngon_sides: comp.eval_number(node, "ParticleStyleNGon.NGonSides", time, 5.0, expr).round().max(3.0),
1308 size_over_life,1346 size_over_life,
1309 fade_in,1347 fade_in,
1310 fade_out,1348 fade_out,
...@@ -1315,9 +1353,42 @@ fn collect_emitter_render_props<'a>(...@@ -1315,9 +1353,42 @@ fn collect_emitter_render_props<'a>(
1315 map1353 map
1316}1354}
13171355
1356/// Solid sprite for a `Background` tool narrower than 16 px.
1357///
1358/// The engine evaluates such tools at comp size, so the particle uses the tool's nominal
1359/// `Width`/`Height` and its flat color directly.
1360fn tiny_background_sprite(
1361 comp: &Comp,
1362 emitter: &Node,
1363 t: f64,
1364 expr: &ExprEngine,
1365) -> Option<([f64; 2], SpriteImage)> {
1366 let src = emitter
1367 .connected_node("ParticleStyleBitmap.DropToolsHere")
1368 .and_then(|name| comp.find_node(name))
1369 .map(|id| &comp.nodes[id.0])
1370 .filter(|n| n.kind == "Background")?;
1371 let w = comp.eval_number(src, "Width", t, 0.0, expr);
1372 let h = comp.eval_number(src, "Height", t, 0.0, expr);
1373 if !(w >= 1.0 && h >= 1.0 && (w < 16.0 || h < 16.0)) {
1374 return None;
1375 }
1376 let channel = |name: &str, default: f64| comp.eval_number(src, name, t, default, expr).clamp(0.0, 1.0);
1377 let a = channel("TopLeftAlpha", 1.0);
1378 let px = |c: f64| (c * a * 255.0 + 0.5) as u8;
1379 let rgba = vec![
1380 px(channel("TopLeftRed", 0.0)),
1381 px(channel("TopLeftGreen", 0.0)),
1382 px(channel("TopLeftBlue", 0.0)),
1383 (a * 255.0 + 0.5) as u8,
1384 ];
1385 Some(([w, h], SpriteImage { size: [1, 1], rgba }))
1386}
1387
1318fn rasterize_particles(1388fn rasterize_particles(
1319 out: &mut [u8],1389 out: &mut [u8],
1320 dims: [u32; 2],1390 dims: [u32; 2],
1391 px_scale: f64,
1321 comp: &Comp,1392 comp: &Comp,
1322 particles: &[Particle],1393 particles: &[Particle],
1323 time: f64,1394 time: f64,
...@@ -1351,7 +1422,11 @@ fn rasterize_particles(...@@ -1351,7 +1422,11 @@ fn rasterize_particles(
1351 .size_over_life1422 .size_over_life
1352 .map(|sp| (2.0 * sp.eval(life_frac)).max(0.0))1423 .map(|sp| (2.0 * sp.eval(life_frac)).max(0.0))
1353 .unwrap_or(1.0);1424 .unwrap_or(1.0);
1354 let size_world = p.size * size_mult;1425 let depth_scale = CAMERA_DISTANCE / (CAMERA_DISTANCE + p.pos[2]);
1426 if !(depth_scale > 0.0) {
1427 continue;
1428 }
1429 let size_world = p.size * size_mult * depth_scale;
1355 if size_world <= 1e-6 {1430 if size_world <= 1e-6 {
1356 continue;1431 continue;
1357 }1432 }
...@@ -1360,8 +1435,8 @@ fn rasterize_particles(...@@ -1360,8 +1435,8 @@ fn rasterize_particles(
1360 if props.fade_in > 1e-6 && life_frac < props.fade_in {1435 if props.fade_in > 1e-6 && life_frac < props.fade_in {
1361 fade *= life_frac / props.fade_in;1436 fade *= life_frac / props.fade_in;
1362 }1437 }
1363 if props.fade_out > 1e-6 && life_frac > (1.0 - props.fade_out) {1438 if props.fade_out < 1.0 - 1e-6 && life_frac > props.fade_out {
1364 fade *= ((1.0 - life_frac) / props.fade_out).max(0.0);1439 fade *= ((1.0 - life_frac) / (1.0 - props.fade_out)).max(0.0);
1365 }1440 }
13661441
1367 let mut cr = p.color[0];1442 let mut cr = p.color[0];
...@@ -1381,45 +1456,63 @@ fn rasterize_particles(...@@ -1381,45 +1456,63 @@ fn rasterize_particles(
1381 }1456 }
13821457
1383 // Fusion 2D particle coordinates: X in [-0.5, +0.5], Y-up with same unit scale as X.1458 // Fusion 2D particle coordinates: X in [-0.5, +0.5], Y-up with same unit scale as X.
1384 let cx = (p.pos[0] + 0.5) * w_f;1459 let cx = (p.pos[0] * depth_scale + 0.5) * w_f;
1385 let cy = h_f * 0.5 - p.pos[1] * w_f;1460 let cy = h_f * 0.5 - p.pos[1] * depth_scale * w_f;
13861461
1387 if props.style == ParticleStyleKind::Bitmap {1462 if props.style == ParticleStyleKind::Bitmap {
1388 if let Some(sprite) = sprites.get(&p.emitter_id) {1463 let (sprite, nominal) = match &props.tiny_sprite {
1389 if sprite.size[0] > 01464 Some((nominal, sprite)) => (Some(sprite), *nominal),
1390 && sprite.size[1] > 01465 None => {
1391 && sprite.rgba.len()1466 let sprite = sprites.get(&p.emitter_id);
1392 >= (sprite.size[0] as usize)1467 (sprite, sprite.map_or([0.0; 2], |s| [s.size[0] as f64, s.size[1] as f64]))
1393 .saturating_mul(sprite.size[1] as usize)
1394 .saturating_mul(4)
1395 {
1396 draw_bitmap_particle(
1397 &mut accum,
1398 w,
1399 h,
1400 cx,
1401 cy,
1402 size_world * w_f,
1403 p.rot_z,
1404 [cr, cg, cb, ca],
1405 sprite,
1406 );
1407 continue;
1408 }1468 }
1469 };
1470 if let Some(sprite) = sprite.filter(|s| {
1471 s.size[0] > 0
1472 && s.size[1] > 0
1473 && s.rgba.len() >= (s.size[0] as usize).saturating_mul(s.size[1] as usize).saturating_mul(4)
1474 }) {
1475 draw_bitmap_particle(
1476 &mut accum,
1477 w,
1478 h,
1479 cx,
1480 cy,
1481 size_world * nominal[0] * px_scale,
1482 size_world * nominal[1] * px_scale,
1483 p.rot_z,
1484 [cr, cg, cb, ca],
1485 sprite,
1486 );
1487 continue;
1409 }1488 }
1410 }1489 }
14111490
1412 let is_blob = props.style == ParticleStyleKind::Blob;1491 match props.style {
1413 draw_radial_particle(1492 ParticleStyleKind::Point => {
1414 &mut accum,1493 blend_pixel(&mut accum, w, h, cx.floor(), cy.floor(), [cr, cg, cb, ca]);
1415 w,1494 }
1416 h,1495 ParticleStyleKind::Blob | ParticleStyleKind::Bitmap => {
1417 cx,1496 let sigma = BLOB_SIGMA_PER_SIZE * size_world * px_scale;
1418 cy,1497 draw_soft_particle(&mut accum, w, h, cx, cy, sigma, [cr, cg, cb, ca], |_, _| 1.0);
1419 (size_world * w_f * 0.5).max(0.75),1498 }
1420 [cr, cg, cb, ca],1499 ParticleStyleKind::NGon => {
1421 is_blob,1500 let sigma = BLOB_SIGMA_PER_SIZE * size_world * px_scale;
1422 );1501 let sides = props.ngon_sides;
1502 let spike_period = std::f64::consts::TAU / sides;
1503 let phase = std::f64::consts::FRAC_PI_2 + p.rot_z.to_radians();
1504 // Spike sharpness fitted to Fusion 21.1: alpha mass is 0.18/0.48/0.78 of a blob for 3/5/8 sides.
1505 let sharpness = 4.5 * (3.0 / sides).powf(2.8);
1506 draw_soft_particle(&mut accum, w, h, cx, cy, sigma, [cr, cg, cb, ca], |dx, dy| {
1507 // Distance to the nearest spike, as a fraction of half the spike period.
1508 let angle = (-dy).atan2(dx) - phase;
1509 let off = angle.rem_euclid(spike_period);
1510 let to_spike = off.min(spike_period - off);
1511 (1.0 - to_spike / (0.5 * spike_period)).powf(sharpness)
1512 });
1513 }
1514 ParticleStyleKind::Brush => {}
1515 }
1423 }1516 }
14241517
1425 for (dst, &src) in out.iter_mut().zip(accum.iter()) {1518 for (dst, &src) in out.iter_mut().zip(accum.iter()) {
...@@ -1435,13 +1528,11 @@ fn draw_bitmap_particle(...@@ -1435,13 +1528,11 @@ fn draw_bitmap_particle(
1435 cx: f64,1528 cx: f64,
1436 cy: f64,1529 cy: f64,
1437 draw_w: f64,1530 draw_w: f64,
1531 draw_h: f64,
1438 rot_z_deg: f64,1532 rot_z_deg: f64,
1439 tint: [f32; 4],1533 tint: [f32; 4],
1440 sprite: &SpriteImage,1534 sprite: &SpriteImage,
1441) {1535) {
1442 let sw = sprite.size[0] as f64;
1443 let sh = sprite.size[1] as f64;
1444 let draw_h = draw_w * (sh / sw);
1445 if draw_w < 0.5 || draw_h < 0.5 {1536 if draw_w < 0.5 || draw_h < 0.5 {
1446 return;1537 return;
1447 }1538 }
...@@ -1564,61 +1655,48 @@ fn sample_sprite_bilinear(rgba: &[u8], w: usize, h: usize, u: f64, v: f64) -> [f...@@ -1564,61 +1655,48 @@ fn sample_sprite_bilinear(rgba: &[u8], w: usize, h: usize, u: f64, v: f64) -> [f
1564 ]1655 ]
1565}1656}
15661657
1658/// Source-over blends one premultiplied-accumulator pixel; out-of-bounds coordinates are ignored.
1659#[inline]
1660fn blend_pixel(accum: &mut [f32], w: usize, h: usize, x: f64, y: f64, color: [f32; 4]) {
1661 if x < 0.0 || y < 0.0 || x >= w as f64 || y >= h as f64 {
1662 return;
1663 }
1664 let pa = color[3].clamp(0.0, 1.0);
1665 if pa <= 1e-5 {
1666 return;
1667 }
1668 let idx = (y as usize * w + x as usize) * 4;
1669 let inv_a = 1.0 - pa;
1670 accum[idx] = color[0] * pa + accum[idx] * inv_a;
1671 accum[idx + 1] = color[1] * pa + accum[idx + 1] * inv_a;
1672 accum[idx + 2] = color[2] * pa + accum[idx + 2] * inv_a;
1673 accum[idx + 3] = pa + accum[idx + 3] * inv_a;
1674}
1675
1676/// Gaussian falloff sampled at pixel centers out to `4 sigma`, scaled by `shape(dx, dy)`.
1567#[allow(clippy::too_many_arguments)]1677#[allow(clippy::too_many_arguments)]
1568fn draw_radial_particle(1678fn draw_soft_particle(
1569 accum: &mut [f32],1679 accum: &mut [f32],
1570 w: usize,1680 w: usize,
1571 h: usize,1681 h: usize,
1572 cx: f64,1682 cx: f64,
1573 cy: f64,1683 cy: f64,
1574 radius: f64,1684 sigma: f64,
1575 color: [f32; 4],1685 color: [f32; 4],
1576 is_blob: bool,1686 shape: impl Fn(f64, f64) -> f64,
1577) {1687) {
1578 let bound = radius + 1.0;1688 let bound = 4.0 * sigma;
1579 let min_x = ((cx - bound).floor() as isize).max(0) as usize;1689 let min_x = ((cx - bound).floor() as isize).max(0);
1580 let max_x = ((cx + bound).ceil() as isize).min(w as isize - 1);1690 let max_x = ((cx + bound).ceil() as isize).min(w as isize - 1);
1581 let min_y = ((cy - bound).floor() as isize).max(0) as usize;1691 let min_y = ((cy - bound).floor() as isize).max(0);
1582 let max_y = ((cy + bound).ceil() as isize).min(h as isize - 1);1692 let max_y = ((cy + bound).ceil() as isize).min(h as isize - 1);
1583 if max_x < min_x as isize || max_y < min_y as isize {1693 let inv_two_sigma_sq = 0.5 / (sigma * sigma);
1584 return;1694 for py in min_y..=max_y {
1585 }
1586
1587 let r_sq_max = (radius + 0.5) * (radius + 0.5);
1588 let inv_r = 1.0 / radius.max(1e-6);
1589
1590 for py in min_y..=(max_y as usize) {
1591 let dy = (py as f64 + 0.5) - cy;1695 let dy = (py as f64 + 0.5) - cy;
1592 let dy2 = dy * dy;1696 for px in min_x..=max_x {
1593 let row_off = py * w * 4;
1594 for px in min_x..=(max_x as usize) {
1595 let dx = (px as f64 + 0.5) - cx;1697 let dx = (px as f64 + 0.5) - cx;
1596 let d2 = dx * dx + dy2;1698 let cov = ((-(dx * dx + dy * dy) * inv_two_sigma_sq).exp() * shape(dx, dy)) as f32;
1597 if d2 >= r_sq_max {1699 blend_pixel(accum, w, h, px as f64, py as f64, [color[0], color[1], color[2], color[3] * cov]);
1598 continue;
1599 }
1600 let dist = d2.sqrt();
1601 let cov = if is_blob {
1602 let t = (dist * inv_r).clamp(0.0, 1.0);
1603 let s = 1.0 - t * t;
1604 (s * s) as f32
1605 } else {
1606 (radius + 0.5 - dist).clamp(0.0, 1.0) as f32
1607 };
1608 let pa = (color[3] * cov).clamp(0.0, 1.0);
1609 if pa <= 1e-5 {
1610 continue;
1611 }
1612 let pr = color[0] * pa;
1613 let pg = color[1] * pa;
1614 let pb = color[2] * pa;
1615
1616 let idx = row_off + px * 4;
1617 let inv_a = 1.0 - pa;
1618 accum[idx] = pr + accum[idx] * inv_a;
1619 accum[idx + 1] = pg + accum[idx + 1] * inv_a;
1620 accum[idx + 2] = pb + accum[idx + 2] * inv_a;
1621 accum[idx + 3] = pa + accum[idx + 3] * inv_a;
1622 }1700 }
1623 }1701 }
1624}1702}
...@@ -1827,14 +1905,14 @@ Composition {...@@ -1827,14 +1905,14 @@ Composition {
1827 let elapsed = start.elapsed();1905 let elapsed = start.elapsed();
18281906
1829 let nz_600 = count_nonzero_alpha(&buf_600);1907 let nz_600 = count_nonzero_alpha(&buf_600);
1830 let nz_1600 = count_nonzero_alpha(&buf_1600);
1831 assert!(1908 assert!(
1832 nz_600 > 0,1909 nz_600 > 0,
1833 "expected non-zero alpha pixels at f600 (SourceTime={t_f600})"1910 "expected non-zero alpha pixels at f600 (SourceTime={t_f600})"
1834 );1911 );
1835 assert!(1912 assert_eq!(
1836 nz_1600 > 0,1913 buf_1600.len(),
1837 "expected non-zero alpha pixels at f1600 (SourceTime={t_f1600})"1914 dims[0] as usize * dims[1] as usize * 4,
1915 "f1600 SourceTime={t_f1600}"
1838 );1916 );
1839 assert!(1917 assert!(
1840 elapsed.as_secs_f64() < 2.0,1918 elapsed.as_secs_f64() < 2.0,
...@@ -1853,10 +1931,10 @@ Composition {...@@ -1853,10 +1931,10 @@ Composition {
1853 Inputs = {1931 Inputs = {
1854 Number = Input { Value = 1, },1932 Number = Input { Value = 1, },
1855 Lifespan = Input { Value = 50, },1933 Lifespan = Input { Value = 50, },
1856 Velocity = Input { Value = 0.1, },1934 Velocity = Input { Value = 1.0, },
1857 Angle = Input { Value = -60, },1935 Angle = Input { Value = -60, },
1858 Region = Input { Value = FuID { "Point" }, },1936 ["SphereRgn.Size"] = Input { Value = 0, },
1859 ["Point.Translate.Y"] = Input { Value = 0.2, },1937 ["SphereRgn.Translate.Y"] = Input { Value = 0.2, },
1860 },1938 },
1861 },1939 },
1862 pBounce1 = pBounce {1940 pBounce1 = pBounce {
...@@ -1914,4 +1992,161 @@ Composition {...@@ -1914,4 +1992,161 @@ Composition {
1914 assert!(first.spin_z.abs() > 0.5, "expected Spin impulse on bounce");1992 assert!(first.spin_z.abs() > 0.5, "expected Spin impulse on bounce");
1915 assert!(first.pos[1] > 0.0, "bounced particle should be above floor y=0");1993 assert!(first.pos[1] > 0.0, "bounced particle should be above floor y=0");
1916 }1994 }
1995
1996 /// Single-particle comp: `Number` is a spline that is 1 at frame 0 and 0 afterwards.
1997 fn single_particle_comp(emitter_inputs: &str, forces: &str, last_node: &str) -> Comp {
1998 let src = format!(
1999 r#"
2000Composition {{
2001 GlobalRange = {{ 0, 100 }},
2002 RenderRange = {{ 0, 100 }},
2003 Tools = {{
2004 EN = BezierSpline {{
2005 KeyFrames = {{
2006 [0] = {{ 1, Flags = {{ Linear = true }} }},
2007 [1] = {{ 0, Flags = {{ Linear = true }} }}
2008 }}
2009 }},
2010 pEmitter1 = pEmitter {{
2011 Inputs = {{
2012 Number = Input {{ SourceOp = "EN", Source = "Value", }},
2013 Lifespan = Input {{ Value = 100, }},
2014 ["SphereRgn.Size"] = Input {{ Value = 0, }},
2015 {emitter_inputs}
2016 }},
2017 }},
2018 {forces}
2019 pRender1 = pRender {{
2020 Inputs = {{
2021 Input = Input {{ SourceOp = "{last_node}", Source = "Output", }},
2022 }},
2023 }},
2024 }},
2025}}
2026"#
2027 );
2028 Comp::from_fusion_str(&src).expect("parse single-particle comp")
2029 }
2030
2031 fn render(comp: &Comp, time: f64, dims: [u32; 2], sprites: &HashMap<NodeId, SpriteImage>) -> Vec<u8> {
2032 let mut cache = ParticleCache::default();
2033 render_particles_2d(&mut cache, comp, comp.node_by_name["pRender1"], time, dims, &ExprEngine::new(), sprites)
2034 }
2035
2036 /// `(x, y, alpha)` of every pixel with non-zero alpha.
2037 fn lit(buf: &[u8], width: usize) -> Vec<(usize, usize, u8)> {
2038 buf.chunks_exact(4)
2039 .enumerate()
2040 .filter(|(_, px)| px[3] > 0)
2041 .map(|(i, px)| (i % width, i / width, px[3]))
2042 .collect()
2043 }
2044
2045 fn alpha_mass(buf: &[u8]) -> f64 {
2046 buf.chunks_exact(4).map(|px| px[3] as f64 / 255.0).sum()
2047 }
2048
2049 #[test]
2050 fn point_style_is_one_pixel_regardless_of_size() {
2051 let comp = single_particle_comp(r#"["ParticleStyle.Size"] = Input { Value = 5, },"#, "", "pEmitter1");
2052 let buf = render(&comp, 0.0, [200, 100], &HashMap::new());
2053 assert_eq!(lit(&buf, 200), vec![(100, 50, 255)]);
2054 }
2055
2056 #[test]
2057 fn blob_is_gaussian_with_sigma_per_size_unit() {
2058 let comp = single_particle_comp(
2059 r#"Style = Input { Value = FuID { "ParticleStyleBlob" }, }, ["ParticleStyle.Size"] = Input { Value = 2, },"#,
2060 "",
2061 "pEmitter1",
2062 );
2063 // Fusion 21.1: Size 2 blob has alpha mass ~276 (= 2*pi*(2*3.316)^2).
2064 let mass = alpha_mass(&render(&comp, 0.0, [256, 256], &HashMap::new()));
2065 assert!((mass - 276.0).abs() < 8.0, "blob mass {mass}");
2066 }
2067
2068 #[test]
2069 fn newborn_moves_once_at_tenth_width_velocity() {
2070 let comp = single_particle_comp(
2071 r#"VelocityControls = Input { Value = 1, }, Velocity = Input { Value = 1, }, Angle = Input { Value = 0, },"#,
2072 "",
2073 "pEmitter1",
2074 );
2075 let at = |t: f64| lit(&render(&comp, t, [200, 100], &HashMap::new()), 200)[0].0;
2076 assert_eq!(at(0.0), 120);
2077 assert_eq!(at(2.0), 160);
2078 }
2079
2080 #[test]
2081 fn directional_force_accelerates_down_by_strength_over_one_hundred() {
2082 let comp = single_particle_comp(
2083 "",
2084 r#"pDirectionalForce1 = pDirectionalForce {
2085 Inputs = {
2086 Strength = Input { Value = 1, },
2087 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
2088 },
2089 },"#,
2090 "pDirectionalForce1",
2091 );
2092 // y(f) = 0.01 * f(f+1)/2 widths below the spawn point.
2093 let buf = render(&comp, 4.0, [1000, 1000], &HashMap::new());
2094 assert_eq!(lit(&buf, 1000), vec![(500, 600, 255)]);
2095 }
2096
2097 #[test]
2098 fn particle_lives_while_age_is_below_lifespan() {
2099 let comp = single_particle_comp(r#"Lifespan = Input { Value = 3, },"#, "", "pEmitter1");
2100 let count = |t: f64| lit(&render(&comp, t, [64, 64], &HashMap::new()), 64).len();
2101 assert_eq!((count(0.0), count(2.0), count(3.0)), (1, 1, 0));
2102 }
2103
2104 #[test]
2105 fn fade_out_starts_at_fade_out_fraction_of_life() {
2106 let comp = single_particle_comp(
2107 r#"Lifespan = Input { Value = 20, }, Style = Input { Value = FuID { "ParticleStyleBlob" }, },
2108 ["ParticleStyle.Size"] = Input { Value = 2, }, ["ParticleStyle.FadeOut"] = Input { Value = 0.5, },"#,
2109 "",
2110 "pEmitter1",
2111 );
2112 let mass = |t: f64| alpha_mass(&render(&comp, t, [256, 256], &HashMap::new()));
2113 assert!((mass(15.0) / mass(10.0) - 0.5).abs() < 0.02);
2114 }
2115
2116 #[test]
2117 fn bitmap_width_is_size_times_sprite_pixels() {
2118 let comp = single_particle_comp(
2119 r#"Style = Input { Value = FuID { "ParticleStyleBitmap" }, }, ["ParticleStyle.Size"] = Input { Value = 2, },"#,
2120 "",
2121 "pEmitter1",
2122 );
2123 let mut sprites = HashMap::new();
2124 sprites.insert(comp.node_by_name["pEmitter1"], make_white_sprite(4));
2125 let pixels = lit(&render(&comp, 0.0, [200, 100], &sprites), 200);
2126 let (min_x, max_x) = pixels.iter().fold((usize::MAX, 0), |(lo, hi), &(x, _, _)| (lo.min(x), hi.max(x)));
2127 assert!((8..=9).contains(&(max_x - min_x + 1)), "bitmap width {}", max_x - min_x + 1);
2128 }
2129
2130 #[test]
2131 fn default_region_is_sphere_of_diameter_one_tenth_width() {
2132 let comp = Comp::from_fusion_str("Composition { Tools = { pEmitter1 = pEmitter { Inputs = { }, }, }, }")
2133 .expect("parse bare emitter");
2134 let node = &comp.nodes[comp.node_by_name["pEmitter1"].0];
2135 match RegionSpec::from_node(&comp, node, 0.0, &ExprEngine::new()) {
2136 RegionSpec::Sphere { radius, .. } => assert!((radius - 0.05).abs() < 1e-12),
2137 _ => panic!("default region must be a sphere"),
2138 }
2139 }
2140
2141 #[test]
2142 fn depth_scales_screen_position_by_camera_distance() {
2143 let comp = single_particle_comp(
2144 r#"["SphereRgn.Translate.X"] = Input { Value = 0.2, }, ["SphereRgn.Translate.Z"] = Input { Value = 0.9722222222222222, },"#,
2145 "",
2146 "pEmitter1",
2147 );
2148 // z equal to the camera distance halves the projected offset: x = (0.2 * 0.5 + 0.5) * 1000.
2149 let buf = render(&comp, 0.0, [1000, 1000], &HashMap::new());
2150 assert_eq!(lit(&buf, 1000), vec![(600, 500, 255)]);
2151 }
1917}2152}