// Copyright Marcus Del Favero 2025
// Licensed under the GNU AGPLv3 with an exception, see `README.md` for details
use std::f32::consts::TAU;

use super::{DELTA_TIME, sampler::BrownianNoise, resampler::{Resampler, SmoothstepResampler}};

const AMPLITUDE: f32 = 0.5;
const TIME: f32 = 0.25;
const FADE_IN: f32 = TIME / 64.0;

pub fn generate() {
	let mut amplitude_noise = SmoothstepResampler::new(BrownianNoise::new(0.25, 791461));
	let mut frequency_noise = SmoothstepResampler::new(BrownianNoise::new(0.125, 791462));
	let mut phase_noise = SmoothstepResampler::new(BrownianNoise::new(0.1875, 791463));
	let mut extra_noise = SmoothstepResampler::new(BrownianNoise::new(1.0, 791464));

	super::generate("ammo_crate", TIME, AMPLITUDE, |t| {
		let mut wave = 0.0;
		let freq = frequency_noise.next(1000.0 * DELTA_TIME) * 48.0 + 200.0;
		let phase = phase_noise.next(750.0 * DELTA_TIME) * 50.0;
		for i in 0..8 {
			let amplitude = (1.0 - t / TIME).powf(1.0 + i as f32 * 0.75);
			let w = (t * freq * (i as f32 + 1.0) * TAU + phase).sin();
			wave += w / (i + 1) as f32 * amplitude;
		}

		let mut amplitude = {
			let a = amplitude_noise.next(600.0 * DELTA_TIME);
			a.abs().powf(1.5) * a.signum()
		};
		amplitude *= 1.0 - (1.0 - (t / FADE_IN).min(1.0)).powi(2); // Fade in

		wave * amplitude * (extra_noise.next(16000.0 * DELTA_TIME) * 0.5 + 0.5)
	});
}
