pub mod animator;
pub mod dunes;
pub mod heightfield;
pub mod presets;
pub mod render;
pub mod sand;
pub mod snow;
pub mod surface;
pub mod thermal;
pub mod volume;
pub mod weather;
pub use animator::{Layer, ParticleAnimator};
pub use heightfield::Heightfield;
pub use render::{particles_object, ParticleBlend, ParticleEffect, ParticleKind, ParticleLook};
pub use thermal::Thermal;
pub use weather::Weather;
use crate::core::BufferGeometry;
use crate::math::{Color, Vector3};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Range {
pub min: f32,
pub max: f32,
}
impl Range {
pub const fn new(min: f32, max: f32) -> Self {
Self { min, max }
}
pub const fn fixed(v: f32) -> Self {
Self { min: v, max: v }
}
fn sample(&self, rng: &mut Rng) -> f32 {
let r = rng.next();
if self.min == self.max {
self.min
} else {
self.min + (self.max - self.min) * r
}
}
}
#[derive(Debug, Clone)]
pub enum EmitterShape {
Point,
Sphere { radius: f32, surface: bool },
Box { half: Vector3 },
Disc { radius: f32, normal: Vector3 },
Surface(SurfaceSampler),
Points {
points: std::sync::Arc<[Vector3]>,
jitter: f32,
},
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Direction {
Outward,
Cone { axis: Vector3, angle: f32 },
Any,
}
#[derive(Debug, Clone)]
pub struct Emitter {
pub shape: EmitterShape,
pub position: Vector3,
pub rate: f32,
pub bursts: Vec<(f32, u32)>,
pub direction: Direction,
pub speed: Range,
pub velocity: Vector3,
pub lifetime: Range,
pub size: Range,
pub terminal_speed: Range,
pub spin: Range,
pub volume: f32,
pub enabled: bool,
accumulated: f32,
fired: usize,
}
impl Emitter {
pub fn new(shape: EmitterShape, position: Vector3) -> Self {
Self {
shape,
position,
rate: 0.0,
bursts: Vec::new(),
direction: Direction::Outward,
speed: Range::fixed(0.0),
velocity: Vector3::ZERO,
lifetime: Range::fixed(2.0),
size: Range::fixed(0.05),
terminal_speed: Range::fixed(0.0),
spin: Range::fixed(0.0),
volume: 0.0,
enabled: true,
accumulated: 0.0,
fired: 0,
}
}
fn due(&mut self, t0: f32, dt: f32) -> usize {
if !self.enabled {
return 0;
}
self.accumulated += self.rate.max(0.0) * dt;
let n = self.accumulated.floor();
self.accumulated -= n;
let mut count = n as usize;
while self.fired < self.bursts.len() && self.bursts[self.fired].0 < t0 + dt {
count += self.bursts[self.fired].1 as usize;
self.fired += 1;
}
count
}
fn spawn(&self, rng: &mut Rng) -> (Vector3, Vector3) {
let (offset, outward) = match &self.shape {
EmitterShape::Point => (Vector3::ZERO, rng.unit_vector()),
EmitterShape::Sphere { radius, surface } => {
let d = rng.unit_vector();
let r = if *surface {
*radius
} else {
radius * rng.next().cbrt()
};
(d * r, d)
}
EmitterShape::Box { half } => (
Vector3::new(
(rng.next() * 2.0 - 1.0) * half.x,
(rng.next() * 2.0 - 1.0) * half.y,
(rng.next() * 2.0 - 1.0) * half.z,
),
rng.unit_vector(),
),
EmitterShape::Disc { radius, normal } => {
let n = normal.normalize();
let (u, v) = basis(n);
let r = radius * rng.next().sqrt();
let a = std::f32::consts::TAU * rng.next();
(u * (r * a.cos()) + v * (r * a.sin()), n)
}
EmitterShape::Surface(s) => s.sample(rng),
EmitterShape::Points { points, jitter } => {
if points.is_empty() {
(Vector3::ZERO, Vector3::new(0.0, 1.0, 0.0))
} else {
let p =
points[((rng.next() * points.len() as f32) as usize).min(points.len() - 1)];
let j = Vector3::new(
rng.next() * 2.0 - 1.0,
rng.next() * 2.0 - 1.0,
rng.next() * 2.0 - 1.0,
);
(p + j * *jitter, Vector3::new(0.0, 1.0, 0.0))
}
}
};
let dir = match self.direction {
Direction::Outward => outward,
Direction::Any => rng.unit_vector(),
Direction::Cone { axis, angle } => rng.in_cone(axis.normalize(), angle),
};
(
self.position + offset,
dir * self.speed.sample(rng) + self.velocity,
)
}
}
#[derive(Debug, Clone)]
pub struct SurfaceSampler {
triangles: Vec<[Vector3; 3]>,
cumulative: Vec<f32>,
}
impl SurfaceSampler {
pub fn new(geometry: &BufferGeometry) -> Self {
let mut triangles = Vec::new();
if let Some(p) = geometry.get_attribute("position") {
let v = |i: usize| Vector3::new(p.array[i * 3], p.array[i * 3 + 1], p.array[i * 3 + 2]);
let count = p.count();
let index: Vec<usize> = match &geometry.index {
Some(ix) => ix.iter().map(|&i| i as usize).collect(),
None => (0..count).collect(),
};
for t in index.as_chunks::<3>().0 {
triangles.push([v(t[0]), v(t[1]), v(t[2])]);
}
}
let mut cumulative = Vec::with_capacity(triangles.len());
let mut total = 0.0;
for [a, b, c] in &triangles {
total += (*b - *a).cross(*c - *a).length() * 0.5;
cumulative.push(total);
}
Self {
triangles,
cumulative,
}
}
fn sample(&self, rng: &mut Rng) -> (Vector3, Vector3) {
let Some(&total) = self.cumulative.last() else {
return (Vector3::ZERO, Vector3::new(0.0, 1.0, 0.0));
};
let x = rng.next() * total;
let i = self
.cumulative
.partition_point(|&c| c < x)
.min(self.triangles.len() - 1);
let [a, b, c] = self.triangles[i];
let (mut u, mut v) = (rng.next(), rng.next());
if u + v > 1.0 {
u = 1.0 - u;
v = 1.0 - v;
}
let n = (b - a).cross(c - a);
let n = if n.length() > 0.0 {
n.normalize()
} else {
Vector3::new(0.0, 1.0, 0.0)
};
(a + (b - a) * u + (c - a) * v, n)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Turbulence {
pub strength: f32,
pub scale: f32,
pub churn: f32,
pub anisotropy: f32,
}
impl Default for Turbulence {
fn default() -> Self {
Self {
strength: 0.0,
scale: 1.0,
churn: 0.3,
anisotropy: 0.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Field {
Attractor {
position: Vector3,
strength: f32,
radius: f32,
},
Vortex {
position: Vector3,
axis: Vector3,
speed: f32,
radius: f32,
},
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BoundaryLayer {
pub ground: f32,
pub roughness: f32,
pub reference: f32,
}
impl BoundaryLayer {
pub fn factor(&self, y: f32) -> f32 {
let z0 = self.roughness.max(1e-5);
let z = (y - self.ground).max(z0);
((z / z0).ln() / (self.reference.max(z0 * 2.0) / z0).ln()).max(0.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Cooling {
pub time: f32,
pub cold_gravity: Vector3,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Forces {
pub gravity: Vector3,
pub wind: Vector3,
pub turbulence: Turbulence,
pub fields: Vec<Field>,
pub boundary_layer: Option<BoundaryLayer>,
pub cooling: Option<Cooling>,
pub flutter: f32,
}
impl Default for Forces {
fn default() -> Self {
Self {
gravity: Vector3::new(0.0, -9.81, 0.0),
wind: Vector3::ZERO,
turbulence: Turbulence::default(),
fields: Vec::new(),
boundary_layer: None,
cooling: None,
flutter: 0.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Response {
Bounce { restitution: f32, friction: f32 },
Stick,
Die,
Deposit,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Spray {
pub count: Range,
pub speed: Range,
pub angle: f32,
pub carry: f32,
pub lifetime: Range,
pub size: Range,
pub terminal_speed: Range,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Collider {
Ground { height: f32 },
Sphere { center: Vector3, radius: f32 },
Box { min: Vector3, max: Vector3 },
}
#[derive(Debug, Clone, PartialEq)]
pub struct Curve(pub Vec<(f32, f32)>);
impl Curve {
pub fn constant(v: f32) -> Self {
Self(vec![(0.0, v)])
}
pub fn at(&self, t: f32) -> f32 {
lerp_keys(&self.0, t, |a, b, s| a + (b - a) * s).unwrap_or(1.0)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Gradient(pub Vec<(f32, [f32; 4])>);
impl Gradient {
pub fn constant(color: Color, alpha: f32) -> Self {
Self(vec![(0.0, [color.r, color.g, color.b, alpha])])
}
pub fn at(&self, t: f32) -> [f32; 4] {
lerp_keys(&self.0, t, |a, b, s| {
[0, 1, 2, 3].map(|i| a[i] + (b[i] - a[i]) * s)
})
.unwrap_or([1.0; 4])
}
}
fn lerp_keys<T: Copy>(keys: &[(f32, T)], t: f32, mix: impl Fn(T, T, f32) -> T) -> Option<T> {
let first = keys.first()?;
if t <= first.0 {
return Some(first.1);
}
for w in keys.windows(2) {
let ((t0, a), (t1, b)) = (w[0], w[1]);
if t <= t1 {
let s = if t1 > t0 { (t - t0) / (t1 - t0) } else { 1.0 };
return Some(mix(a, b, s));
}
}
keys.last().map(|k| k.1)
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Landing {
pub position: Vector3,
pub volume: f32,
}
#[derive(Debug, Clone, Default)]
pub struct Particles {
pub position: Vec<Vector3>,
pub velocity: Vec<Vector3>,
pub age: Vec<f32>,
pub lifetime: Vec<f32>,
pub size: Vec<f32>,
pub drag: Vec<f32>,
pub rotation: Vec<f32>,
pub spin: Vec<f32>,
pub volume: Vec<f32>,
pub resting: Vec<bool>,
pub seed: Vec<f32>,
pub generation: Vec<u8>,
pub temperature: Vec<f32>,
pub remaining: Vec<f32>,
}
impl Particles {
pub fn len(&self) -> usize {
self.position.len()
}
pub fn is_empty(&self) -> bool {
self.position.is_empty()
}
fn swap_remove(&mut self, i: usize) {
self.position.swap_remove(i);
self.velocity.swap_remove(i);
self.age.swap_remove(i);
self.lifetime.swap_remove(i);
self.size.swap_remove(i);
self.drag.swap_remove(i);
self.rotation.swap_remove(i);
self.spin.swap_remove(i);
self.volume.swap_remove(i);
self.resting.swap_remove(i);
self.seed.swap_remove(i);
self.generation.swap_remove(i);
if i < self.temperature.len() {
self.temperature.swap_remove(i);
}
if i < self.remaining.len() {
self.remaining.swap_remove(i);
}
}
}
#[derive(Debug, Clone)]
pub struct ParticleSystem {
pub emitters: Vec<Emitter>,
pub forces: Forces,
pub colliders: Vec<Collider>,
pub response: Response,
pub spray: Option<Spray>,
pub size_over_life: Curve,
pub color_over_life: Gradient,
pub temperature_over_life: Option<Curve>,
pub thermal: Option<Thermal>,
pub look: ParticleLook,
pub max_particles: usize,
pub bounds: f32,
pub particles: Particles,
landed: Vec<Landing>,
time: f32,
rng: Rng,
modes: [Mode; MODES],
modes_norm: f32,
air: Vec<Vector3>,
steps: u64,
stretched: Option<(Vector3, f32, [Mode; MODES])>,
}
impl ParticleSystem {
pub fn new(look: ParticleLook) -> Self {
Self {
emitters: Vec::new(),
forces: Forces::default(),
colliders: Vec::new(),
response: Response::Die,
spray: None,
size_over_life: Curve::constant(1.0),
color_over_life: Gradient::constant(Color::WHITE, 1.0),
temperature_over_life: None,
thermal: None,
look,
max_particles: 20_000,
bounds: 1_000.0,
particles: Particles::default(),
landed: Vec::new(),
time: 0.0,
rng: Rng::new(0x5eed),
modes: Mode::set(0x5eed),
modes_norm: Mode::norm(),
air: Vec::new(),
steps: 0,
stretched: None,
}
}
pub fn with_seed(mut self, seed: u64) -> Self {
self.rng = Rng::new(seed);
self.modes = Mode::set(seed);
self
}
pub fn with_emitter(mut self, emitter: Emitter) -> Self {
self.emitters.push(emitter);
self
}
pub fn len(&self) -> usize {
self.particles.len()
}
pub fn is_empty(&self) -> bool {
self.particles.is_empty()
}
pub fn time(&self) -> f32 {
self.time
}
pub fn take_landed(&mut self) -> Vec<Landing> {
std::mem::take(&mut self.landed)
}
pub fn landed(&self) -> &[Landing] {
&self.landed
}
pub fn air_at(&self, p: Vector3) -> Vector3 {
let shelter = self.forces.boundary_layer.map_or(1.0, |b| b.factor(p.y));
let mut u = (self.forces.wind + self.turbulence_at(p, self.time)) * shelter;
for f in &self.forces.fields {
if let Field::Vortex {
position,
axis,
speed,
radius,
} = *f
{
let a = axis.normalize();
let r = p - position;
let radial = r - a * r.dot(a);
let d = radial.length();
if d > 1e-4 && d < radius {
let fade = 1.0 - d / radius;
u = u + a.cross(radial * (1.0 / d)) * (speed * fade);
}
}
}
u
}
pub fn turbulence_at(&self, p: Vector3, t: f32) -> Vector3 {
let turb = &self.forces.turbulence;
if turb.strength <= 0.0 {
return Vector3::ZERO;
}
let q = (p - self.forces.wind * t) * (1.0 / turb.scale.max(1e-3));
let churn = turb.churn * turb.strength / turb.scale.max(1e-3) * t;
let mut u = Vector3::ZERO;
let fresh;
let modes = if turb.anisotropy > 0.0 {
match &self.stretched {
Some((w, a, m)) if *w == self.forces.wind && *a == turb.anisotropy => m,
_ => {
fresh = self.stretch_modes();
&fresh
}
}
} else {
&self.modes
};
for m in modes {
u = u + m.curl * (m.amplitude * fast_cos(q.dot(m.k) + m.phase + churn * m.rate));
}
u * (turb.strength * self.modes_norm)
}
fn stretch_modes(&self) -> [Mode; MODES] {
let a = self.forces.turbulence.anisotropy.clamp(0.0, 1.0);
let w = Vector3::new(self.forces.wind.x, 0.0, self.forces.wind.z);
let along = if w.length() > 1e-4 {
w.normalize()
} else {
Vector3::new(1.0, 0.0, 0.0)
};
let up = Vector3::new(0.0, 1.0, 0.0);
let across = up.cross(along);
let (lx, ly, lz) = (1.0 + 2.0 * a, 1.0 + 0.6 * a, 1.0 - 0.45 * a);
self.modes.map(|m| {
let k = along * (m.k.dot(along) / lx)
+ across * (m.k.dot(across) / ly)
+ up * (m.k.dot(up) / lz);
let kn = k.normalize();
let c = m.curl - kn * m.curl.dot(kn);
let curl = if c.length() > 1e-4 {
c.normalize()
} else {
kn.cross(up).normalize()
};
Mode { k, curl, ..m }
})
}
pub fn step(&mut self, dt: f32, ground: Option<&Heightfield>) {
if dt <= 0.0 {
return;
}
let turb = self.forces.turbulence;
if turb.anisotropy > 0.0
&& !matches!(&self.stretched, Some((w, a, _)) if *w == self.forces.wind && *a == turb.anisotropy)
{
self.stretched = Some((self.forces.wind, turb.anisotropy, self.stretch_modes()));
}
self.emit(dt);
let fastest = self
.particles
.velocity
.iter()
.map(|v| v.length())
.fold(0.0f32, f32::max);
let substeps = ((fastest * dt / 0.25).ceil() as usize).clamp(1, 8);
let h = dt / substeps as f32;
for _ in 0..substeps {
self.integrate(h, ground);
self.time += h;
}
self.heat(dt);
self.retire();
}
fn emit(&mut self, dt: f32) {
let t0 = self.time;
let mut spawns = Vec::new();
for (e, emitter) in self.emitters.iter_mut().enumerate() {
let n = emitter.due(t0, dt);
spawns.push((e, n));
}
for (e, n) in spawns {
for k in 0..n {
if self.particles.len() >= self.max_particles {
return;
}
let emitter = &self.emitters[e];
let (p, v) = emitter.spawn(&mut self.rng);
let late = dt * (k as f32 + self.rng.next()) / n.max(1) as f32;
let vt = emitter.terminal_speed.sample(&mut self.rng);
let g = self.forces.gravity.length().max(1e-3);
let ps = &mut self.particles;
ps.position.push(p);
ps.velocity.push(v);
ps.age.push(-late);
ps.lifetime
.push(emitter.lifetime.sample(&mut self.rng).max(1e-3));
ps.size.push(emitter.size.sample(&mut self.rng));
ps.drag.push(if vt > 0.0 { g / (vt * vt) } else { 0.0 });
ps.rotation.push(self.rng.next() * std::f32::consts::TAU);
ps.spin.push(emitter.spin.sample(&mut self.rng));
ps.volume.push(emitter.volume);
ps.resting.push(false);
ps.seed.push(self.rng.next());
ps.generation.push(0);
}
}
}
fn integrate(&mut self, h: f32, ground: Option<&Heightfield>) {
let g = self.forces.gravity;
let n = self.particles.len();
let mut sprays: Vec<(Vector3, Vector3, Vector3, f32)> = Vec::new();
self.air.resize(n, Vector3::new(f32::NAN, 0.0, 0.0));
self.steps += 1;
let parity = (self.steps & 1) as usize;
for i in 0..n {
let born = self.particles.age[i];
self.particles.age[i] += h;
if self.particles.resting[i] {
continue;
}
let h = if born < 0.0 { (born + h).max(0.0) } else { h };
if h <= 0.0 {
continue;
}
let p = self.particles.position[i];
let mut v = self.particles.velocity[i];
let age = self.particles.age[i].max(0.0);
let mut a = match self.forces.cooling {
Some(c) => c.cold_gravity + (g - c.cold_gravity) * (-age / c.time.max(1e-3)).exp(),
None => g,
};
if self.forces.flutter > 0.0 {
let s = self.particles.seed[i];
let w = std::f32::consts::TAU * (0.9 + 0.9 * s);
a = a + Vector3::new(
fast_cos(w * age + s * 17.0 - std::f32::consts::FRAC_PI_2),
0.0,
fast_cos(w * 0.83 * age + s * 31.0),
) * self.forces.flutter;
}
for f in &self.forces.fields {
if let Field::Attractor {
position,
strength,
radius,
} = *f
{
let d = position - p;
let r = d.length();
if r > 1e-4 && r < radius {
a = a + d * (strength * (1.0 - r / radius) / r);
}
}
}
let k = self.particles.drag[i];
if k > 0.0 {
if self.air[i].x.is_nan() || i & 1 == parity {
self.air[i] = self.air_at(p);
}
let air = self.air[i];
let rel = v - air + a * h;
let speed = (v - air).length();
v = air + rel * (1.0 / (1.0 + k * speed * h));
} else {
v = v + a * h;
}
let mut np = p + v * h;
self.particles.rotation[i] += self.particles.spin[i] * h;
let mut hit: Option<(Vector3, Vector3)> = None; if let Some(field) = ground
&& let Some(top) = field.height_at(np.x, np.z)
&& np.y < top
{
hit = Some((Vector3::new(np.x, top, np.z), field.normal_at(np.x, np.z)));
}
if hit.is_none() {
for c in &self.colliders {
if let Some(contact) = c.contact(np) {
hit = Some(contact);
break;
}
}
}
if let Some((point, normal)) = hit {
let child = self.particles.generation[i] > 0;
if !child && self.spray.is_some() {
sprays.push((point, normal, v, self.particles.size[i]));
}
let response = match self.response {
Response::Deposit | Response::Stick if child => Response::Die,
r => r,
};
match response {
Response::Bounce {
restitution,
friction,
} => {
let vn = normal * v.dot(normal);
let vt = v - vn;
if v.dot(normal) < 0.0 {
v = vt * (1.0 - friction).max(0.0) - vn * restitution;
}
np = point + normal * 1e-4;
}
Response::Stick => {
v = Vector3::ZERO;
np = point;
self.particles.resting[i] = true;
}
Response::Die | Response::Deposit => {
np = point;
self.particles.age[i] = f32::INFINITY;
self.particles.resting[i] = true;
if response == Response::Deposit {
self.landed.push(Landing {
position: point,
volume: self.particles.volume[i],
});
}
}
}
}
self.particles.position[i] = np;
self.particles.velocity[i] = v;
}
for (point, normal, v, size) in sprays {
self.spray_at(point, normal, v, size);
}
}
fn spray_at(&mut self, point: Vector3, normal: Vector3, v: Vector3, size: f32) {
let Some(spray) = self.spray.clone() else {
return;
};
let g = self.forces.gravity.length().max(1e-3);
let along = v - normal * v.dot(normal);
let n = spray.count.sample(&mut self.rng).round().max(0.0) as usize;
for _ in 0..n {
if self.particles.len() >= self.max_particles {
return;
}
let dir = self.rng.in_cone(normal, spray.angle);
let vel = dir * spray.speed.sample(&mut self.rng) + along * spray.carry;
let vt = spray.terminal_speed.sample(&mut self.rng);
let ps = &mut self.particles;
ps.position.push(point + normal * 1e-3);
ps.velocity.push(vel);
ps.age.push(0.0);
ps.lifetime
.push(spray.lifetime.sample(&mut self.rng).max(1e-3));
ps.size.push(size * spray.size.sample(&mut self.rng));
ps.drag.push(if vt > 0.0 { g / (vt * vt) } else { 0.0 });
ps.rotation.push(self.rng.next() * std::f32::consts::TAU);
ps.spin.push(0.0);
ps.volume.push(0.0);
ps.resting.push(false);
ps.seed.push(self.rng.next());
ps.generation.push(1);
}
}
fn retire(&mut self) {
let floor = self
.colliders
.iter()
.filter_map(|c| match c {
Collider::Ground { height } => Some(*height),
_ => None,
})
.fold(f32::INFINITY, f32::min);
let mut i = 0;
while i < self.particles.len() {
let p = self.particles.position[i];
let gone = self.particles.age[i] >= self.particles.lifetime[i]
|| !p.x.is_finite()
|| p.length() > self.bounds
|| (floor.is_finite() && p.y < floor - 1.0);
if gone {
self.particles.swap_remove(i);
if i < self.air.len() {
self.air.swap_remove(i);
}
} else {
i += 1;
}
}
}
pub fn life_fraction(&self, i: usize) -> f32 {
let l = self.particles.lifetime[i];
if l.is_finite() {
(self.particles.age[i] / l).clamp(0.0, 1.0)
} else {
0.0
}
}
}
impl Collider {
fn contact(&self, p: Vector3) -> Option<(Vector3, Vector3)> {
match *self {
Collider::Ground { height } => (p.y < height)
.then(|| (Vector3::new(p.x, height, p.z), Vector3::new(0.0, 1.0, 0.0))),
Collider::Sphere { center, radius } => {
let d = p - center;
let r = d.length();
(r < radius).then(|| {
let n = if r > 1e-6 {
d * (1.0 / r)
} else {
Vector3::new(0.0, 1.0, 0.0)
};
(center + n * radius, n)
})
}
Collider::Box { min, max } => {
let inside = p.x > min.x
&& p.x < max.x
&& p.y > min.y
&& p.y < max.y
&& p.z > min.z
&& p.z < max.z;
if !inside {
return None;
}
let faces = [
(p.x - min.x, Vector3::new(-1.0, 0.0, 0.0)),
(max.x - p.x, Vector3::new(1.0, 0.0, 0.0)),
(p.y - min.y, Vector3::new(0.0, -1.0, 0.0)),
(max.y - p.y, Vector3::new(0.0, 1.0, 0.0)),
(p.z - min.z, Vector3::new(0.0, 0.0, -1.0)),
(max.z - p.z, Vector3::new(0.0, 0.0, 1.0)),
];
let (d, n) = faces
.into_iter()
.fold((f32::INFINITY, Vector3::ZERO), |a, b| {
if b.0 < a.0 {
b
} else {
a
}
});
Some((p + n * d, n))
}
}
}
}
const MODES: usize = 12;
#[derive(Debug, Clone, Copy)]
struct Mode {
k: Vector3,
curl: Vector3,
amplitude: f32,
phase: f32,
rate: f32,
}
impl Mode {
fn set(seed: u64) -> [Mode; MODES] {
let mut rng = Rng::new(seed ^ 0x7ab1e);
let mut n = 0;
[(); MODES].map(|_| {
let octave = n / 4;
n += 1;
let scale = 2f32.powi(octave);
let k = rng.unit_vector() * (std::f32::consts::TAU * (0.7 + 0.6 * rng.next()) * scale);
let e = rng.unit_vector();
let c = k.cross(e);
let curl = if c.length() > 1e-4 {
c.normalize()
} else {
Vector3::new(1.0, 0.0, 0.0)
};
Mode {
k,
curl,
amplitude: scale.powf(-1.0 / 3.0),
phase: rng.next() * std::f32::consts::TAU,
rate: (0.5 + rng.next()) * scale.powf(2.0 / 3.0),
}
})
}
fn norm() -> f32 {
let total: f32 = (0..MODES)
.map(|n| 2f32.powi((n / 4) as i32).powf(-2.0 / 3.0) * 0.5)
.sum();
1.0 / total.sqrt()
}
}
#[inline]
pub(crate) fn fast_cos(x: f32) -> f32 {
use std::f32::consts::{FRAC_PI_2, PI, TAU};
let mut t = x + FRAC_PI_2;
t -= TAU * (t * (1.0 / TAU)).round();
let y = (4.0 / PI) * t - (4.0 / (PI * PI)) * t * t.abs();
0.225 * (y * y.abs() - y) + y
}
pub(crate) fn basis(n: Vector3) -> (Vector3, Vector3) {
let t = if n.x.abs() < 0.9 {
Vector3::new(1.0, 0.0, 0.0)
} else {
Vector3::new(0.0, 1.0, 0.0)
};
let u = n.cross(t).normalize();
(u, n.cross(u))
}
#[derive(Debug, Clone)]
pub(crate) struct Rng(u64);
impl Rng {
pub(crate) fn new(seed: u64) -> Self {
Self(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1)
}
pub(crate) fn next(&mut self) -> f32 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
let x = self.0.wrapping_mul(0x2545_f491_4f6c_dd1d);
(x >> 40) as f32 / (1u64 << 24) as f32
}
pub(crate) fn unit_vector(&mut self) -> Vector3 {
let z = self.next() * 2.0 - 1.0;
let a = self.next() * std::f32::consts::TAU;
let r = (1.0 - z * z).max(0.0).sqrt();
Vector3::new(r * a.cos(), r * a.sin(), z)
}
pub(crate) fn in_cone(&mut self, axis: Vector3, angle: f32) -> Vector3 {
let cos_max = angle.cos();
let z = 1.0 - self.next() * (1.0 - cos_max);
let a = self.next() * std::f32::consts::TAU;
let r = (1.0 - z * z).max(0.0).sqrt();
let (u, v) = basis(axis);
u * (r * a.cos()) + v * (r * a.sin()) + axis * z
}
}
#[cfg(test)]
mod tests;