diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 75a4f7ad3..3d9fbd85e 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -567,8 +567,8 @@ pub trait EffectHost: Sync { } /// Parameter `id` (a [`flatten_params`] id such as `birthRate`) of effect `effect_index` in /// the layer's stack (the running effect's [`EffectEnv::effect_index`]) at another **layer - /// time**: Particle Emitter 3D samples its Birth Rate at every step it simulates (#1373). - /// `None` when unavailable. + /// time**: stepped particle systems sample their Birth Rate (#1373) and producer position + /// at every step they simulate. `None` when unavailable. fn param_at(&self, _effect_index: usize, _id: &str, _layer_time: f64) -> Option { None } @@ -1524,10 +1524,10 @@ pub fn is_time_dependent(id: &str) -> bool { } /// Does effect `id` read its own parameters at earlier times (the stepped particle systems sample -/// their Birth Rate at every step, #1373)? Caches keyed on the current values can't see what an -/// expression returned then. +/// their Birth Rate and producer position at every step, #1373)? Caches keyed on the current +/// values can't see what an expression returned then. pub fn reads_param_history(id: &str) -> bool { - matches!(id, "ec.sim.ccparticleworld" | "ec.sim.ccparticlesystems2" | "ec.sim.ccmrmercury") + matches!(id, "ec.sim.ccparticleworld" | "ec.sim.ccparticlesystems2" | "ec.sim.ccmrmercury" | "ec.sim.particleplayground") } /// Run an effect on a buffer. diff --git a/crates/effects/src/psim.rs b/crates/effects/src/psim.rs index 5716a2dcb..b414d4f57 100644 --- a/crates/effects/src/psim.rs +++ b/crates/effects/src/psim.rs @@ -13,7 +13,6 @@ #[derive(Clone, Copy, Debug, PartialEq)] pub struct EngineDesc { pub life: f32, - pub producer: [f32; 3], pub radius: [f32; 3], /// Animation (0 Explosive … 9 Fractal Uni). pub anim: u32, @@ -34,7 +33,6 @@ pub struct EngineDesc { /// Particle Playground's Cannon with gravity only (see `sim3::Pg`). #[derive(Clone, Copy, Debug, PartialEq)] pub struct CannonDesc { - pub pos: [f32; 2], pub barrel_angle: f32, pub barrel_radius: f32, pub dir_spread: f32, @@ -61,6 +59,10 @@ pub struct SimRequest<'a> { pub steps: u64, /// Birth step of every particle id born before `steps` (ascending). pub births: &'a [u32], + /// Producer position at the start of each simulated step, in the system's own coordinates: + /// entry `i` is the position used by particles born in step `i` and by the force centre + /// during step `i`. + pub producers: &'a [[f32; 3]], pub system: ParticleSystem, } @@ -110,3 +112,33 @@ pub fn births_at(steps: u64, cap: usize, rate: impl Fn(u64) -> f64) -> Option u64 { + for value in position { + hash = (hash ^ u64::from(value.to_bits())).wrapping_mul(0x0100_0000_01b3).rotate_left(5); + } + hash +} + +/// Fingerprint of the first `steps` producer positions. +pub fn producer_hash(producers: &[[f32; 3]], steps: u64) -> u64 { + let count = usize::try_from(steps).unwrap_or(usize::MAX); + let mut hash = 0; + for position in producers.iter().take(count) { + hash = producer_hash_step(hash, *position); + } + hash +} + +/// Rolling fingerprints of the producer history after each step (the empty prefix is zero). +pub fn producer_prefixes(producers: &[[f32; 3]]) -> Vec { + let mut out = Vec::with_capacity(producers.len().saturating_add(1)); + out.push(0); + let mut hash = 0; + for position in producers { + hash = producer_hash_step(hash, *position); + out.push(hash); + } + out +} diff --git a/crates/effects/src/sim.rs b/crates/effects/src/sim.rs index ca5bc5126..6f6737b18 100644 --- a/crates/effects/src/sim.rs +++ b/crates/effects/src/sim.rs @@ -28,10 +28,10 @@ mod weather; pub(crate) use common::{h, hs, pct, pt, spec}; pub use engine::particle_state; #[cfg(test)] -use engine::{MERCURY, PS2, PW_EFFECT_CAMERA, Stepped, rate_history, sim_key, simulate_rates}; +use engine::{MERCURY, PS2, PW, PW_EFFECT_CAMERA, Stepped, rate_history, sim_key, simulate_rates}; #[cfg(test)] pub(crate) use engine::{PState, PW_ANIMS, Phys, simulate}; -pub(crate) use engine::{SPS, steps_at}; +pub(crate) use engine::{ProducerPath, SPS, steps_at}; pub(crate) use particle_fx::particle_world_textured; pub use particle_fx::{Blob, mercury_blobs}; #[cfg(test)] diff --git a/crates/effects/src/sim/engine.rs b/crates/effects/src/sim/engine.rs index 8d9914e31..8904e7a53 100644 --- a/crates/effects/src/sim/engine.rs +++ b/crates/effects/src/sim/engine.rs @@ -15,6 +15,94 @@ pub(crate) fn steps_at(t: f64) -> u64 { if t <= 0.0 { 0 } else { ((t * SPS + 1e-6).floor() as u64).min(crate::util::MAX_SIM_STEPS) } } +/// The parameter path of a simulation producer and the coordinates its positions use. +#[derive(Clone, Copy, Debug)] +pub(crate) enum ProducerPath { + /// One point parameter. `by_height` converts layer pixels to the systems' height-relative units. + Point { id: &'static str, by_height: bool }, + /// Three scalar parameters in world coordinates. + Components { x: &'static str, y: &'static str, z: &'static str }, +} + +impl ProducerPath { + fn raw_current(self, ctx: &EffectCtx) -> [f64; 3] { + match self { + Self::Point { id, .. } => { + let p = ctx.params.v2(id); + [p[0], p[1], 0.0] + } + Self::Components { x, y, z } => [ctx.params.f(x), ctx.params.f(y), ctx.params.f(z)], + } + } + + fn convert(self, ctx: &EffectCtx, raw: [f64; 3]) -> [f32; 3] { + let unit = match self { + Self::Point { by_height: true, .. } => ctx.layer_size[1].max(1.0), + _ => 1.0, + }; + let finite = |v: f64| if v.is_finite() { (v / unit) as f32 } else { 0.0 }; + [finite(raw[0]), finite(raw[1]), finite(raw[2])] + } + + /// The producer position at the start of every simulated step. + pub(crate) fn history(self, ctx: &EffectCtx) -> Vec<[f32; 3]> { + let steps = steps_at(ctx.time); + if steps == 0 { + return vec![]; + } + let current_raw = self.raw_current(ctx).map(|v| if v.is_finite() { v } else { 0.0 }); + let current = self.convert(ctx, current_raw); + let host = ctx.env.host; + let index = ctx.env.effect_index; + match self { + Self::Point { id, .. } => { + let dynamic = host.is_some_and(|h| !h.param_is_static(index, id)); + if !dynamic { + return vec![current; steps as usize]; + } + (0..steps) + .map(|i| { + let raw = host + .and_then(|h| h.param_at(index, id, i as f64 / SPS)) + .map(|v| { + let p = v.as_vec2(); + [p[0], p[1], 0.0] + }) + .unwrap_or(current_raw); + self.convert(ctx, raw) + }) + .collect() + } + Self::Components { x, y, z } => { + let static_x = host.is_some_and(|h| h.param_is_static(index, x)); + let static_y = host.is_some_and(|h| h.param_is_static(index, y)); + let static_z = host.is_some_and(|h| h.param_is_static(index, z)); + (0..steps) + .map(|i| { + let time = i as f64 / SPS; + let value = |id: &str, now: f64, is_static: bool| { + if is_static { + now + } else { + host.and_then(|h| h.param_at(index, id, time)).map(|v| v.as_f64()).filter(|v| v.is_finite()).unwrap_or(now) + } + }; + self.convert(ctx, [value(x, current_raw[0], static_x), value(y, current_raw[1], static_y), value(z, current_raw[2], static_z)]) + }) + .collect() + } + } + } + + /// Parameter ids left out of the main cache key; their history is fingerprinted separately. + pub(crate) fn cache_skips(self) -> Vec<&'static str> { + match self { + Self::Point { id, .. } => vec![id], + Self::Components { x, y, z } => vec![x, y, z], + } + } +} + #[derive(Clone, Debug)] pub(crate) struct Particle { pub p: [f32; 3], @@ -34,6 +122,9 @@ pub(crate) struct PState { /// The birth rates of the steps so far (see [`rates_hash`]): a checkpoint is only resumed /// from with the same history. pub hist: u64, + /// The producer positions of the steps so far: a checkpoint is only resumed from with the + /// same producer history. + pub producer_hist: u64, } /// `hist` after one more step at `rate` particles per second. @@ -47,7 +138,6 @@ pub(crate) struct Phys { /// Particles per second. pub rate: f64, pub life: f32, - pub producer: [f32; 3], pub radius: [f32; 3], pub anim: u32, pub speed: f32, @@ -82,14 +172,14 @@ fn rand_dir(i: u32, k: u32, seed: u32, flat: bool) -> [f32; 3] { } impl Phys { - fn spawn(&self, id: u32) -> Particle { + fn spawn(&self, id: u32, producer: [f32; 3]) -> Particle { let seed = self.seed; let mut p = [0.0f32; 3]; // Uniform in the producer ellipsoid. let u = rand_dir(id, 1, seed, self.flat); let rr = h(id, 3, seed).powf(if self.flat { 0.5 } else { 1.0 / 3.0 }); for k in 0..3 { - p[k] = self.producer[k] + u[k] * self.radius[k] * rr; + p[k] = producer[k] + u[k] * self.radius[k] * rr; } if self.flat { p[2] = 0.0; @@ -118,13 +208,13 @@ impl Phys { /// One step at the constant [`Phys::rate`] (the tests' reference). #[cfg(test)] - pub(crate) fn step(&self, st: &mut PState, step: u64) { - self.step_at_rate(st, step, self.rate); + pub(crate) fn step(&self, st: &mut PState, step: u64, producer: [f32; 3]) { + self.step_at_rate(st, step, self.rate, producer); } /// One step with `rate` particles per second born during it (rather than [`Phys::rate`]): /// the rate only decides the births, particles already alive move and age as ever. - pub(crate) fn step_at_rate(&self, st: &mut PState, step: u64, rate: f64) { + pub(crate) fn step_at_rate(&self, st: &mut PState, step: u64, rate: f64, producer: [f32; 3]) { let dt = (1.0 / SPS) as f32; let t = step as f32 * dt; let mut drag = self.resistance; @@ -138,19 +228,19 @@ impl Phys { match self.anim { 4 => { // Twirly: swirl around the vertical axis through the producer. - let (dx, dz) = (q.p[0] - self.producer[0], q.p[2] - self.producer[2]); + let (dx, dz) = (q.p[0] - producer[0], q.p[2] - producer[2]); let k = 4.0 * self.extra; a[0] += -dz * k; a[2] += dx * k; if self.flat { - let dy = q.p[1] - self.producer[1]; + let dy = q.p[1] - producer[1]; a[0] += -dy * k; a[1] += dx * k; } } 5 => { // Vortex: strong tangential + inward pull. - let (dx, dy) = (q.p[0] - self.producer[0], q.p[1] - self.producer[1]); + let (dx, dy) = (q.p[0] - producer[0], q.p[1] - producer[1]); let k = 6.0 * self.extra; a[0] += -dy * k - dx * 2.0; a[1] += dx * k - dy * 2.0; @@ -183,6 +273,7 @@ impl Phys { }); st.parts.retain(|q| q.age < q.life); st.hist = rates_hash(st.hist, rate); + st.producer_hist = crate::psim::producer_hash_step(st.producer_hist, producer); st.carry += rate / SPS; let n = st.carry.floor() as u32; st.carry -= n as f64; @@ -193,7 +284,7 @@ impl Phys { let id = st.next_id; st.next_id = st.next_id.wrapping_add(1); // Sub-step birth offset keeps continuous streams smooth. - let mut q = self.spawn(id); + let mut q = self.spawn(id, producer); let frac = h(id, 12, seed) * dt; for k in 0..3 { q.p[k] += q.v[k] * frac; @@ -214,7 +305,6 @@ impl Phys { let dt = (1.0 / SPS) as f32; crate::psim::EngineDesc { life: self.life, - producer: self.producer, radius: self.radius, anim: self.anim, speed: self.speed, @@ -232,20 +322,21 @@ impl Phys { /// The state at layer time `ctx.time` from the host's particle backend (GPU particles), or /// `None` (simulate on the CPU). `rates`: the birth rate of each step, when it changes over time /// (else [`Phys::rate`]). -pub(super) fn accelerated(ctx: &EffectCtx, key: u64, phys: &Phys, rates: Option<&[f64]>) -> Option> { +pub(super) fn accelerated(ctx: &EffectCtx, key: u64, phys: &Phys, rates: Option<&[f64]>, producers: &[[f32; 3]]) -> Option> { let backend = ctx.env.host?.particles()?; let steps = steps_at(ctx.time); let births = match rates { Some(r) => crate::psim::births_at(steps, phys.max, |i| r.get(i as usize).copied().unwrap_or(0.0))?, None => crate::psim::births(phys.rate, steps, phys.max)?, }; - let req = crate::psim::SimRequest { key, steps, births: &births, system: crate::psim::ParticleSystem::Engine(phys.desc()) }; + let req = crate::psim::SimRequest { key, steps, births: &births, producers, system: crate::psim::ParticleSystem::Engine(phys.desc()) }; let parts = backend.simulate(&req)?; Some(std::sync::Arc::new(PState { parts: parts.into_iter().map(|q| Particle { p: q.p, v: q.v, age: q.age, life: q.life, rnd: q.rnd, id: q.id }).collect(), carry: 0.0, next_id: births.len() as u32, hist: 0, + producer_hist: crate::psim::producer_hash(producers, steps), })) } @@ -267,15 +358,23 @@ pub(super) fn rate_history(ctx: &EffectCtx, id: &str, k: f64) -> Vec { /// Run a particle system through `rates` (one birth rate per step, see [`rate_history`]) with /// `cache`, resuming only from checkpoints reached with the same rates. -pub(super) fn simulate_rates(cache: &SimCache, key: u64, phys: &Phys, rates: &[f64]) -> std::sync::Arc { +pub(super) fn simulate_rates(cache: &SimCache, key: u64, phys: &Phys, rates: &[f64], producers: &[[f32; 3]]) -> std::sync::Arc { // `hist` of the state after each number of steps. let mut prefix = Vec::with_capacity(rates.len() + 1); prefix.push(0u64); for r in rates { prefix.push(rates_hash(prefix.last().copied().unwrap_or(0), *r)); } + let producer_prefix = crate::psim::producer_prefixes(producers); let rate = |i: u64| rates.get(i as usize).copied().unwrap_or(0.0); - cache.run_where(key, rates.len() as u64, PState::default, |st, i| phys.step_at_rate(st, i, rate(i)), |s, st| prefix.get(s as usize) == Some(&st.hist)) + let producer = |i: u64| producers.get(i as usize).copied().unwrap_or([0.0; 3]); + cache.run_where( + key, + rates.len() as u64, + PState::default, + |st, i| phys.step_at_rate(st, i, rate(i), producer(i)), + |s, st| prefix.get(s as usize) == Some(&st.hist) && producer_prefix.get(s as usize) == Some(&st.producer_hist), + ) } /// A stepped particle system's particles at `ctx.time`, born at the Birth Rate of their own @@ -286,6 +385,7 @@ pub(super) struct Stepped<'a> { pub(super) cache: &'a SimCache, pub(super) salt: u64, pub(super) skip: &'a [&'a str], + pub(super) producer: ProducerPath, pub(super) k: f64, pub(super) gpu: bool, } @@ -293,20 +393,31 @@ pub(super) struct Stepped<'a> { impl Stepped<'_> { pub(super) fn state(&self, ctx: &EffectCtx, phys: &Phys) -> std::sync::Arc { let rates = rate_history(ctx, "birthRate", self.k); + let producers = self.producer.history(ctx); let mut skip = self.skip.to_vec(); skip.push("birthRate"); + skip.extend(self.producer.cache_skips()); let key = params_key_except(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, self.salt, &skip); - let gpu = if self.gpu { accelerated(ctx, key, phys, Some(&rates)) } else { None }; - gpu.unwrap_or_else(|| simulate_rates(self.cache, key, phys, &rates)) + let gpu = if self.gpu { accelerated(ctx, key, phys, Some(&rates), &producers) } else { None }; + gpu.unwrap_or_else(|| simulate_rates(self.cache, key, phys, &rates, &producers)) } } /// CC Particle World. -const PW: Stepped = Stepped { cache: &PW_CACHE, salt: 1, skip: &[PW_EFFECT_CAMERA], k: PW_RATE, gpu: true }; +pub(super) const PW: Stepped = Stepped { + cache: &PW_CACHE, + salt: 1, + skip: &[PW_EFFECT_CAMERA], + producer: ProducerPath::Components { x: "producer/producerX", y: "producer/producerY", z: "producer/producerZ" }, + k: PW_RATE, + gpu: true, +}; /// CC Particle Systems II. -pub(super) const PS2: Stepped = Stepped { cache: &PS2_CACHE, salt: 2, skip: &[], k: PS2_RATE, gpu: true }; +pub(super) const PS2: Stepped = + Stepped { cache: &PS2_CACHE, salt: 2, skip: &[], producer: ProducerPath::Point { id: "producer/position", by_height: true }, k: PS2_RATE, gpu: true }; /// CC Mr. Mercury (its blobs are simulated on the CPU). -pub(super) const MERCURY: Stepped = Stepped { cache: &MERCURY_CACHE, salt: 3, skip: &[], k: MERCURY_RATE, gpu: false }; +pub(super) const MERCURY: Stepped = + Stepped { cache: &MERCURY_CACHE, salt: 3, skip: &[], producer: ProducerPath::Point { id: "producer", by_height: true }, k: MERCURY_RATE, gpu: false }; /// CC Particle World's particles at `ctx.time`, born at the Birth Rate of their own time. pub(super) fn pw_state(ctx: &EffectCtx, phys: &Phys) -> std::sync::Arc { @@ -326,17 +437,19 @@ pub fn particle_state(id: &str, ctx: &EffectCtx) -> Option u64 { - params_key_except(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, salt, &[PW_EFFECT_CAMERA]) + let mut skip = vec![PW_EFFECT_CAMERA, "birthRate"]; + skip.extend(PW.producer.cache_skips()); + params_key_except(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, salt, &skip) } /// Run a particle system at its constant [`Phys::rate`] to layer time `t` through `cache` (the /// tests' reference). #[cfg(test)] -pub(crate) fn simulate(cache: &SimCache, key: u64, t: f64, phys: &Phys) -> std::sync::Arc { - cache.run(key, steps_at(t), PState::default, |st, i| phys.step(st, i)) +pub(crate) fn simulate(cache: &SimCache, key: u64, t: f64, phys: &Phys, producer: [f32; 3]) -> std::sync::Arc { + cache.run(key, steps_at(t), PState::default, |st, i| phys.step(st, i, producer)) } pub(crate) const PARTICLE_TYPES: &[&str] = diff --git a/crates/effects/src/sim/particle_fx.rs b/crates/effects/src/sim/particle_fx.rs index c2f493ab5..d15a6188d 100644 --- a/crates/effects/src/sim/particle_fx.rs +++ b/crates/effects/src/sim/particle_fx.rs @@ -15,7 +15,6 @@ pub(super) fn pw_phys(ctx: &EffectCtx) -> Phys { Phys { rate: pr.f("birthRate").max(0.0) * PW_RATE, life: pr.f("longevity").max(0.0) as f32, - producer: [pr.f("producer/producerX") as f32, pr.f("producer/producerY") as f32, pr.f("producer/producerZ") as f32], radius: [pr.f("producer/radiusX").max(0.0) as f32, pr.f("producer/radiusY").max(0.0) as f32, pr.f("producer/radiusZ").max(0.0) as f32], anim: pr.e("physics/animation"), speed: pr.f("physics/velocity") as f32 * 0.5, @@ -251,12 +250,10 @@ pub(super) fn ps2_phys(ctx: &EffectCtx) -> Phys { let pr = ctx.params; let lh = ctx.layer_size[1] as f32; let unit = lh.max(1.0); - let pos = pr.v2("producer/position"); let dir = (pr.f("physics/direction") as f32).to_radians(); Phys { rate: pr.f("birthRate").max(0.0) * PS2_RATE, life: pr.f("longevity").max(0.0) as f32, - producer: [pos[0] as f32 / unit, pos[1] as f32 / unit, 0.0], radius: [pr.f("producer/radiusX").max(0.0) as f32 / unit, pr.f("producer/radiusY").max(0.0) as f32 / unit, 0.0], anim: [0u32, 1, 2, 3, 4, 5, 6, 7, 8, 9][pr.e("physics/animation").min(9) as usize], speed: pr.f("physics/velocity") as f32 * 0.25, @@ -321,12 +318,10 @@ pub struct Blob { pub(super) fn mercury_phys(ctx: &EffectCtx) -> Phys { let pr = ctx.params; let unit = (ctx.layer_size[1] as f32).max(1.0); - let pos = pr.v2("producer"); let dir = (pr.f("direction") as f32).to_radians(); Phys { rate: pr.f("birthRate").max(0.0) * MERCURY_RATE, life: pr.f("longevity").max(0.0) as f32, - producer: [pos[0] as f32 / unit, pos[1] as f32 / unit, 0.0], radius: [pr.f("radiusX").max(0.0) as f32 / unit, pr.f("radiusY").max(0.0) as f32 / unit, 0.0], anim: [0u32, 1, 2, 3, 4, 5, 6, 7, 8, 9][pr.e("animation").min(9) as usize], speed: pr.f("velocity") as f32 * 0.3, diff --git a/crates/effects/src/sim/tests.rs b/crates/effects/src/sim/tests.rs index 4c708dae4..592a3b0ba 100644 --- a/crates/effects/src/sim/tests.rs +++ b/crates/effects/src/sim/tests.rs @@ -227,7 +227,6 @@ fn engine_resume_equals_from_scratch() { let phys = Phys { rate: 90.0, life: 1.5, - producer: [0.0; 3], radius: [0.05; 3], anim, speed: 0.5, @@ -242,10 +241,10 @@ fn engine_resume_equals_from_scratch() { }; let a: SimCache = SimCache::new(2); let b: SimCache = SimCache::new(2); - let direct = simulate(&a, 1, 2.0, &phys); - let _ = simulate(&b, 1, 1.0, &phys); - let _ = simulate(&b, 1, 0.37, &phys); - let resumed = simulate(&b, 1, 2.0, &phys); + let direct = simulate(&a, 1, 2.0, &phys, [0.0; 3]); + let _ = simulate(&b, 1, 1.0, &phys, [0.0; 3]); + let _ = simulate(&b, 1, 0.37, &phys, [0.0; 3]); + let resumed = simulate(&b, 1, 2.0, &phys, [0.0; 3]); assert_eq!(direct.parts.len(), resumed.parts.len(), "anim {anim}"); assert!(direct.parts.iter().zip(&resumed.parts).all(|(p, q)| p.p == q.p && p.v == q.v && p.id == q.id), "anim {anim}"); assert!(!direct.parts.is_empty()); @@ -566,6 +565,34 @@ fn half_resolution_scales_sprites() { // ---------------------------------------------------------- Birth Rate over time (#1373) +/// A host whose producer moves from `start_x` at layer time 0 to `start_x + 60 · t`. +struct MovingProducer { + index: usize, + start_x: f64, +} + +impl crate::EffectHost for MovingProducer { + fn layer(&self, _: u64, _: bool) -> Option { + None + } + fn audio(&self, _: u64, _: f64, _: usize, _: u32) -> Option> { + None + } + fn param_at(&self, effect_index: usize, id: &str, t: f64) -> Option { + if effect_index != self.index { + return None; + } + let x = self.start_x + 60.0 * t; + match id { + "producer/position" | "producer" => Some(Value::Vec2([x, 50.0])), + "producer/producerX" => Some(num(x)), + "producer/producerY" => Some(num(50.0)), + "producer/producerZ" => Some(num(0.0)), + _ => None, + } + } +} + /// A host that evaluates effect `index`'s Birth Rate at other layer times as `rate(t)`. struct Rate { index: usize, @@ -624,8 +651,13 @@ fn pw_at(seed: f64, now: f64, t: f64, host: Option<&Rate>) -> Vec Vec { let p = pw_params(seed, now); let ctx = pw_ctx(&p, t, Some(host), host.index); - let key = params_key_except(&ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 1, &[PW_EFFECT_CAMERA, "birthRate"]); - let st = simulate_rates(&SimCache::new(1), key, &pw_phys(&ctx), &rate_history(&ctx, "birthRate", PW_RATE)); + let rates = rate_history(&ctx, "birthRate", PW_RATE); + let producers = PW.producer.history(&ctx); + let mut skip = PW.skip.to_vec(); + skip.push("birthRate"); + skip.extend(PW.producer.cache_skips()); + let key = params_key_except(&ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 1, &skip); + let st = simulate_rates(&SimCache::new(1), key, &pw_phys(&ctx), &rates, &producers); st.parts.iter().map(|q| crate::psim::SimParticle { p: q.p, v: q.v, age: q.age, life: q.life, rnd: q.rnd, id: q.id }).collect() } @@ -699,7 +731,7 @@ fn a_constant_birth_rate_is_unchanged() { let p = pw_params(105.0, 2.0); let ctx = pw_ctx(&p, 1.3, None, 0); let phys = pw_phys(&ctx); - let before = simulate(&SimCache::new(1), sim_key(&ctx, 1), 1.3, &phys); + let before = simulate(&SimCache::new(1), sim_key(&ctx, 1), 1.3, &phys, [0.0; 3]); let now = pw_at(105.0, 2.0, 1.3, Some(&host)); assert_eq!(now.len(), before.parts.len()); assert!(now.iter().zip(&before.parts).all(|(a, b)| a.id == b.id && a.p == b.p && a.v == b.v && a.age == b.age)); @@ -714,7 +746,8 @@ fn the_birth_schedule_follows_the_rate_history() { let p = pw_params(106.0, 0.0); let ctx = pw_ctx(&p, 0.7, Some(&host), 0); let rates = rate_history(&ctx, "birthRate", PW_RATE); - let st = simulate_rates(&SimCache::new(1), 9, &pw_phys(&ctx), &rates); + let producers = PW.producer.history(&ctx); + let st = simulate_rates(&SimCache::new(1), 9, &pw_phys(&ctx), &rates, &producers); let births = crate::psim::births_at(rates.len() as u64, 40_000, |i| rates[i as usize]).unwrap(); assert_eq!(st.next_id as usize, births.len()); assert!(births.iter().all(|&b| f64::from(b) / SPS < 0.5), "nothing born once the ramp reaches 0"); @@ -762,8 +795,11 @@ fn sys_fresh(sys: &System, seed: u32, now: f64, t: f64, host: &Rate) -> Vec<(u32 let ctx = sys_ctx(&p, t, Some(host), seed); let mut skip = sys.stepped.skip.to_vec(); skip.push("birthRate"); + skip.extend(sys.stepped.producer.cache_skips()); let key = params_key_except(&ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, sys.stepped.salt, &skip); - let st = simulate_rates(&SimCache::new(1), key, &(sys.phys)(&ctx), &rate_history(&ctx, "birthRate", sys.stepped.k)); + let rates = rate_history(&ctx, "birthRate", sys.stepped.k); + let producers = sys.stepped.producer.history(&ctx); + let st = simulate_rates(&SimCache::new(1), key, &(sys.phys)(&ctx), &rates, &producers); st.parts.iter().map(|q| (q.id, q.p, q.age)).collect() } @@ -819,10 +855,134 @@ fn particle_systems_ii_and_mr_mercury_are_unchanged_at_a_constant_rate() { for sys in &SYSTEMS { let p = sys_params(sys.id, 2.0); let ctx = sys_ctx(&p, 1.3, None, 203); - let before = simulate(&SimCache::new(1), 1, 1.3, &(sys.phys)(&ctx)); + let producers = sys.stepped.producer.history(&ctx); + let producer = producers.last().copied().unwrap_or([0.0; 3]); + let before = simulate(&SimCache::new(1), 1, 1.3, &(sys.phys)(&ctx), producer); let before: Vec<_> = before.parts.iter().map(|q| (q.id, q.p, q.age)).collect(); assert!(!before.is_empty()); assert_eq!(sys_at(sys, 203, 2.0, 1.3, Some(&host)), before, "{}: keyed to a constant", sys.id); assert_eq!(sys_at(sys, 203, 2.0, 1.3, None), before, "{}: no host", sys.id); } } + +/// #1955: a particle is born where its producer was during that step, not where the producer +/// is when the frame is rendered. +#[test] +fn stepped_particles_are_born_at_their_producer_positions() { + let cases: [(&str, &Stepped<'static>, fn(&EffectCtx) -> Phys); 3] = + [("ec.sim.ccparticleworld", &PW, pw_phys), ("ec.sim.ccparticlesystems2", &PS2, ps2_phys), ("ec.sim.ccmrmercury", &MERCURY, mercury_phys)]; + for (id, stepped, phys_fn) in cases { + let mut p = sys_params(id, 1.0); + p.values.insert("longevity".into(), num(5.0)); + for (key, value) in [ + ("producer/radiusX", num(0.0)), + ("producer/radiusY", num(0.0)), + ("producer/radiusZ", num(0.0)), + ("radiusX", num(0.0)), + ("radiusY", num(0.0)), + ("physics/velocity", num(0.0)), + ("physics/gravity", num(0.0)), + ("gravity", num(0.0)), + ("velocity", num(0.0)), + ] { + if p.values.contains_key(key) { + p.values.insert(key.into(), value); + } + } + match id { + "ec.sim.ccparticleworld" => { + p.values.insert("producer/producerX".into(), num(80.0)); + p.values.insert("producer/producerY".into(), num(50.0)); + p.values.insert("producer/producerZ".into(), num(0.0)); + } + "ec.sim.ccparticlesystems2" => { + p.values.insert("producer/position".into(), pt(80.0, 50.0)); + } + "ec.sim.ccmrmercury" => { + p.values.insert("producer".into(), pt(80.0, 50.0)); + } + _ => {} + } + let host = MovingProducer { index: 0, start_x: 20.0 }; + let env = EffectEnv { host: Some(&host), effect_index: 0, ..Default::default() }; + let ctx = EffectCtx { params: &p, time: 1.0, layer_size: [100.0, 100.0], seed: 301, adjustment: false, env }; + let phys = phys_fn(&ctx); + let state = stepped.state(&ctx, &phys); + let births = crate::psim::births_at(steps_at(ctx.time), 40_000, |_| phys.rate).unwrap(); + assert!(!state.parts.is_empty(), "{id}: particles born"); + for q in &state.parts { + let birth = births[q.id as usize] as f32; + // The producer moves 60 units per second. Particle Emitter 3D uses world units; + // the 2D systems use layer-height-relative units in this 100-pixel-high layer. + let want = if id == "ec.sim.ccparticleworld" { [20.0 + birth, 50.0, 0.0] } else { [(20.0 + birth) / 100.0, 0.5, 0.0] }; + let distance = (0..3).map(|k| (q.p[k] - want[k]).abs()).fold(0.0f32, f32::max); + assert!(distance < 1e-5, "{id}: particle {} born at {want:?}, not {:?}", q.id, q.p); + } + } +} + +/// A producer's current position stays out of the simulation key even in production-shaped +/// parameters, where it has both a canonical id and a positional alias. +#[test] +fn current_producer_positions_do_not_change_stepped_simulation_keys() { + use effectcraft_project::build::Ids; + let cases: [(&str, &Stepped<'static>, &[(&str, &str, Value)], (&str, Value)); 3] = [ + ( + "ec.sim.ccparticleworld", + &PW, + &[ + ("producer/producerX", "#1/producerX", num(80.0)), + ("producer/producerY", "#1/producerY", num(50.0)), + ("producer/producerZ", "#1/producerZ", num(0.0)), + ], + ("longevity", num(2.0)), + ), + ("ec.sim.ccparticlesystems2", &PS2, &[("producer/position", "#1/position", pt(80.0, 50.0))], ("longevity", num(2.0))), + ("ec.sim.ccmrmercury", &MERCURY, &[("producer", "producer", pt(80.0, 50.0))], ("radiusX", num(2.0))), + ]; + for (id, stepped, producers, (other, other_value)) in cases { + let spec = crate::find(id).unwrap(); + let mut next = 1; + let group = crate::instantiate(spec, &mut Ids(&mut next), spec.name, [100.0, 100.0]); + let mut p = crate::flatten_params(&group, &mut |pr| pr.value.clone()); + let key = |p: &crate::Params| { + let ctx = EffectCtx { params: p, time: 1.0, layer_size: [100.0, 100.0], seed: 303, adjustment: false, env: EffectEnv::default() }; + let mut skip = stepped.skip.to_vec(); + skip.push("birthRate"); + skip.extend(stepped.producer.cache_skips()); + params_key_except(&ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, stepped.salt, &skip) + }; + let before = key(&p); + for (canonical, alias, value) in producers { + assert!(p.values.contains_key(*canonical), "{id}: {canonical}"); + assert!(p.values.contains_key(*alias), "{id}: {alias}"); + p.values.insert((*canonical).into(), (*value).clone()); + p.values.insert((*alias).into(), (*value).clone()); + } + assert_eq!(key(&p), before, "{id}: the current producer position changed the key"); + p.values.insert(other.into(), other_value); + assert_ne!(key(&p), before, "{id}: another parameter still changes the key"); + } +} + +/// The producer's current value is not part of the simulation key, but an earlier producer +/// value is: a checkpoint reached with another producer history is not reused. +#[test] +fn a_changed_producer_history_drops_stale_checkpoints() { + let state = |start_x| { + let mut p = sys_params("ec.sim.ccparticlesystems2", 1.0); + p.values.insert("longevity".into(), num(5.0)); + p.values.insert("producer/position".into(), pt(80.0, 50.0)); + p.values.insert("producer/radiusX".into(), num(0.0)); + p.values.insert("producer/radiusY".into(), num(0.0)); + p.values.insert("physics/velocity".into(), num(0.0)); + p.values.insert("physics/gravity".into(), num(0.0)); + let host = MovingProducer { index: 0, start_x }; + let env = EffectEnv { host: Some(&host), effect_index: 0, ..Default::default() }; + let ctx = EffectCtx { params: &p, time: 1.0, layer_size: [100.0, 100.0], seed: 302, adjustment: false, env }; + let phys = ps2_phys(&ctx); + PS2.state(&ctx, &phys).parts.first().map(|q| q.p).unwrap() + }; + assert!((state(20.0)[0] - 0.2).abs() < 1e-5, "{:?}", state(20.0)); + assert!((state(60.0)[0] - 0.6).abs() < 1e-5, "{:?}", state(60.0)); +} diff --git a/crates/effects/src/sim3.rs b/crates/effects/src/sim3.rs index c2a286390..7fe00bbd6 100644 --- a/crates/effects/src/sim3.rs +++ b/crates/effects/src/sim3.rs @@ -27,8 +27,8 @@ use effectcraft_project::ParamUi; use effectcraft_raster::{Image, Px}; use rayon::prelude::*; -use crate::sim::{Acc, Post, SPS, Shape, Sprite, SpritePlan, Tint, combine, splat, steps_at}; -use crate::util::{SimCache, hash1, params_key, point_in_poly, unpremul}; +use crate::sim::{Acc, Post, ProducerPath, SPS, Shape, Sprite, SpritePlan, Tint, combine, splat, steps_at}; +use crate::util::{SimCache, hash1, params_key_except, point_in_poly, unpremul}; use crate::{Buf, EffectCtx, EffectSpec, col, num, p, popup, slider}; fn spec(id: &'static str, name: &'static str, params: Vec, render: crate::RenderFn) -> EffectSpec { @@ -108,6 +108,8 @@ pub struct PgState { pub parts: Vec, carry: f64, next_id: u32, + /// Fingerprint of the producer positions of the steps so far. + producer_hist: u64, } /// A map layer sampled in layer coordinates. @@ -346,7 +348,6 @@ impl Mapper { struct Pg { // Cannon cannon: bool, - pos: [f32; 2], barrel_angle: f32, barrel_radius: f32, rate: f64, @@ -380,7 +381,8 @@ struct Pg { } impl Pg { - fn spawn(&self, id: u32) -> PgParticle { + /// Spawn a cannon particle at `producer` (the cannon's position during its birth step). + fn spawn_at(&self, id: u32, producer: [f32; 2]) -> PgParticle { let s = self.seed; let h = |k: u32| hash1(id, k, s) * 2.0 - 1.0; // AE angles: 0° = up, clockwise. @@ -395,7 +397,7 @@ impl Pg { let (a, rr) = (hash1(id, 5, s) * std::f32::consts::TAU, hash1(id, 6, s).sqrt() * -r); [a.cos() * rr, a.sin() * rr] }; - let p = [self.pos[0] + off[0], self.pos[1] + off[1]]; + let p = [producer[0] + off[0], producer[1] + off[1]]; let mut q = PgParticle::new(p, [d[0] * speed, d[1] * speed], self.color, self.radius, id, SRC_CANNON); if !self.cannon_text.is_empty() { q.ch = self.cannon_text[id as usize % self.cannon_text.len()] as u32; @@ -403,6 +405,12 @@ impl Pg { q } + /// Spawn a cannon particle at the origin (the tests' reference). + #[cfg(test)] + fn spawn(&self, id: u32) -> PgParticle { + self.spawn_at(id, [0.0; 2]) + } + /// The particle as the ephemeral mapper sees it this step (unchanged without one). fn ephemeral(&self, q: &PgParticle) -> PgParticle { let mut e = *q; @@ -412,7 +420,8 @@ impl Pg { e } - fn step(&self, st: &mut PgState) { + /// Advance the simulation one step, using `producer` for particles born in that step. + fn step_at(&self, st: &mut PgState, producer: [f32; 2]) { let dt = (1.0 / SPS) as f32; let s = self.seed; // Persistent Property Mapper: the mapped values stay with the particle. @@ -534,18 +543,36 @@ impl Pg { } let id = st.next_id; st.next_id = st.next_id.wrapping_add(1); - let mut q = self.spawn(id); + let mut q = self.spawn_at(id, producer); // Sub-step birth offset keeps streams smooth. let frac = hash1(id, 9, s) * dt; q.p = [q.p[0] + q.v[0] * frac, q.p[1] + q.v[1] * frac]; st.parts.push(q); } } + st.producer_hist = crate::psim::producer_hash_step(st.producer_hist, [producer[0], producer[1], 0.0]); + } + + /// Advance one step with the origin as its producer (the tests' reference). + #[cfg(test)] + fn step(&self, st: &mut PgState) { + self.step_at(st, [0.0; 2]); } } static PG_CACHE: SimCache = SimCache::new(6); +/// The cannon's position history is sampled in layer pixels, not in the shared systems' +/// height-relative coordinates. +const PG_PRODUCER: ProducerPath = ProducerPath::Point { id: "cannon/cannonPosition", by_height: false }; + +/// The simulation key without the cannon's current position: its history is fingerprinted +/// separately, so moving the cannon does not make every simulation restart. +fn pg_key(ctx: &EffectCtx) -> u64 { + let skip = PG_PRODUCER.cache_skips(); + params_key_except(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 0x7067, &skip) +} + fn image_key(img: &Image) -> u64 { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); @@ -615,7 +642,6 @@ fn pg_of(ctx: &EffectCtx) -> Pg { let ephemeral = mapper_from(ctx, "ephemeralPropertyMapper", true); Pg { cannon: pr.b("cannonEnabled"), - pos: { pr.v2("cannon/cannonPosition").map(|v| v as f32) }, barrel_angle: pr.f("cannon/barrelAngle") as f32, barrel_radius: pr.f("cannon/barrelRadius") as f32, rate: pr.f("cannon/particlesPerSecond").max(0.0), @@ -665,12 +691,14 @@ impl Affects { } /// Particle Playground cannons with gravity only, simulated by the host's particle backend. -fn pg_accelerated(ctx: &EffectCtx, key: u64, pg: &Pg) -> Option> { +fn pg_accelerated(ctx: &EffectCtx, key: u64, pg: &Pg, producers: &[[f32; 3]]) -> Option> { let backend = ctx.env.host?.particles()?; let steps = steps_at(ctx.time); + if producers.len() < usize::try_from(steps).ok()? { + return None; + } let births = crate::psim::births(pg.rate, steps, 60_000)?; let desc = crate::psim::CannonDesc { - pos: pg.pos, barrel_angle: pg.barrel_angle, barrel_radius: pg.barrel_radius, dir_spread: pg.dir_spread, @@ -681,19 +709,22 @@ fn pg_accelerated(ctx: &EffectCtx, key: u64, pg: &Pg) -> Option>>()?; + Some(std::sync::Arc::new(PgState { parts, carry: 0.0, next_id: births.len() as u32, producer_hist: crate::psim::producer_hash(producers, steps) })) } /// The live particles of a Particle Playground whose cannon is the only producer and force @@ -707,8 +738,19 @@ pub fn playground_state(ctx: &EffectCtx) -> Option if !pg.cannon_only() || grid || exploder { return None; } - let key = params_key(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 0x7067); - let st = pg_accelerated(ctx, key, &pg).unwrap_or_else(|| PG_CACHE.run(key, steps_at(ctx.time), PgState::default, |st, _| pg.step(st))); + let producers = PG_PRODUCER.history(ctx); + let producer_prefix = crate::psim::producer_prefixes(&producers); + let key = pg_key(ctx); + let producer = |i: u64| producers.get(i as usize).map(|p| [p[0], p[1]]).unwrap_or([0.0; 2]); + let st = pg_accelerated(ctx, key, &pg, &producers).unwrap_or_else(|| { + PG_CACHE.run_where( + key, + steps_at(ctx.time), + PgState::default, + |st, i| pg.step_at(st, producer(i)), + |s, st| producer_prefix.get(s as usize) == Some(&st.producer_hist), + ) + }); Some( st.parts .iter() @@ -748,7 +790,7 @@ pub fn playground_plan(ctx: &EffectCtx, b: &Buf) -> PgPlan { let ex_r = pr.f("layerExploder/radiusOfNewParticles").max(0.5) as f32; let ex_disp = pr.f("layerExploder/velocityDispersion") as f32; - let mut key = params_key(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 0x7067); + let mut key = pg_key(ctx); for m in [&pg.persistent, &pg.ephemeral].into_iter().flatten() { key ^= image_key(&m.map.img).rotate_left(7); } @@ -819,8 +861,19 @@ pub fn playground_plan(ctx: &EffectCtx, b: &Buf) -> PgPlan { }; // A cannon with gravity only: every particle moves on its own (GPU particles). let independent = pg.cannon_only() && !(grid_on && across > 0 && down > 0) && exploder.is_none(); - let gpu = if independent { pg_accelerated(ctx, key, &pg) } else { None }; - let st = gpu.unwrap_or_else(|| PG_CACHE.run(key, steps_at(ctx.time), init, |st, _| pg.step(st))); + let producers = PG_PRODUCER.history(ctx); + let producer_prefix = crate::psim::producer_prefixes(&producers); + let producer = |i: u64| producers.get(i as usize).map(|p| [p[0], p[1]]).unwrap_or([0.0; 2]); + let gpu = if independent { pg_accelerated(ctx, key, &pg, &producers) } else { None }; + let st = gpu.unwrap_or_else(|| { + PG_CACHE.run_where( + key, + steps_at(ctx.time), + init, + |st, i| pg.step_at(st, producer(i)), + |s, st| producer_prefix.get(s as usize) == Some(&st.producer_hist), + ) + }); // Render: what the ephemeral mapper changes shows for this frame only. let parts: Vec = st.parts.iter().map(|q| pg.ephemeral(q)).collect(); let auto_orient = pr.b("options/autoOrientRotation"); diff --git a/crates/effects/src/sim3/tests.rs b/crates/effects/src/sim3/tests.rs index ffce0ae6d..8e0be1ec0 100644 --- a/crates/effects/src/sim3/tests.rs +++ b/crates/effects/src/sim3/tests.rs @@ -1,5 +1,5 @@ use super::*; -use crate::{EffectEnv, MaskShape, run_fx}; +use crate::{EffectCtx, EffectEnv, MaskShape, Params, run_fx}; fn run(vals: &[(&str, Value)], t: f64) -> Image { run_fx("ec.sim.particleplayground", vals, Image::filled(80, 60, [0.2, 0.2, 0.2, 1.0]), t, EffectEnv::default()).img @@ -27,6 +27,125 @@ fn cannon_stream_is_seek_consistent() { assert!(z.data.iter().all(|p| p[3] == 0.0)); } +/// A host whose cannon moves from `start_x` at layer time 0 to `start_x + 60 · t`. +struct MovingCannon { + index: usize, + start_x: f64, +} + +impl crate::EffectHost for MovingCannon { + fn layer(&self, _: u64, _: bool) -> Option { + None + } + fn audio(&self, _: u64, _: f64, _: usize, _: u32) -> Option> { + None + } + fn param_at(&self, effect_index: usize, id: &str, t: f64) -> Option { + (effect_index == self.index && id == "cannon/cannonPosition").then_some(Value::Vec2([self.start_x + 60.0 * t, 50.0])) + } +} + +fn pg_params(current_x: f64) -> Params { + let spec = crate::find("ec.sim.particleplayground").unwrap(); + let mut p = Params { values: spec.params.iter().map(|ps| (ps.id.to_string(), crate::default_value(ps, [80.0, 60.0]))).collect() }; + for (id, value) in [ + ("gridEnabled", Value::Bool(false)), + ("cannonEnabled", Value::Bool(true)), + ("cannon/cannonPosition", Value::Vec2([current_x, 50.0])), + ("cannon/barrelRadius", num(0.0)), + ("cannon/particlesPerSecond", num(60.0)), + ("cannon/directionRandomSpread", num(0.0)), + ("cannon/velocity", num(0.0)), + ("cannon/velocityRandomSpread", num(0.0)), + ("gravity/gravityForce", num(0.0)), + ("randomSeed", num(1.0)), + ] { + p.values.insert(id.into(), value); + } + p +} + +/// Production-shaped Particle Playground parameters, including the positional aliases that +/// [`crate::flatten_params`] adds for grouped controls. +fn pg_production_params(current_x: f64) -> Params { + use effectcraft_project::build::Ids; + let spec = crate::find("ec.sim.particleplayground").unwrap(); + let mut next = 1; + let mut group = crate::instantiate(spec, &mut Ids(&mut next), spec.name, [80.0, 60.0]); + group.sub_mut("cannon").unwrap().prop_mut("cannonPosition").unwrap().value = Value::Vec2([current_x, 50.0]); + crate::flatten_params(&group, &mut |pr| pr.value.clone()) +} + +/// #1955: a Particle Playground cannon particle is born at the cannon's position during its +/// birth step, not at the cannon's position when the frame is rendered. +#[test] +fn cannon_particles_are_born_at_their_producer_positions() { + let p = pg_params(80.0); + let host = MovingCannon { index: 0, start_x: 20.0 }; + let env = EffectEnv { host: Some(&host), effect_index: 0, ..Default::default() }; + let ctx = EffectCtx { params: &p, time: 1.0, layer_size: [80.0, 60.0], seed: 11, adjustment: false, env }; + let parts = playground_state(&ctx).unwrap(); + let births = crate::psim::births(60.0, steps_at(1.0), 60_000).unwrap(); + assert!(parts.len() > 20, "{} particles", parts.len()); + for q in parts { + let step = births[q.id as usize] as f32; + assert!((q.p[0] - (20.0 + step)).abs() < 1e-4, "particle {} at {:?}, expected {}", q.id, q.p, 20.0 + step); + } +} + +/// The current cannon position is not part of the simulation key, but an earlier one is: a +/// checkpoint reached with another producer history is not reused. +#[test] +fn a_changed_cannon_history_drops_stale_checkpoints() { + let p = pg_params(80.0); + let state = |start_x| { + let host = MovingCannon { index: 0, start_x }; + let env = EffectEnv { host: Some(&host), effect_index: 0, ..Default::default() }; + let ctx = EffectCtx { params: &p, time: 1.0, layer_size: [80.0, 60.0], seed: 12, adjustment: false, env }; + playground_state(&ctx).unwrap().into_iter().next().unwrap().p[0] + }; + assert!((state(20.0) - 20.0).abs() < 1e-4, "{}", state(20.0)); + assert!((state(60.0) - 60.0).abs() < 1e-4, "{}", state(60.0)); +} + +/// The cannon's current position is not part of the simulation key, while its other cannon +/// parameters remain part of it. +#[test] +fn the_cannon_position_is_not_part_of_the_particle_playground_key() { + let p = pg_production_params(80.0); + fn ctx(p: &Params) -> EffectCtx<'_> { + EffectCtx { params: p, time: 1.0, layer_size: [80.0, 60.0], seed: 13, adjustment: false, env: EffectEnv::default() } + } + assert!(p.values.contains_key("#2/cannonPosition"), "production parameters have the positional alias"); + let mut moved = p.clone(); + moved.values.insert("cannon/cannonPosition".into(), Value::Vec2([120.0, 50.0])); + moved.values.insert("#2/cannonPosition".into(), Value::Vec2([120.0, 50.0])); + assert_eq!(pg_key(&ctx(&p)), pg_key(&ctx(&moved))); + moved.values.insert("cannon/barrelAngle".into(), num(10.0)); + moved.values.insert("#2/barrelAngle".into(), num(10.0)); + assert_ne!(pg_key(&ctx(&p)), pg_key(&ctx(&moved))); +} + +/// Moving the cannon only changes the position of particles born after the move; particles +/// that already exist keep their world-space trajectory. +#[test] +fn moving_the_cannon_does_not_move_existing_particles() { + let pg = Pg { cannon: true, rate: 60.0, vel: 60.0, ..bare(3) }; + let mut initial = PgState::default(); + pg.step_at(&mut initial, [10.0, 10.0]); + let mut moved = initial.clone(); + let mut unchanged = initial.clone(); + pg.step_at(&mut moved, [100.0, 10.0]); + pg.step_at(&mut unchanged, [10.0, 10.0]); + assert_eq!(moved.parts.len(), 2); + assert_eq!(unchanged.parts.len(), 2); + assert_eq!(moved.parts[0].id, unchanged.parts[0].id); + assert_eq!(moved.parts[0].p, unchanged.parts[0].p); + assert_eq!(moved.parts[0].v, unchanged.parts[0].v); + assert!((moved.parts[1].p[0] - 100.0).abs() < 1e-4, "{:?}", moved.parts[1].p); + assert!((unchanged.parts[1].p[0] - 10.0).abs() < 1e-4, "{:?}", unchanged.parts[1].p); +} + #[test] fn grid_falls_with_gravity_and_bounces_off_a_wall() { let grid = |t: f64, env: EffectEnv| { @@ -136,7 +255,6 @@ fn property_mapper_and_layer_map_read_layers() { fn bare(seed: u32) -> Pg { Pg { cannon: false, - pos: [0.0; 2], barrel_angle: 0.0, barrel_radius: 0.0, rate: 0.0, diff --git a/crates/effects/src/util.rs b/crates/effects/src/util.rs index 390750c6e..fc2465928 100644 --- a/crates/effects/src/util.rs +++ b/crates/effects/src/util.rs @@ -522,12 +522,44 @@ pub fn params_key(ctx: &crate::EffectCtx, b: &crate::Buf, salt: u64) -> u64 { params_key_except(ctx, b, salt, &[]) } +/// Whether a flattened parameter is one of the paths in `skip`. +/// +/// [`crate::flatten_params`] gives a grouped parameter both its canonical path (for example +/// `producer/position`) and a positional alias (for example `#1/position`). The aliases carry +/// the same value, so skipping only the canonical path would still let the current producer +/// position change a simulation key. Group metadata maps each alias back to its canonical path. +fn skipped_param(ctx: &crate::EffectCtx, id: &str, skip: &[&str]) -> bool { + if skip.iter().any(|s| id.starts_with(s)) { + return true; + } + if !id.contains('#') { + return false; + } + let mut canonical = String::new(); + let mut prefix = String::new(); + for part in id.split('/') { + let group = part.strip_prefix('#').filter(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())).and_then(|_| { + let metadata = format!("{prefix}{part}/@match"); + match ctx.params.values.get(&metadata) { + Some(crate::Value::Str(group)) => Some(group.as_str()), + _ => None, + } + }); + canonical.push_str(group.unwrap_or(part)); + canonical.push('/'); + prefix.push_str(part); + prefix.push('/'); + } + canonical.pop(); + skip.iter().any(|s| canonical.starts_with(s)) +} + /// [`params_key`] without the parameters whose ids start with one of `skip` (ones that only /// change how the simulation is viewed, so animating them doesn't restart it). pub fn params_key_except(ctx: &crate::EffectCtx, b: &crate::Buf, salt: u64, skip: &[&str]) -> u64 { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); - let mut keys: Vec<&String> = ctx.params.values.keys().filter(|k| !skip.iter().any(|s| k.starts_with(s))).collect(); + let mut keys: Vec<&String> = ctx.params.values.keys().filter(|k| !skipped_param(ctx, k, skip)).collect(); keys.sort(); for k in keys { k.hash(&mut h); diff --git a/crates/engine/src/tests/essential_more.rs b/crates/engine/src/tests/essential_more.rs index c87d36eec..4513f54db 100644 --- a/crates/engine/src/tests/essential_more.rs +++ b/crates/engine/src/tests/essential_more.rs @@ -306,8 +306,8 @@ fn instance_keys_stay_out_of_a_layer_that_blends_frames() { assert!(pr.keys.is_empty()); } -/// An override from a collapsed parent reaches the nested instance as a value only: the keys the -/// nested instance property carries itself must not be copied onto its own target. +/// A static override from a collapsed parent reaches the nested instance as a value only: the +/// keys the nested instance property carries itself must not be copied onto its own target. #[test] fn collapsed_parent_override_replaces_the_nested_instance_keys() { let mut s = Session::default(); @@ -338,3 +338,109 @@ fn collapsed_parent_override_replaces_the_nested_instance_keys() { assert!((over[0].value.as_f64() - 80.0).abs() < 1e-6, "value {:?}", over[0].value); assert!(over[0].keys.is_empty(), "the nested instance's own keys are stale"); } + +/// Top → Mid → Inner, with a keyed Essential override on the Top instance. The Inner target is +/// `target`; the Mid instance is `nested`. `time_remap` makes the nested source time differ from +/// the Mid instance's layer time. +fn collapsed_parent_scene(time_remap: bool) -> (Session, effectcraft_project::ItemId, effectcraft_project::ItemId, u64, u64, u64) { + let mut s = Session::default(); + s.execute("comp.new", json!({"name": "Inner", "width": 32, "height": 32, "frameRate": 30, "duration": 4})).unwrap(); + let target = s.execute("layer.newSolid", json!({"name": "A", "color": "#ffffff"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("essential.addProperty", json!({"layer": target, "path": "transform/opacity"})).unwrap(); + s.execute("comp.new", json!({"name": "Mid", "width": 32, "height": 32, "frameRate": 30, "duration": 4})).unwrap(); + let mid = s.active_comp_id().unwrap(); + let inner = s.project.find_by_name("Inner").unwrap().id; + let nested = s.execute("layer.addItem", json!({"item": inner.0, "time": 0.0})).unwrap()["layer"].as_u64().unwrap(); + let nested_path = s.execute("essential.instance", json!({"layer": nested})).unwrap()["controls"][0]["path"].as_str().unwrap().to_string(); + s.execute("prop.addKey", json!({"layer": nested, "path": nested_path, "time": 0.0, "value": 0.0})).unwrap(); + s.execute("prop.addKey", json!({"layer": nested, "path": nested_path, "time": 1.0, "value": 100.0})).unwrap(); + let ctl = s.execute("essential.addProperty", json!({"layer": nested, "path": nested_path})).unwrap()["controls"][0].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layers": [nested], "switch": "collapse", "value": true})).unwrap(); + if time_remap { + s.execute("layer.enableTimeRemap", json!({"layers": [nested]})).unwrap(); + } + s.execute("comp.new", json!({"name": "Top", "width": 32, "height": 32, "frameRate": 30, "duration": 4})).unwrap(); + let top = s.active_comp_id().unwrap(); + let inst = s.execute("layer.addItem", json!({"item": mid.0, "time": 0.0})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layers": [inst], "switch": "collapse", "value": true})).unwrap(); + let controls = s.execute("essential.instance", json!({"layer": inst})).unwrap()["controls"].clone(); + let top_path = controls.as_array().unwrap().iter().find(|c| c["control"].as_u64() == Some(ctl)).unwrap()["path"].as_str().unwrap().to_string(); + s.execute("prop.addKey", json!({"layer": inst, "path": top_path, "time": 0.0, "value": 10.0})).unwrap(); + s.execute("prop.addKey", json!({"layer": inst, "path": top_path, "time": 1.0, "value": 90.0})).unwrap(); + (s, top, inner, target, nested, inst) +} + +/// A keyed override from a collapsed parent replaces the nested instance's own history with the +/// parent's, so the nested target can still sample the producer at its birth times. +#[test] +fn a_collapsed_parent_keeps_its_override_history_for_the_nested_instance() { + use effectcraft_project::LayerId; + + let (mut s, top, inner, target, nested, inst) = collapsed_parent_scene(false); + // The Inner target starts late and is stretched: the parent's source-time keys must be moved + // into this target's own layer time. + { + let layer = std::sync::Arc::make_mut(&mut s.project).comp_mut(inner).unwrap().layer_mut(LayerId(target)).unwrap(); + layer.start_time = Tick::from_seconds_f64(0.5); + layer.stretch = 125.0; + } + + let r = effectcraft_render::Renderer::new(&s.project, &*s.footage, crate::render::RenderOpts::default()); + let ctx = effectcraft_render::EvalCtx::new(&s.project, top, s.project.comp(top).unwrap(), Tick::from_seconds_f64(0.25)); + let layer = ctx.comp.layer(LayerId(inst)).unwrap(); + let collapsed = r.collapsed(&ctx, layer).expect("the instance collapses"); + let (_, nctx) = r.collapse_into(&ctx, layer, &collapsed, 1.0).expect("a nested context"); + let nl = nctx.comp.layer(LayerId(nested)).unwrap(); + let over = effectcraft_render::essential_overrides(&nctx, nl); + assert_eq!(over.len(), 1); + assert!((over[0].value.as_f64() - 30.0).abs() < 1e-6, "value {:?}", over[0].value); + assert_eq!(over[0].keys.len(), 2, "the parent's history reaches the nested target"); + assert_eq!(over[0].keys[0].value, KV::Scalar(10.0)); + assert_eq!(over[0].keys[1].value, KV::Scalar(90.0)); + + // The flattened path puts source times 0 and 1 at -0.4 and 0.4 in the target's layer time. + let flat = essential::with_overrides(&s.project, inner, &over).unwrap(); + let flat_target = flat.comp(inner).unwrap().layer(LayerId(target)).unwrap(); + let flat_prop = flat_target.props.prop("transform/opacity").unwrap(); + assert_eq!(flat_prop.keys[0].time, Tick::from_seconds_f64(-0.4)); + assert_eq!(flat_prop.keys[1].time, Tick::from_seconds_f64(0.4)); + + // The collapsed path reads the same values at those exact target-layer times. + let nested_collapsed = r.collapsed(&nctx, nl).expect("the nested instance collapses"); + let (_, target_ctx) = r.collapse_into(&nctx, nl, &nested_collapsed, 1.0).expect("the target context"); + let target_layer = target_ctx.comp.layer(LayerId(target)).unwrap(); + let target_prop = target_layer.props.prop("transform/opacity").unwrap(); + assert_eq!(target_ctx.value_at_layer_time(target_layer, target_prop, Tick::from_seconds_f64(-0.4)), KV::Scalar(10.0)); + assert_eq!(target_ctx.value_at_layer_time(target_layer, target_prop, Tick::from_seconds_f64(0.4)), KV::Scalar(90.0)); +} + +/// A remapped nested source has a different time domain, so its inherited history stays out just +/// as it does on the flattened path. Both paths use the same current value. +#[test] +fn a_remapped_nested_instance_drops_inherited_history_consistently() { + use effectcraft_project::LayerId; + + let (s, top, inner, target, nested, inst) = collapsed_parent_scene(true); + let r = effectcraft_render::Renderer::new(&s.project, &*s.footage, crate::render::RenderOpts::default()); + let ctx = effectcraft_render::EvalCtx::new(&s.project, top, s.project.comp(top).unwrap(), Tick::from_seconds_f64(0.25)); + let layer = ctx.comp.layer(LayerId(inst)).unwrap(); + let collapsed = r.collapsed(&ctx, layer).expect("the instance collapses"); + let (_, nctx) = r.collapse_into(&ctx, layer, &collapsed, 1.0).expect("a nested context"); + let nl = nctx.comp.layer(LayerId(nested)).unwrap(); + let over = effectcraft_render::essential_overrides(&nctx, nl); + assert_eq!(over.len(), 1); + assert!(over[0].keys.is_empty(), "the remapped source has no usable inherited history"); + + let flat = essential::with_overrides(&s.project, inner, &over).unwrap(); + let flat_target = flat.comp(inner).unwrap().layer(LayerId(target)).unwrap(); + let flat_prop = flat_target.props.prop("transform/opacity").unwrap(); + let flat_ctx = effectcraft_render::EvalCtx::new(&flat, inner, flat.comp(inner).unwrap(), Tick::from_seconds_f64(0.25)); + let flat_value = flat_ctx.value(flat_target, flat_prop); + + let nested_collapsed = r.collapsed(&nctx, nl).expect("the nested instance collapses"); + let (_, target_ctx) = r.collapse_into(&nctx, nl, &nested_collapsed, 1.0).expect("the target context"); + let target_layer = target_ctx.comp.layer(LayerId(target)).unwrap(); + let target_prop = target_layer.props.prop("transform/opacity").unwrap(); + let collapsed_value = target_ctx.value(target_layer, target_prop); + assert_eq!(collapsed_value, flat_value); +} diff --git a/crates/expr/src/host.rs b/crates/expr/src/host.rs index 90ef00c4a..cc340988d 100644 --- a/crates/expr/src/host.rs +++ b/crates/expr/src/host.rs @@ -469,8 +469,10 @@ impl<'a> Resolver<'a> { Req::PropInfo { comp, layer, path } => { let (l, p) = self.prop(*comp, *layer, path)?; let dims = prop_dims(l, p); - let times = p.keys.iter().map(|k| Resp::Num(l.comp_time(k.time).seconds())).collect(); - let values = p.keys.iter().map(|k| value_resp(&k.value, dims)).collect(); + let ctx = self.ctx_at(*comp, self.ctx.time.seconds())?; + let effective = ctx.effective_property(l, p); + let times = effective.keys.iter().map(|k| Resp::Num(l.comp_time(k.time).seconds())).collect(); + let values = effective.keys.iter().map(|k| value_resp(&k.value, dims)).collect(); let index = path.rsplit('/').next().and_then(|last| { let parent = path.rsplit_once('/').map(|(g, _)| g); let g = match parent { @@ -497,13 +499,15 @@ impl<'a> Resolver<'a> { Req::Value { comp, layer, path, t, pre } => { let (l, p) = self.prop(*comp, *layer, path)?; let t = f64::from_bits(*t); - let v = if *pre { p.value_at(l.layer_time(Tick::from_seconds_f64(t))) } else { self.ctx_at(*comp, t)?.value(l, p) }; + let ctx = self.ctx_at(*comp, t)?; + let v = if *pre { ctx.effective_property(l, p).value_at(l.layer_time(Tick::from_seconds_f64(t))) } else { ctx.value(l, p) }; value_resp(&v, prop_dims(l, p)) } Req::Doc { comp, layer, path, t, pre } => { let (l, p) = self.prop(*comp, *layer, path)?; let t = f64::from_bits(*t); - let v = if *pre { p.value_at(l.layer_time(Tick::from_seconds_f64(t))) } else { self.ctx_at(*comp, t)?.value(l, p) }; + let ctx = self.ctx_at(*comp, t)?; + let v = if *pre { ctx.effective_property(l, p).value_at(l.layer_time(Tick::from_seconds_f64(t))) } else { ctx.value(l, p) }; match v { Value::Text(d) => Resp::Str(doc_json(&d)), Value::Str(s) => Resp::Str(doc_json(&effectcraft_keyframe::TextDoc::plain(&s))), diff --git a/crates/expr/src/tests.rs b/crates/expr/src/tests.rs index dafb52e6a..c36598d77 100644 --- a/crates/expr/src/tests.rs +++ b/crates/expr/src/tests.rs @@ -1974,6 +1974,75 @@ fn a_layer_parameters_own_expression_reads_its_layer() { } } +#[test] +fn a_collapsed_essential_override_is_the_history_an_expression_reads() { + use effectcraft_project::essential::{self, EgControl, EgKind, EssentialGraphics}; + use effectcraft_project::{Expression, GroupKind}; + + let mut p = Project::default(); + let mut inner = Comp::new(64, 32, FrameRate::FPS_30, Tick::from_seconds_f64(2.0)); + let mut target = solid(&mut p, &inner, "Target", [1.0, 1.0, 1.0], 64, 32); + let opacity = target.props.prop_mut(OPA).unwrap(); + opacity.keys = vec![Keyframe::new(secs(0.0), Value::Scalar(0.0)), Keyframe::new(secs(1.0), Value::Scalar(100.0))]; + opacity.expr = Some(Expression { + text: "thisProperty.valueAtTime(0) + thisProperty.numKeys + thisProperty.key(1).value + thisProperty.nearestKey(0.9).value".into(), + enabled: true, + }); + let target_id = target.id; + let opacity_id = opacity.uid; + inner.layers = vec![target].into(); + inner.essential = Some(EssentialGraphics { + controls: vec![EgControl { + id: 1, + name: "Opacity".into(), + kind: EgKind::Property { layer: target_id, prop: opacity_id, links: vec![] }, + as_type: None, + }], + ..Default::default() + }); + let inner_id = p.add_item("Inner", Label::Sandstone, None, ItemKind::Comp(inner.into())); + + let mut outer = Comp::new(64, 32, FrameRate::FPS_30, Tick::from_seconds_f64(2.0)); + let mut instance = build::layer(&mut p, &outer, "Inner", LayerSource::Comp { item: inner_id }, (64, 32), None); + let mut next = p.next_id; + let mut ids = Ids(&mut next); + let mut control = ids.prop(&essential::match_id(1), "Opacity", Value::Scalar(20.0)); + control.keys = vec![Keyframe::new(secs(0.0), Value::Scalar(20.0)), Keyframe::new(secs(1.0), Value::Scalar(80.0))]; + let mut group = ids.group(essential::GROUP, "Essential Properties"); + group.kind = GroupKind::Essential { overridden: vec![control.uid] }; + group.children.push(control.into()); + instance.props.children.push(group.into()); + p.next_id = next; + instance.switches.collapse = true; + outer.layers = vec![instance].into(); + let outer_id = p.add_item("Outer", Label::Sandstone, None, ItemKind::Comp(outer.into())); + + // The flattened path replaces the target property's keys with the instance override's. + let ctx = EvalCtx::new(&p, outer_id, p.comp(outer_id).unwrap(), secs(0.25)); + let outer_layer = &ctx.comp.layers[0]; + let overrides = effectcraft_render::essential_overrides(&ctx, outer_layer); + let flat = essential::with_overrides(&p, inner_id, &overrides).unwrap(); + let mut flat_ctx = EvalCtx::new(&flat, inner_id, flat.comp(inner_id).unwrap(), secs(0.25)); + flat_ctx.expr = Some(&Expressions); + let flat_target = flat_ctx.comp.layer(target_id).unwrap(); + let flat_value = flat_ctx.value(flat_target, flat_target.props.prop(OPA).unwrap()).as_f64(); + + // The collapsed path carries the same history in its override. An expression on the target + // reads that effective history, just as it does on the flattened path. + let mut r = Renderer::new(&p, &NoFootage, RenderOpts::default()); + r.expr = Some(&Expressions); + let mut collapsed_ctx = EvalCtx::new(&p, outer_id, p.comp(outer_id).unwrap(), secs(0.25)); + collapsed_ctx.expr = Some(&Expressions); + let outer_layer = &collapsed_ctx.comp.layers[0]; + let collapsed = r.collapsed(&collapsed_ctx, outer_layer).expect("the precomp collapses"); + let (_, nested_ctx) = r.collapse_into(&collapsed_ctx, outer_layer, &collapsed, 1.0).unwrap(); + let nested_target = nested_ctx.comp.layer(target_id).unwrap(); + let collapsed_value = nested_ctx.value(nested_target, nested_target.props.prop(OPA).unwrap()).as_f64(); + + assert_close!(flat_value, 122.0); + assert_close!(collapsed_value, flat_value); +} + #[test] fn time_to_frames_rounds_durations_away_from_zero() { let f = fx(); diff --git a/crates/gpu/src/particles.rs b/crates/gpu/src/particles.rs index 9ac103557..07435f893 100644 --- a/crates/gpu/src/particles.rs +++ b/crates/gpu/src/particles.rs @@ -5,7 +5,7 @@ use std::sync::{Mutex, OnceLock}; -use effectcraft_effects::psim::{ParticleSystem, SimParticle, SimRequest}; +use effectcraft_effects::psim::{ParticleSystem, SimParticle, SimRequest, producer_prefixes}; use crate::context::GpuContext; @@ -25,6 +25,8 @@ struct Checkpoint { n: u32, /// The birth steps of its particles (see [`born`]). born: u64, + /// Fingerprint of the producer history that reached this checkpoint. + producer: u64, buf: wgpu::Buffer, used: u64, } @@ -74,6 +76,7 @@ fn pipes(g: &GpuContext) -> &Pipes { buffer(1, wgpu::BufferBindingType::Storage { read_only: true }), buffer(2, wgpu::BufferBindingType::Storage { read_only: true }), buffer(3, wgpu::BufferBindingType::Storage { read_only: false }), + buffer(4, wgpu::BufferBindingType::Storage { read_only: true }), ], }); let layout = d.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { @@ -93,6 +96,18 @@ fn pipes(g: &GpuContext) -> &Pipes { }) } +/// Producer positions packed for the shader's `vec4` storage buffer. +fn packed_producers(producers: &[[f32; 3]]) -> Vec { + let mut out = Vec::new(); + for position in producers { + out.extend_from_slice(&position[0].to_le_bytes()); + out.extend_from_slice(&position[1].to_le_bytes()); + out.extend_from_slice(&position[2].to_le_bytes()); + out.extend_from_slice(&0.0f32.to_le_bytes()); + } + out +} + /// The shader's parameter block. fn uniforms(req: &SimRequest, n: u32, s0: u64, prev_n: u32) -> Vec { let dt = (1.0 / effectcraft_effects::psim::SPS) as f32; @@ -103,8 +118,7 @@ fn uniforms(req: &SimRequest, n: u32, s0: u64, prev_n: u32) -> Vec { ParticleSystem::Engine(e) => { u2 = [e.anim, e.flat as u32, e.seed, prev_n]; f[0] = [e.life, e.speed, e.extra, e.cone]; - f[1] = [e.producer[0], e.producer[1], e.producer[2], 0.0]; - f[2] = [e.radius[0], e.radius[1], e.radius[2], 0.0]; + f[1] = [e.radius[0], e.radius[1], e.radius[2], 0.0]; f[3] = [e.gravity[0], e.gravity[1], e.gravity[2], 0.0]; f[4] = [e.axis[0], e.axis[1], e.axis[2], 0.0]; f[5] = [e.damp, dt, 0.0, 0.0]; @@ -112,9 +126,9 @@ fn uniforms(req: &SimRequest, n: u32, s0: u64, prev_n: u32) -> Vec { ParticleSystem::Cannon(c) => { u[3] = 1; u2 = [0, 1, c.seed, prev_n]; - f[0] = [c.pos[0], c.pos[1], c.barrel_angle, c.barrel_radius]; - f[1] = [c.dir_spread, c.vel, c.vel_spread, c.grav_spread]; - f[2] = [c.gravity[0], c.gravity[1], dt, 0.0]; + f[0] = [c.barrel_angle, c.barrel_radius, c.dir_spread, c.vel]; + f[1] = [c.vel_spread, c.grav_spread, dt, 0.0]; + f[2] = [c.gravity[0], c.gravity[1], 0.0, 0.0]; f[3] = c.bounds; } } @@ -141,10 +155,24 @@ pub(crate) fn simulate(g: &GpuContext, req: &SimRequest) -> Option u32::MAX as u64 { return None; } - let n = req.births.len() as u32; + let n = u32::try_from(req.births.len()).ok()?; if n == 0 { return Some(vec![]); } + let steps = usize::try_from(req.steps).ok()?; + if steps == 0 { + return None; + } + if req.producers.len() < steps { + return None; + } + // Check the storage-buffer size before allocating the history fingerprint or its bytes. + let producer_size = steps.checked_mul(16)?; + if u64::try_from(producer_size).ok()? > g.device.limits().max_storage_buffer_binding_size { + return None; + } + let producers = &req.producers[..steps]; + let producer_prefix = producer_prefixes(producers); let deferred = g.deferred.clone(); let key = deferred.as_ref().map(|_| sim_key(req)); if let (Some(d), Some(k)) = (&deferred, key) { @@ -167,7 +195,17 @@ pub(crate) fn simulate(g: &GpuContext, req: &SimRequest) -> Option { k.used = now; (k.steps, Some(k.buf.clone()), k.n) @@ -178,6 +216,8 @@ pub(crate) fn simulate(g: &GpuContext, req: &SimRequest) -> Option = req.births.iter().flat_map(|b| b.to_le_bytes()).collect(); let births = g.buffer_init(Some("births"), &births, wgpu::BufferUsages::STORAGE); + let producer_bytes = packed_producers(producers); + let producers = g.buffer_init(Some("particle producers"), &producer_bytes, wgpu::BufferUsages::STORAGE); let prev = prev.unwrap_or_else(|| { d.create_buffer(&wgpu::BufferDescriptor { label: Some("particles"), size: STATE_BYTES, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false }) }); @@ -196,6 +236,7 @@ pub(crate) fn simulate(g: &GpuContext, req: &SimRequest) -> Option Option u128 { k.u64(req.steps); k.u64(req.births.len() as u64); k.bytes(&req.births.iter().flat_map(|b| b.to_le_bytes()).collect::>()); + let producer_count = usize::try_from(req.steps).ok().and_then(|steps| req.producers.get(..steps)).map_or(0, |producers| producers.len()); + k.u64(producer_count as u64); + k.bytes(&packed_producers(req.producers.get(..producer_count).unwrap_or(&[]))); k.debug(&req.system); k.finish() } @@ -256,12 +300,13 @@ fn parse(bytes: &[u8]) -> Vec { } /// Keep a simulated state on the GPU as a checkpoint (the oldest go beyond the limit). -fn keep_checkpoint(g: &GpuContext, req: &SimRequest, n: u32, next: wgpu::Buffer) { +fn keep_checkpoint(g: &GpuContext, req: &SimRequest, n: u32, next: wgpu::Buffer, producer_prefix: &[u64]) { if let Ok(mut c) = g.particle_states.lock() { let now = c.clock; c.list.retain(|k| !(k.key == req.key && k.steps == req.steps)); let (_, h) = born(req.births, req.steps); - c.list.push(Checkpoint { key: req.key, steps: req.steps, n, born: h, buf: next, used: now }); + let producer = producer_prefix.get(req.steps as usize).copied().unwrap_or(0); + c.list.push(Checkpoint { key: req.key, steps: req.steps, n, born: h, producer, buf: next, used: now }); while c.list.len() > CHECKPOINTS { let Some(i) = c.list.iter().enumerate().min_by_key(|(_, k)| k.used).map(|(i, _)| i) else { break }; c.list.remove(i); diff --git a/crates/gpu/src/shaders/particles.wgsl b/crates/gpu/src/shaders/particles.wgsl index ac12b8fc7..59646e761 100644 --- a/crates/gpu/src/shaders/particles.wgsl +++ b/crates/gpu/src/shaders/particles.wgsl @@ -9,10 +9,10 @@ struct PSim { u: vec4, // Animation, flat, seed, particles in `prev`. u2: vec4, - // Engine: f[0] = (life, speed, extra, cone), f[1] = producer, f[2] = radius, - // f[3] = gravity, f[4] = axis, f[5] = (damp, dt). - // Cannon: f[0] = (pos.x, pos.y, barrel angle, barrel radius), f[1] = (dir spread, vel, - // vel spread, grav spread), f[2] = (gravity.x, gravity.y, dt), f[3] = bounds. + // Engine: f[0] = (life, speed, extra, cone), f[1] = radius, f[3] = gravity, + // f[4] = axis, f[5] = (damp, dt). + // Cannon: f[0] = (barrel angle, barrel radius, dir spread, vel), f[1] = (vel spread, + // grav spread, dt), f[2] = (gravity.x, gravity.y), f[3] = bounds. f: array, 6>, } @@ -29,6 +29,8 @@ struct PState { @group(1) @binding(1) var births: array; @group(1) @binding(2) var prev: array; @group(1) @binding(3) var next: array; +// Producer position at each simulated step, in the system's own coordinates. +@group(1) @binding(4) var producers: array>; const PS_TAU: f32 = 6.2831855; @@ -70,11 +72,11 @@ struct Part { } // sim::Phys::spawn (+ the step's sub-step birth offset). -fn ps_spawn_engine(id: u32) -> Part { +fn ps_spawn_engine(id: u32, birth: u32) -> Part { let flat = S.u2.y != 0u; let anim = S.u2.x; - let producer = S.f[1].xyz; - let radius = S.f[2].xyz; + let producer = producers[birth].xyz; + let radius = S.f[1].xyz; let u = ps_rand_dir(id, 1u, flat); var e = 1.0 / 3.0; if (flat) { @@ -129,7 +131,7 @@ fn ps_step_engine(q: Part, j: u32) -> Part { let seed = S.u2.z; let dt = S.f[5].y; let t = f32(j) * dt; - let producer = S.f[1].xyz; + let producer = producers[j].xyz; let gravity = S.f[3].xyz; let extra = S.f[0].z; var a = gravity; @@ -181,13 +183,13 @@ fn ps_step_engine(q: Part, j: u32) -> Part { } // sim3::Pg::spawn (+ the sub-step birth offset). -fn ps_spawn_cannon(id: u32) -> Part { - let pos = S.f[0].xy; - let angle = S.f[0].z; - let r = S.f[0].w; - let spread = S.f[1].x; - let vel = S.f[1].y; - let vel_spread = S.f[1].z; +fn ps_spawn_cannon(id: u32, birth: u32) -> Part { + let pos = producers[birth].xy; + let angle = S.f[0].x; + let r = S.f[0].y; + let spread = S.f[0].z; + let vel = S.f[0].w; + let vel_spread = S.f[1].x; let a = radians(angle + ps_hs(id, 1u) * spread * 0.5); let d = vec2(sin_p(a), -cos_p(a)); let speed = max(vel + ps_hs(id, 3u) * vel_spread, 0.0); @@ -200,7 +202,7 @@ fn ps_spawn_cannon(id: u32) -> Part { off = vec2(cos_p(aa) * rr, sin_p(aa) * rr); } let v = d * speed; - let dt = S.f[2].z; + let dt = S.f[1].z; let frac = ps_h(id, 9u) * dt; let p = pos + off + v * frac; return Part(vec3(p, 0.0), vec3(v, 0.0), 0.0, 0.0, 0.0); @@ -208,8 +210,8 @@ fn ps_spawn_cannon(id: u32) -> Part { // sim3::Pg::step for one particle (gravity only); returns false when it leaves the bounds. fn ps_step_cannon(q: ptr, id: u32) -> bool { - let dt = S.f[2].z; - let spread = S.f[1].w; + let dt = S.f[1].z; + let spread = S.f[1].y; var g = 1.0; if (spread > 0.0) { g = 1.0 + (ps_h(id, 7u) * 2.0 - 1.0) * spread; @@ -245,9 +247,9 @@ fn particles(@builtin(global_invocation_id) gid: vec3) { j = s0; } else { if (cannon) { - q = ps_spawn_cannon(id); + q = ps_spawn_cannon(id, b); } else { - q = ps_spawn_engine(id); + q = ps_spawn_engine(id, b); } j = b + 1u; } diff --git a/crates/gpu/src/tests/deferred_jobs.rs b/crates/gpu/src/tests/deferred_jobs.rs index 7e5edbedd..b755642b5 100644 --- a/crates/gpu/src/tests/deferred_jobs.rs +++ b/crates/gpu/src/tests/deferred_jobs.rs @@ -3,6 +3,7 @@ //! passes; and the job loops' pass driver (`effectcraft_render::passes`) settles natively. use effectcraft_effects::EffectCtx; +use effectcraft_effects::psim::{EngineDesc, ParticleSim, ParticleSystem, SimRequest}; use effectcraft_project::BitDepth; use effectcraft_render::three_d::adv; use effectcraft_render::{Accelerator, Backend, LayerCache, NoFootage, RenderOpts, Renderer}; @@ -47,6 +48,46 @@ fn particles_resolve_in_passes() { } } +/// The deferred readback key includes the producer history: a request with a different history +/// starts its own readback instead of returning the previous history's particles. +#[test] +fn particle_producer_history_is_part_of_the_deferred_key() { + let Some((g, _lock)) = deferred_gpu() else { return }; + let system = ParticleSystem::Engine(EngineDesc { + life: 10.0, + radius: [0.0; 3], + anim: 0, + speed: 0.0, + gravity: [0.0; 3], + axis: [0.0, -1.0, 0.0], + extra: 0.0, + cone: 0.0, + damp: 1.0, + seed: 51, + flat: true, + }); + let births = [0u32]; + let first_producers = [[10.0, 0.0, 0.0]]; + let first = SimRequest { key: 0x1955_0def, steps: 1, births: &births, producers: &first_producers, system }; + g.frame_begin(); + g.pass_begin(); + assert!(g.simulate(&first).unwrap().is_empty() && g.pass_missed(), "the first readback starts"); + settle(g); + g.pass_begin(); + let ready = g.simulate(&first).unwrap(); + assert!(!ready.is_empty() && !g.pass_missed(), "the first readback is ready"); + assert!((ready[0].p[0] - 10.0).abs() < 1e-4, "{:?}", ready[0].p); + + let changed_producers = [[99.0, 0.0, 0.0]]; + let changed = SimRequest { key: first.key, steps: 1, births: &births, producers: &changed_producers, system }; + g.pass_begin(); + assert!(g.simulate(&changed).unwrap().is_empty() && g.pass_missed(), "the producer history was not part of the deferred key"); + settle(g); + g.pass_begin(); + let changed = g.simulate(&changed).unwrap(); + assert!(!changed.is_empty() && (changed[0].p[0] - 99.0).abs() < 1e-4, "{:?}", changed[0].p); +} + #[test] fn advanced_3d_resolves_in_passes() { let Some((g, _lock)) = deferred_gpu() else { return }; diff --git a/crates/gpu/src/tests/particles.rs b/crates/gpu/src/tests/particles.rs index e11dd6585..e4ca79d69 100644 --- a/crates/gpu/src/tests/particles.rs +++ b/crates/gpu/src/tests/particles.rs @@ -3,7 +3,7 @@ //! ids) at positions within tolerance, from scratch and when advancing / seeking from GPU //! checkpoints. -use effectcraft_effects::psim::{ParticleSim, SimParticle}; +use effectcraft_effects::psim::{EngineDesc, ParticleSim, ParticleSystem, SimParticle, SimRequest}; use effectcraft_effects::{EffectCtx, EffectEnv, EffectHost, LayerPixels, Params}; use effectcraft_keyframe::Value; @@ -24,6 +24,39 @@ impl EffectHost for Host { } } +/// A host whose producer moves from `start_x` at layer time 0 to `start_x + 60 · t`. +struct MovingProducer { + gpu: Option<&'static Gpu>, + index: usize, + start_x: f64, +} + +impl EffectHost for MovingProducer { + fn layer(&self, _id: u64, _masks_and_effects: bool) -> Option { + None + } + fn audio(&self, _id: u64, _start: f64, _frames: usize, _rate: u32) -> Option> { + None + } + fn particles(&self) -> Option<&dyn ParticleSim> { + self.gpu.map(|g| g as &dyn ParticleSim) + } + fn param_at(&self, effect_index: usize, id: &str, t: f64) -> Option { + if effect_index != self.index { + return None; + } + let x = self.start_x + 60.0 * t; + match id { + "producer/position" | "producer" => Some(Value::Vec2([x, 50.0])), + "producer/producerX" => Some(n(x)), + "producer/producerY" => Some(n(50.0)), + "producer/producerZ" => Some(n(0.0)), + "cannon/cannonPosition" => Some(Value::Vec2([x, 50.0])), + _ => None, + } + } +} + pub(crate) fn params(id: &str, vals: &[(&str, Value)]) -> Params { let spec = effectcraft_effects::find(id).unwrap(); let size = [320.0, 240.0]; @@ -179,6 +212,111 @@ fn particle_systems_ii_matches_the_cpu() { } } +/// #1955: a moving producer is sampled at every simulation step on both the CPU and the GPU. +#[test] +fn moving_producers_match_the_cpu_on_the_gpu() { + let Some(g) = gpu() else { return }; + for id in ["ec.sim.ccparticleworld", "ec.sim.ccparticlesystems2"] { + let p = if id == "ec.sim.ccparticleworld" { + params( + id, + &[ + ("birthRate", n(2.0)), + ("longevity", n(5.0)), + ("producer/producerX", n(80.0)), + ("producer/producerY", n(50.0)), + ("producer/producerZ", n(0.0)), + ("producer/radiusX", n(0.0)), + ("producer/radiusY", n(0.0)), + ("producer/radiusZ", n(0.0)), + ("physics/animation", Value::Enum(4)), + ("physics/velocity", n(0.0)), + ("physics/gravity", n(0.0)), + ], + ) + } else { + params( + id, + &[ + ("birthRate", n(2.0)), + ("longevity", n(5.0)), + ("producer/position", Value::Vec2([80.0, 50.0])), + ("producer/radiusX", n(0.0)), + ("producer/radiusY", n(0.0)), + ("physics/animation", Value::Enum(5)), + ("physics/velocity", n(0.0)), + ("physics/gravity", n(0.0)), + ], + ) + }; + let cpu_host = MovingProducer { gpu: None, index: 0, start_x: 20.0 }; + let gpu_host = MovingProducer { gpu: Some(g), index: 0, start_x: 20.0 }; + let ctx = |env| EffectCtx { params: &p, time: 1.0, layer_size: [320.0, 240.0], seed: 31, adjustment: false, env }; + let cpu = effectcraft_effects::particle_state(id, &ctx(EffectEnv { host: Some(&cpu_host), ..Default::default() })).unwrap(); + let before = crate::particles::DISPATCHES.load(std::sync::atomic::Ordering::Relaxed); + let gpu = effectcraft_effects::particle_state(id, &ctx(EffectEnv { host: Some(&gpu_host), ..Default::default() })).unwrap(); + assert!(crate::particles::DISPATCHES.load(std::sync::atomic::Ordering::Relaxed) > before, "{id}: simulated on the GPU"); + agree(&format!("{id} moving producer"), &cpu, &gpu, 1e-4, cpu.len() / 100 + 1); + } + + let p = params( + "ec.sim.particleplayground", + &[ + ("cannonEnabled", Value::Bool(true)), + ("grid/particlesAcross", n(0.0)), + ("grid/particlesDown", n(0.0)), + ("cannon/barrelRadius", n(0.0)), + ("cannon/particlesPerSecond", n(60.0)), + ("cannon/velocity", n(0.0)), + ("cannon/velocityRandomSpread", n(0.0)), + ("gravity/gravityForce", n(0.0)), + ], + ); + let cpu_host = MovingProducer { gpu: None, index: 0, start_x: 20.0 }; + let gpu_host = MovingProducer { gpu: Some(g), index: 0, start_x: 20.0 }; + let ctx = |env| EffectCtx { params: &p, time: 1.0, layer_size: [320.0, 240.0], seed: 32, adjustment: false, env }; + let cpu = effectcraft_effects::playground_state(&ctx(EffectEnv { host: Some(&cpu_host), ..Default::default() })).unwrap(); + let before = crate::particles::DISPATCHES.load(std::sync::atomic::Ordering::Relaxed); + let gpu = effectcraft_effects::playground_state(&ctx(EffectEnv { host: Some(&gpu_host), ..Default::default() })).unwrap(); + assert!(crate::particles::DISPATCHES.load(std::sync::atomic::Ordering::Relaxed) > before, "particle playground: simulated on the GPU"); + agree("particle playground moving producer", &cpu, &gpu, 1e-4, cpu.len() / 100 + 1); + let births = effectcraft_effects::psim::births(60.0, 60, 60_000).unwrap(); + for q in &gpu { + let birth = births[q.id as usize] as f32; + assert!((q.p[0] - (20.0 + birth)).abs() < 1e-4, "particle {} at {:?}, expected {}", q.id, q.p, 20.0 + birth); + } +} + +/// A checkpoint reached with one producer history is not reused for another history, even +/// when the current producer position and the system's key are unchanged. +#[test] +fn a_changed_gpu_producer_history_drops_a_stale_checkpoint() { + let Some(g) = gpu() else { return }; + let system = ParticleSystem::Engine(EngineDesc { + life: 10.0, + radius: [0.0; 3], + anim: 0, + speed: 0.0, + gravity: [0.0; 3], + axis: [0.0, -1.0, 0.0], + extra: 0.0, + cone: 0.0, + damp: 1.0, + seed: 41, + flat: true, + }); + let births_one = [0u32]; + let producers_one = [[10.0, 0.0, 0.0]]; + let first = g.simulate(&SimRequest { key: 0x1955, steps: 1, births: &births_one, producers: &producers_one, system }).unwrap(); + assert!((first[0].p[0] - 10.0).abs() < 1e-4, "{:?}", first[0].p); + + let births_two = [0u32, 1u32]; + let producers_two = [[99.0, 0.0, 0.0], [20.0, 0.0, 0.0]]; + let second = g.simulate(&SimRequest { key: 0x1955, steps: 2, births: &births_two, producers: &producers_two, system }).unwrap(); + assert!((second[0].p[0] - 99.0).abs() < 1e-4, "the old checkpoint was reused: {:?}", second[0].p); + assert!((second[1].p[0] - 20.0).abs() < 1e-4, "{:?}", second[1].p); +} + #[test] fn playground_cannon_matches_the_cpu_and_checkpoints_reuse() { let Some(g) = gpu() else { return }; diff --git a/crates/project/src/essential.rs b/crates/project/src/essential.rs index cc3b12209..ee7acaa9c 100644 --- a/crates/project/src/essential.rs +++ b/crates/project/src/essential.rs @@ -650,7 +650,7 @@ pub fn sync_project(before: &Project, after: &mut Project) { /// Keys given in comp time, in the time of a layer that starts at `start` and is stretched to /// `stretch` percent. Empty when the stretch is not a usable factor. -fn keys_in_layer_time(keys: &[Keyframe], start: Tick, stretch: f64) -> Vec { +pub fn keys_in_layer_time(keys: &[Keyframe], start: Tick, stretch: f64) -> Vec { if stretch.is_finite() && stretch > 0.0 { keys.iter().map(|k| key_in_layer_time(k, start, stretch)).collect() } else { vec![] } } diff --git a/crates/render/src/cache.rs b/crates/render/src/cache.rs index 06ed04b75..f8aba34b4 100644 --- a/crates/render/src/cache.rs +++ b/crates/render/src/cache.rs @@ -723,15 +723,22 @@ fn hash_blend_spans(h: &mut KeyHasher, ctx: &EvalCtx, layer: &Layer) { /// Feed every property of `g` that can change over time (keyframes or expression) as its value /// at the context time. The static structure is hashed separately. -/// Mix the collapsed-instance overrides that target `id` into a cache key. They replace values +/// Mix the collapsed-instance overrides that target `layer` into a cache key. They replace values /// without editing the layer, so a key without them would reuse another instance's buffer. -fn hash_overrides(h: &mut KeyHasher, ctx: &EvalCtx, id: effectcraft_project::LayerId) { - for o in ctx.property_overrides.iter().filter(|o| o.layer == id) { +fn hash_overrides(h: &mut KeyHasher, ctx: &EvalCtx, layer: &Layer) { + for o in ctx.property_overrides.iter().filter(|o| o.layer == layer.id) { o.prop.hash(h); o.font.hash(h); hash_debug(h, &o.value); + hash_debug(h, &o.keys); + // The stored value belongs to the outer context. The nested layer can be compared with + // its previous frame while that value stays fixed, so hash the effective value at the + // target layer's exact time as well. + if let Some(prop) = layer.props.find(o.prop) { + hash_debug(h, &o.value_at_layer_time(prop, layer.layer_time(ctx.time))); + } } - for m in ctx.media_overrides.iter().filter(|m| m.layer == id) { + for m in ctx.media_overrides.iter().filter(|m| m.layer == layer.id) { m.item.hash(h); } } @@ -754,8 +761,8 @@ fn hash_values(h: &mut KeyHasher, ctx: &EvalCtx, layer: &Layer, g: &PropGroup) { /// time, or `None` when the layer must not be cached (movie footage, precomps, cameras, adjustment /// layers…). pub fn layer_key(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool, blur: bool) -> Option { - // Time effects (and CC Particle World's Birth Rate history) see property values at other - // times. Keyframes are part of the hashed structure (and the layer time is folded in), but + // Time effects (and stepped particle systems' Birth Rate and producer history) see property + // values at other times. Keyframes are part of the hashed structure (and the layer time is folded in), but // expressions may read other layers at those times, which the key cannot see: such layers // are not cached. if history_unkeyable(layer, None) { @@ -778,8 +785,8 @@ pub fn input_key(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool, blur: bo } /// Does the layer run (among its first `effects` effects, all when `None`) an effect that reads -/// the layer at other times (Echo, Timewarp…) or its own parameters' history (CC Particle -/// World's Birth Rate, #1373)? +/// the layer at other times (Echo, Timewarp…) or its own parameters' history (stepped particle +/// systems' Birth Rate and producer position, #1373)? fn reads_other_times(layer: &Layer, effects: Option) -> bool { layer.switches.effects && layer.effects().is_some_and(|fx| { @@ -930,7 +937,7 @@ fn key_any(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool, blur: bool, fo // Collapsed-instance overrides replace values without editing the nested layer, so mix them // into the key: a Font override, effect parameter or any other source-affecting override // must not reuse another instance's processed buffer. - hash_overrides(&mut h, ctx, layer.id); + hash_overrides(&mut h, ctx, layer); hash_debug(&mut h, &layer.source); // (Audio, Lock and Shy don't change pixels.) hash_debug(&mut h, &layer.switches.pixels()); diff --git a/crates/render/src/cache/dependencies.rs b/crates/render/src/cache/dependencies.rs index 9b9b5e79a..1aebad749 100644 --- a/crates/render/src/cache/dependencies.rs +++ b/crates/render/src/cache/dependencies.rs @@ -87,7 +87,7 @@ impl Dependencies<'_> { hash_debug(self.h, layer); // An overridden clip plays on the layer clock and a keyed one from its key: the same // selection at the same time can pose differently. - super::hash_overrides(self.h, ctx, layer.id); + super::hash_overrides(self.h, ctx, layer); hash_values(self.h, ctx, layer, &layer.props); hash_debug(self.h, &ctx.world_matrix(layer)); if let Some(item) = layer.source.item() { @@ -148,7 +148,7 @@ impl Dependencies<'_> { hash_debug(self.h, layer); // A referenced layer's static values can be overridden by the collapsed instance without // editing it (`hash_values` only sees animated ones), so the owner's key needs them too. - super::hash_overrides(self.h, ctx, layer.id); + super::hash_overrides(self.h, ctx, layer); hash_values(self.h, ctx, layer, &layer.props); hash_debug(self.h, &ctx.world_matrix(layer)); // A cached owner never runs this layer's effects, so the comp camera and lights its diff --git a/crates/render/src/eval.rs b/crates/render/src/eval.rs index a9abefb16..2906b23c4 100644 --- a/crates/render/src/eval.rs +++ b/crates/render/src/eval.rs @@ -3,8 +3,10 @@ //! Keyframe times are stored in **layer time** (they move with the layer), so evaluating a //! property at comp time `t` first maps `t` through the layer's start time and stretch. +use std::borrow::Cow; + use effectcraft_geom::{Mat3, Mat4, Vec3, vec2, vec3}; -use effectcraft_keyframe::Value; +use effectcraft_keyframe::{Value, evaluate, evaluate_orientation}; use effectcraft_project::{Comp, ItemId, Layer, LayerId, LayerSource, Project, PropGroup, Property}; use effectcraft_time::Tick; @@ -57,12 +59,21 @@ impl<'a> EvalCtx<'a> { pub fn at(&self, time: Tick) -> EvalCtx<'a> { EvalCtx { time, ..*self } } + /// The property as this context evaluates it: a collapsed Essential Property override + /// replaces its value and keyframes, while a Font override merges only the font. The + /// expression stays on the property and is not evaluated here. + pub fn effective_property<'p>(&self, layer: &Layer, prop: &'p Property) -> Cow<'p, Property> { + let Some(o) = self.property_overrides.iter().rev().find(|o| o.layer == layer.id && o.prop == prop.uid) else { + return Cow::Borrowed(prop); + }; + Cow::Owned(o.effective_property(prop)) + } /// Value of a property at the context time (keyframes, then expression). pub fn value(&self, layer: &Layer, prop: &Property) -> Value { // A collapsed precomp instance's Essential Property override replaces the base value; // its expression (if any) still runs, and sees the overrides of this context. if let Some(o) = self.property_overrides.iter().rev().find(|o| o.layer == layer.id && o.prop == prop.uid) { - let v = o.value(layer, prop, self.time); + let v = o.value_at_layer_time(prop, layer.layer_time(self.time)); if prop.has_expression() && let Some(h) = self.expr { @@ -87,7 +98,12 @@ impl<'a> EvalCtx<'a> { /// fractional stretch: a Hold key at `lt` could read its previous value). An expression /// still runs at the context time. pub fn value_at_layer_time(&self, layer: &Layer, prop: &Property, lt: Tick) -> Value { - let v = prop.value_at(lt); + let v = self + .property_overrides + .iter() + .rev() + .find(|o| o.layer == layer.id && o.prop == prop.uid) + .map_or_else(|| prop.value_at(lt), |o| o.value_at_layer_time(prop, lt)); if prop.has_expression() && let Some(h) = self.expr { @@ -283,16 +299,41 @@ impl<'a> EvalCtx<'a> { } impl crate::PropertyOverride { - pub(crate) fn value(&self, layer: &Layer, prop: &Property, time: Tick) -> Value { + /// The target property with this override applied, without evaluating its expression. + fn effective_property(&self, prop: &Property) -> Property { + let mut property = prop.clone(); if self.font { // A Font control merges only the font into the target text, as - // `essential::with_overrides` does. - let mut value = prop.value_at(layer.layer_time(time)); - effectcraft_project::essential::merge_font(&mut value, &self.value); - value + // `essential::with_overrides` does. The target's own text and keyframes stay. + effectcraft_project::essential::merge_font(&mut property.value, &self.value); + for key in &mut property.keys { + effectcraft_project::essential::merge_font(&mut key.value, &self.value); + } } else { - self.value.clone() + property.keys = self.keys.clone(); + property.value = self.value.clone(); } + property + } + /// The overridden value at the target layer's exact `layer_time`. + pub(crate) fn value_at_layer_time(&self, prop: &Property, layer_time: Tick) -> Value { + if self.font { + // A Font override leaves the target's history in place and merges its font into the + // value that history selects. The same font is merged into every key, so merging + // after evaluation is equivalent and avoids cloning all the target's keys. + let mut value = prop.value_at(layer_time); + effectcraft_project::essential::merge_font(&mut value, &self.value); + return value; + } + if self.keys.is_empty() { + return self.value.clone(); + } + // Match `Property::value_at` for the replacement history, including orientation's + // shortest-arc interpolation and spatial position paths. + if prop.match_id == "orientation" && matches!(self.value, Value::Vec3(_)) { + return evaluate_orientation(&self.keys, layer_time).unwrap_or_else(|| self.value.clone()); + } + evaluate(&self.keys, layer_time, prop.spatial).unwrap_or_else(|| self.value.clone()) } } diff --git a/crates/render/src/fx_host.rs b/crates/render/src/fx_host.rs index 6e8a0d42d..58dc72e79 100644 --- a/crates/render/src/fx_host.rs +++ b/crates/render/src/fx_host.rs @@ -139,7 +139,13 @@ impl EffectHost for FxHost<'_, '_, '_> { } fn param_is_static(&self, effect_index: usize, id: &str) -> bool { - effect_param(self.layer, effect_index, id).is_some_and(|p| p.keys.is_empty() && !p.has_expression()) + let Some(p) = effect_param(self.layer, effect_index, id) else { return false }; + let Some(o) = self.ctx.property_overrides.iter().rev().find(|o| o.layer == self.layer.id && o.prop == p.uid) else { + return p.keys.is_empty() && !p.has_expression(); + }; + // A whole-value override replaces the target property's keys. A Font override leaves them + // in place, so those keys still make the value vary over time. + o.keys.is_empty() && !p.has_expression() && (!o.font || p.keys.is_empty()) } fn comp_scene(&self) -> Option { @@ -210,10 +216,25 @@ pub fn essential_overrides(ctx: &EvalCtx, layer: &Layer) -> Vec, /// A Font control changes only the font of the target text, not its text. pub(crate) font: bool, } @@ -122,28 +124,29 @@ fn collapsed_instance(ctx: &EvalCtx, layer: &Layer, item: ItemId) -> Option<(Vec if over.is_empty() { return Some((vec![], vec![])); } - let g = essential::group(layer)?; - let eg = ctx.project.comp(item)?.essential.as_ref()?; + essential::group(layer)?; + let nc = ctx.project.comp(item)?; + let eg = nc.essential.as_ref()?; let mut property = vec![]; let mut fonts: Vec = vec![]; let mut media = vec![]; - g.walk("", &mut |_, p| { - if !over.contains(&p.uid) { - return; - } - let Some(control) = essential::control_of(&p.match_id) else { return }; - let Some(ctl) = eg.resolve(control) else { return }; - let value = ctx.value(layer, p); + for over in essential_overrides(ctx, layer) { + let Some(ctl) = eg.resolve(over.control) else { continue }; match &ctl.kind { EgKind::Property { .. } => { let font = ctl.as_type == Some(ControlType::Font); - for (layer, prop) in ctl.kind.targets() { - let o = PropertyOverride { layer, prop, value: value.clone(), font }; + for (target_layer, prop) in ctl.kind.targets() { + let keys = if font { + vec![] + } else { + nc.layer(target_layer).map(|target| essential::keys_in_layer_time(&over.keys, target.start_time, target.stretch)).unwrap_or_default() + }; + let o = PropertyOverride { layer: target_layer, prop, value: over.value.clone(), keys, font }; if font { fonts.push(o) } else { property.push(o) } } } EgKind::Media { layer: target } => { - let Value::Scalar(id) = value else { return }; + let Value::Scalar(id) = over.value else { continue }; let item = ItemId(id.max(0.0) as u64); if matches!(ctx.project.item(item).map(|i| &i.kind), Some(ItemKind::Footage(_))) { media.push(MediaOverride { layer: *target, item }); @@ -151,12 +154,17 @@ fn collapsed_instance(ctx: &EvalCtx, layer: &Layer, item: ItemId) -> Option<(Vec } _ => {} } - }); + } // A Font control merges into the text its instance shows, after a whole-value (Text) override // of the same property, as `essential::with_overrides` does: keep one entry per property. for f in fonts { match property.iter_mut().rev().find(|o| o.layer == f.layer && o.prop == f.prop) { - Some(o) => effectcraft_project::essential::merge_font(&mut o.value, &f.value), + Some(o) => { + effectcraft_project::essential::merge_font(&mut o.value, &f.value); + for key in &mut o.keys { + effectcraft_project::essential::merge_font(&mut key.value, &f.value); + } + } None => property.push(f), } } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index fd60f31a1..9a8acfb74 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -697,6 +697,34 @@ fn particle_systems_ii_and_mr_mercury_keep_a_burst_after_birth_rate_drops_to_zer } } +/// A Particle Playground cannon-position expression reads the cannon's position at earlier +/// times, so its layer cannot be served from a cache keyed only by the current value. +#[test] +fn particle_playground_with_a_cannon_position_expression_is_not_layer_cached() { + let (mut p, cid, comp) = setup(); + let mut l = solid(&mut p, &comp, [0.0, 0.0, 0.0], 200, 100); + add_effect( + &mut p, + &mut l, + "ec.sim.particleplayground", + [200.0, 100.0], + &[("grid/particlesAcross", Value::Scalar(0.0)), ("grid/particlesDown", Value::Scalar(0.0)), ("cannon/particlesPerSecond", Value::Scalar(60.0))], + ); + p.comp_mut(cid).unwrap().layers.push(l); + let c = p.comp(cid).unwrap(); + let key = crate::cache::layer_key(&crate::eval::EvalCtx::new(&p, cid, c, Tick::from_seconds_f64(0.9)), &c.layers[0], 1.0, false, false); + assert!(key.is_some(), "a static cannon position is cacheable"); + + let fx = p.comp_mut(cid).unwrap().layers[0].props.sub_mut("effects").unwrap().children.iter_mut().find_map(|c| match c { + effectcraft_project::Node::Group(g) => Some(g), + _ => None, + }); + fx.unwrap().prop_mut("cannon/cannonPosition").unwrap().expr = Some(effectcraft_project::Expression { text: "time * 10".into(), enabled: true }); + let c = p.comp(cid).unwrap(); + let key = crate::cache::layer_key(&crate::eval::EvalCtx::new(&p, cid, c, Tick::from_seconds_f64(0.9)), &c.layers[0], 1.0, false, false); + assert!(key.is_none(), "the cannon's parameter history is not cacheable"); +} + /// A Birth Rate expression on any of the stepped particle systems keeps the layer out of the /// layer cache (its key can't see what the expression returned at earlier times); without one /// the layer is cached. diff --git a/crates/render/src/tests/collapse.rs b/crates/render/src/tests/collapse.rs index 4104e0b38..be3fef49b 100644 --- a/crates/render/src/tests/collapse.rs +++ b/crates/render/src/tests/collapse.rs @@ -1,9 +1,9 @@ //! Collapse Transformations, Continuously Rasterize and the Quality switch. use effectcraft_color::{BlendMode, Label}; -use effectcraft_keyframe::{TextDoc, Value}; +use effectcraft_keyframe::{Keyframe, TextDoc, Value}; use effectcraft_project::build::{self, Ids}; -use effectcraft_project::{BitDepth, Comp, FrameBlend, ItemId, ItemKind, Layer, LayerSource, Project, Quality, Solid}; +use effectcraft_project::{BitDepth, Comp, FrameBlend, GroupKind, ItemId, ItemKind, Layer, LayerSource, Project, Quality, Solid}; use effectcraft_time::{FrameRate, Tick}; use crate::{EvalCtx, Image, NoFootage, RenderOpts, Renderer, render_frame}; @@ -90,6 +90,145 @@ fn collapsed_precomp_equals_manual_flattening() { assert!((half.get(x, y)[0] - (bg + (full - bg) * 0.5)).abs() < 0.03, "{:?} vs {full}", half.get(x, y)); } +/// A Particle Emitter 2D producer in a nested comp, overridden by a keyframed Essential +/// Property on the collapsed precomp instance. The particles born earlier follow the instance +/// override's history, just as they do on the flattened path. +#[test] +fn a_collapsed_particle_producer_follows_the_instance_override_history() { + use effectcraft_project::essential::{self, EgControl, EgKind, EssentialGraphics}; + + fn scene(collapse: bool) -> (Project, ItemId) { + let mut p = project(); + let mut outer = Comp::new(200, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0)); + let mut inner = Comp::new(200, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0)); + let mut layer = solid(&mut p, &inner, [0.0, 0.0, 0.0], (200, 100), [100.0, 50.0, 0.0]); + let spec = effectcraft_effects::find("ec.sim.ccparticlesystems2").unwrap(); + let mut next = p.next_id; + let mut effect = effectcraft_effects::instantiate(spec, &mut Ids(&mut next), spec.name, [200.0, 100.0]); + p.next_id = next; + effect.prop_mut("birthRate").unwrap().value = Value::Scalar(60.0); + effect.prop_mut("longevity").unwrap().value = Value::Scalar(5.0); + let producer = effect.sub_mut("producer").unwrap().prop_mut("position").unwrap(); + producer.value = Value::Vec2([140.0, 50.0]); + producer.keys = vec![Keyframe::new(Tick::ZERO, Value::Vec2([140.0, 50.0])), Keyframe::new(Tick::from_seconds_f64(1.0), Value::Vec2([160.0, 50.0]))]; + let producer_uid = producer.uid; + for (group, name) in [("producer", "radiusX"), ("producer", "radiusY"), ("physics", "velocity"), ("physics", "gravity")] { + effect.sub_mut(group).unwrap().prop_mut(name).unwrap().value = Value::Scalar(0.0); + } + layer.props.sub_mut("effects").unwrap().children.push(effect.into()); + let layer_id = layer.id; + inner.layers = vec![layer].into(); + let inner_id = p.add_item("Inner", Label::Sandstone, None, ItemKind::Comp(inner.into())); + p.comp_mut(inner_id).unwrap().essential = Some(EssentialGraphics { + controls: vec![EgControl { + id: 1, + name: "Producer".into(), + kind: EgKind::Property { layer: layer_id, prop: producer_uid, links: vec![] }, + as_type: None, + }], + ..Default::default() + }); + + let mut pre = build::layer(&mut p, &outer, "Inner", LayerSource::Comp { item: inner_id }, (200, 100), None); + let mut next = p.next_id; + let mut ids = Ids(&mut next); + let mut control = ids.prop(&essential::match_id(1), "Producer", Value::Vec2([20.0, 50.0])); + control.keys = vec![Keyframe::new(Tick::ZERO, Value::Vec2([20.0, 50.0])), Keyframe::new(Tick::from_seconds_f64(1.0), Value::Vec2([120.0, 50.0]))]; + let mut group = ids.group(essential::GROUP, "Essential Properties"); + group.kind = GroupKind::Essential { overridden: vec![control.uid] }; + group.children.push(control.into()); + pre.props.children.push(group.into()); + p.next_id = next; + pre.switches.collapse = collapse; + outer.layers = vec![pre].into(); + let outer_id = p.add_item("Outer", Label::Sandstone, None, ItemKind::Comp(outer.into())); + (p, outer_id) + } + + fn particle_span(img: &Image) -> (f32, f32) { + let (mut first, mut last, mut mass) = (f32::INFINITY, f32::NEG_INFINITY, 0.0); + for y in 0..img.height { + for x in 0..img.width { + let red = img.get(x as i64, y as i64)[0]; + if red > 0.001 { + first = first.min(x as f32); + last = last.max(x as f32); + mass += red; + } + } + } + assert!(mass > 1.0, "particles drawn"); + (first, last) + } + + let (p, cid) = scene(false); + let flattened = particle_span(&render_frame(&p, cid, Tick::from_seconds_f64(1.0), 1.0)); + let (p, cid) = scene(true); + let comp = p.comp(cid).unwrap(); + let ctx = EvalCtx::new(&p, cid, comp, Tick::from_seconds_f64(1.0)); + assert!(Renderer::new(&p, &NoFootage, RenderOpts::default()).collapsed(&ctx, &comp.layers[0]).is_some(), "the precomp stays collapsed"); + let collapsed = particle_span(&render_frame(&p, cid, Tick::from_seconds_f64(1.0), 1.0)); + // The override moves the producer from x=20 to x=120. The trail must reach both ends, + // independently of whether the flattened and collapsed paths agree. + assert!(collapsed.0 < 30.0 && collapsed.1 > 110.0, "collapsed producer trail {collapsed:?}"); + assert!( + (flattened.0 - collapsed.0).abs() < 2.0 && (flattened.1 - collapsed.1).abs() < 2.0, + "collapsed producer history: {collapsed:?} vs flattened {flattened:?}" + ); +} + +/// A keyframed Source Text override on a collapsed precomp changes the nested text layer at +/// its exact layer times. Its processed-layer key must change too, or the previous nested frame +/// is reused and the old text stays on screen. +#[test] +fn an_animated_collapsed_text_override_changes_the_nested_layer_cache_key() { + use effectcraft_project::essential::{self, EgControl, EgKind, EssentialGraphics}; + + fn text(value: &str) -> Value { + Value::Text(Box::new(TextDoc { text: value.into(), size: 60.0, ..Default::default() })) + } + + let mut p = project(); + let mut outer = Comp::new(200, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0)); + let mut inner = Comp::new(200, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0)); + let mut layer = build::layer(&mut p, &inner, "Text", LayerSource::Text, (200, 100), None); + layer.props.prop_mut("text/sourceText").unwrap().value = text("BASE"); + let layer_id = layer.id; + let source_uid = layer.props.prop("text/sourceText").unwrap().uid; + inner.layers = vec![layer].into(); + inner.essential = Some(EssentialGraphics { + controls: vec![EgControl { id: 1, name: "Text".into(), kind: EgKind::Property { layer: layer_id, prop: source_uid, links: vec![] }, as_type: None }], + ..Default::default() + }); + let inner_id = p.add_item("Inner", Label::Sandstone, None, ItemKind::Comp(inner.into())); + + let mut pre = build::layer(&mut p, &outer, "Inner", LayerSource::Comp { item: inner_id }, (200, 100), None); + let mut next = p.next_id; + let mut ids = Ids(&mut next); + let mut control = ids.prop(&essential::match_id(1), "Text", text("A")); + control.keys = vec![Keyframe::new(Tick::ZERO, text("A")), Keyframe::new(Tick::from_seconds_f64(1.0), text("B"))]; + let mut group = ids.group(essential::GROUP, "Essential Properties"); + group.kind = GroupKind::Essential { overridden: vec![control.uid] }; + group.children.push(control.into()); + pre.props.children.push(group.into()); + p.next_id = next; + pre.switches.collapse = true; + outer.layers = vec![pre].into(); + let outer_id = p.add_item("Outer", Label::Sandstone, None, ItemKind::Comp(outer.into())); + + let outer = p.comp(outer_id).unwrap(); + let pre = &outer.layers[0]; + let renderer = Renderer::new(&p, &NoFootage, RenderOpts::default()); + let ctx = EvalCtx::new(&p, outer_id, outer, Tick::from_seconds_f64(1.0)); + let collapsed = renderer.collapsed(&ctx, pre).unwrap(); + let (_, nested) = renderer.collapse_into(&ctx, pre, &collapsed, 1.0).unwrap(); + let layer = &nested.comp.layers[0]; + let before = nested.time - nested.comp.frame_rate.frame_duration(); + let now_key = crate::cache::layer_key(&nested, layer, 1.0, false, false).unwrap(); + let before_key = crate::cache::layer_key(&nested.at(before), layer, 1.0, false, false).unwrap(); + assert_ne!(now_key, before_key, "the animated Source Text override changes the nested layer's pixels"); +} + #[test] fn masks_on_a_collapsed_layer_force_a_flattened_render() { let (mut p, cid) = scene(true, false); @@ -159,8 +298,7 @@ fn referenced_layer_overrides_change_the_owner_cache_key() { let comp = p.comp(cid).unwrap(); let b = comp.layer(bid).unwrap(); let opacity = comp.layer(aid).unwrap().props.prop("transform/opacity").unwrap().uid; - let key = |value: f64| { - let overrides = [crate::PropertyOverride { layer: aid, prop: opacity, value: Value::Scalar(value), font: false }]; + let key = |overrides: &[crate::PropertyOverride]| { let ctx = EvalCtx { project: &p, comp_id: cid, @@ -168,15 +306,19 @@ fn referenced_layer_overrides_change_the_owner_cache_key() { time: Tick::ZERO, expr: None, footage: None, - property_overrides: &overrides, + property_overrides: overrides, media_overrides: &[], reads: None, }; crate::cache::layer_key(&ctx, b, 1.0, false, false) }; - let (opaque, half) = (key(100.0), key(50.0)); + let override_at = |value: f64, keys: Vec| [crate::PropertyOverride { layer: aid, prop: opacity, value: Value::Scalar(value), keys, font: false }]; + let (opaque, half) = (key(&override_at(100.0, vec![])), key(&override_at(50.0, vec![]))); assert!(opaque.is_some(), "the owner is cacheable"); assert_ne!(opaque, half, "A's static override changes B's key"); + let early = override_at(100.0, vec![Keyframe::new(Tick::ZERO, Value::Scalar(25.0))]); + let late = override_at(100.0, vec![Keyframe::new(Tick::ZERO, Value::Scalar(75.0))]); + assert_ne!(key(&early), key(&late), "A's override history changes B's key"); } #[test] diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index eef5b4067..be6f864a2 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -284,7 +284,7 @@ pub fn animator_selection_within(ctx: &EvalCtx, layer: &Layer, anim: &PropGroup, let stat = if prop.has_expression() { // The expression is not run here, but an Essential Property override still wins over the base value. match ctx.property_overrides.iter().rev().find(|o| o.layer == layer.id && o.prop == prop.uid) { - Some(o) => o.value(layer, prop, ctx.time), + Some(o) => o.value_at_layer_time(prop, layer.layer_time(ctx.time)), None => prop.value_at(layer.layer_time(ctx.time)), } } else { diff --git a/docs/architecture.md b/docs/architecture.md index 1ac306174..9955cc79e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -481,12 +481,14 @@ Playground cannons without interacting forces evolve every particle independentl backend (reached through `EffectHost::particles` when the GPU compositor is active) simulates one particle per invocation from the CPU's birth schedule and keeps per-key state checkpoints on the GPU, like `SimCache`; the CPU simulation stays the oracle (tests compare ids and positions). -Particle Emitter 3D, Particle Emitter 2D and Liquid Particles sample their Birth Rate at every -step (`EffectHost::param_at`, #1373), so a keyed rate only decides the births of its own time; -the rate is left out of the simulation key, and a checkpoint is resumed only with the same rate history (the CPU state's `hist`, the GPU -checkpoint's births). The rate's keyframes are read at the step's exact layer time +Particle Emitter 3D, Particle Emitter 2D and Liquid Particles sample their Birth Rate and producer +position at every step (`EffectHost::param_at`, #1373), so a keyed rate only decides the births of +its own time and a particle is born where its producer was during that step. The rate and producer +are left out of the simulation key; a checkpoint is resumed only with the same rate and producer +histories (the CPU state's `hist` and `producer_hist`, the GPU checkpoint's births and producer +fingerprint). The values are read at the step's exact layer time (`EvalCtx::value_at_layer_time`; mapping it to comp time and back rounds under a fractional -stretch), a rate without keyframes or an expression isn't sampled, and a layer of one of them with +stretch), a value without keyframes or an expression isn't sampled, and a layer of one of them with expressions isn't layer cached (its key can't see what an expression returned at earlier times). `effectcraft-cli bench --gpu` reports CPU vs GPU ms/frame, speed-up, Auto's ms/frame, pixel agreement and the steady-state upload / readback MB per frame for every comp plus an