Skip to main content

unbanished_game/nature/
environment.rs

1//! The environment: the temperature, the weather, and the seasonal values the renderer uses. It is
2//! advanced once per simulation iteration, after the calendar. See docs/ENVIRONMENT.md,
3//! docs/GAME-LOOP-STEP-04.md and docs/GAME-LOOP-STEP-05.md.
4//!
5//! Original: `FUN_140099430` (set-up), `FUN_140099300` (bound to the climate), `FUN_1400999b0`
6//! (the update).
7// Game/Game +0x130
8
9use unbanished_formats::game::ClimateGenerator;
10
11use crate::noise::PerlinNoise;
12use crate::random::Random;
13
14// DAT_14017895c
15/// Seconds in a game year.
16pub const YEAR_SECONDS: f32 = 3600.0;
17/// `DAT_1401788e4`: weather slices per year.
18const SLICES: f32 = 48.0;
19/// `DAT_140178800`, `DAT_140178894`: temperature Perlin persistence and octaves.
20const NOISE_PERSISTENCE: f32 = 0.25;
21const NOISE_OCTAVES: f32 = 4.0;
22/// `DAT_1401787b4` / `DAT_140178848`: smoothing weights of the annual targets.
23const SMOOTH_NEW: f32 = 0.000_999_987_1;
24const SMOOTH_OLD: f32 = 0.999;
25/// `DAT_1401787e0`: 1/12.
26const TWELFTH: f32 = 0.083_333_336;
27/// `DAT_140178920`: seconds per Perlin unit.
28const NOISE_PERIOD: f32 = 180.0;
29/// `DAT_140178934`: seconds per month (also the sine phase offset).
30const MONTH_SECONDS: f32 = 300.0;
31// DAT_1401788d8
32/// Rain above this temperature, Snow at or below.
33pub const RAIN_SNOW_THRESHOLD: f32 = 34.0;
34// DAT_1401788d0
35/// Freezing point (°F).
36pub const FREEZING: f32 = 32.0;
37/// Game option `DAT_1401cbde0 + 0x16` (weather effects), on by default (`FUN_140042850`).
38const WEATHER_EFFECTS: bool = true;
39
40// +0x50; +0x60
41// The geometry is made by FUN_1400d93e0.
42/// A weather effect slot: its particle geometry and its ambient sound. Slot 0 is rain, slot 1 is
43/// snow (the order of the environment's weather list).
44#[derive(Debug, Clone, Copy, PartialEq)]
45pub struct WeatherEffect {
46    // geometry +0xc0
47    /// `geometry`: 0..1, also the ambient emitter's volume.
48    pub intensity: f32,
49    // geometry +0xc4
50    /// `geometry`: +1 fading in, −1 fading out.
51    pub direction: f32,
52}
53
54/// The climate fields the controller reads (`ClimateGenerator`).
55///
56/// Original: `FUN_140098470`.
57#[derive(Debug, Clone, PartialEq)]
58pub struct Climate {
59    // +0x34
60    /// Baseline temperature.
61    pub baseline: f32,
62    // +0x38
63    /// Amplitude of the yearly sine.
64    pub seasonal: f32,
65    // +0x3c
66    /// Amplitude of the Perlin noise.
67    pub noise: f32,
68    // +0x40
69    /// Range of the annual random baseline offset.
70    pub baseline_range: f32,
71    // +0x44
72    /// Four floats per month; the first three are cumulative weather-state cutoffs.
73    pub months: [[f32; 4]; 12],
74    // +0x104
75    /// Range of the annual weather-cutoff bias.
76    pub bias_range: f32,
77    // +0x108, +0x10c
78    /// A tornado's odds while it rains (years, odds).
79    ///
80    /// Original: `FUN_1400ae760`.
81    pub tornado: (f32, f32),
82}
83
84impl From<&ClimateGenerator> for Climate {
85    fn from(c: &ClimateGenerator) -> Climate {
86        Climate {
87            baseline: c.settings[0],
88            seasonal: c.settings[1],
89            noise: c.settings[2],
90            baseline_range: c.settings[3],
91            months: c.monthly_thresholds,
92            bias_range: c.trailing_settings[0],
93            tornado: (c.trailing_settings[1], c.trailing_settings[2]),
94        }
95    }
96}
97
98/// The values the renderer receives from the environment each update (the shaders'
99/// `pc_userPosition`).
100///
101/// Original: `FUN_1400988f0`.
102#[derive(Debug, Clone, Copy, Default, PartialEq)]
103pub struct SeasonValues {
104    // +0x1c
105    /// Snow cover, `clamp(32 − temperature, 0, 1)`.
106    pub snow: f32,
107    // +0x20
108    /// Autumn tint.
109    pub autumn: f32,
110    // +0x24
111    /// Leaf loss.
112    pub leaf_loss: f32,
113    // +0x28; geometry +0xc0
114    /// Rain, the strongest active weather effect's intensity (`geometry`).
115    pub rain: f32,
116}
117
118/// The environment: temperature, weather and the renderer's seasonal values. See the [module
119/// documentation](self).
120#[derive(Debug, Clone)]
121pub struct Environment {
122    /// The climate.
123    pub climate: Climate,
124    // +0x10
125    /// 0 precipitation, 1 cloudy, 2 partly sunny, 3 sunny.
126    pub state: i32,
127    // +0x14
128    /// Precipitation level 0..5 (starts at 4).
129    pub level: i32,
130    // +0x18
131    /// °F.
132    pub temperature: f32,
133    /// The renderer's seasonal values.
134    pub season: SeasonValues,
135    /// `+0x2c` / `+0x30`: smoothed and target annual baseline.
136    baseline: f32,
137    baseline_target: f32,
138    /// `+0x34`: temperature noise.
139    noise: PerlinNoise,
140    /// `+0x44` / `+0x48`: smoothed and target weather-cutoff bias.
141    bias: f32,
142    bias_target: f32,
143    /// `+0x4c`: last processed weather slice (−1 before the first update).
144    slice: i32,
145    /// The Rain and Snow effects while they exist.
146    pub effects: [Option<WeatherEffect>; 2],
147    // Weather +0x5c
148    /// `Weather` of each slot's description: seconds to fade in or out. A slot without a loaded
149    /// description never starts.
150    pub fade_times: [Option<f32>; 2],
151    // +0x70
152    /// The time since the last tornado check.
153    pub tornado_timer: i64,
154    // Game +0xd0
155    /// `Game`: bit 7 stops tornadoes (set with disasters off).
156    pub game_flags: u32,
157}
158
159/// `floor(elapsed / 3600 × 48)`, wrapped to 0 past 47.
160fn weather_slice(elapsed: f32) -> i32 {
161    let i = ((elapsed / YEAR_SECONDS) * SLICES) as i32;
162    if i > 0x2f {
163        0
164    } else {
165        i
166    }
167}
168
169impl Environment {
170    // State +0x10, level +0x14, temperature +0x18, renderer values +0x1c, baseline +0x2c/+0x30,
171    // bias +0x44/+0x48, last slice +0x4c; each effect re-created by FUN_140099790 with its +0xc4
172    // direction and +0xc0 intensity.
173    /// The environment as a save stores it: the state, the level, the temperature, the renderer's
174    /// values, the baseline, the bias, the last slice, and each weather effect that exists (made
175    /// again on load with its direction and intensity).
176    ///
177    /// Original: `FUN_140099160`.
178    ///
179    /// Deviation: the temperature noise (`+0x34`) is not saved; after a load the original keeps
180    /// its constructor's clock-seeded field until the next reseed (slice 0 or 24). The port
181    /// keeps its constructor's fixed seed.
182    #[allow(clippy::too_many_arguments)]
183    pub fn restore(
184        &mut self,
185        state: i32,
186        level: i32,
187        temperature: f32,
188        season: SeasonValues,
189        baseline: (f32, f32),
190        bias: (f32, f32),
191        slice: i32,
192        effects: [Option<WeatherEffect>; 2],
193    ) {
194        self.state = state;
195        self.level = level;
196        self.temperature = temperature;
197        self.season = season;
198        (self.baseline, self.baseline_target) = baseline;
199        (self.bias, self.bias_target) = bias;
200        self.slice = slice;
201        self.effects = effects;
202    }
203
204    /// What [`Environment::restore`] takes, for saving: baseline and bias with their targets,
205    /// and the last slice.
206    pub fn saved(&self) -> ((f32, f32), (f32, f32), i32) {
207        (
208            (self.baseline, self.baseline_target),
209            (self.bias, self.bias_target),
210            self.slice,
211        )
212    }
213
214    /// A new environment for a climate: state 0, level 4, and the climate's baseline.
215    ///
216    /// Original: `FUN_140099430`, then `FUN_140099300`.
217    ///
218    /// Deviation: the constructor seeds its first Perlin field from two clock-seeded `Random()`s;
219    /// the first update always reseeds it (slice 0), so a fixed seed is used here.
220    /// `seed_noise_from_clock` gives the original's field for a known clock.
221    pub fn new(climate: Climate) -> Environment {
222        Environment {
223            state: 0,
224            level: 4,
225            temperature: 0.0,
226            season: SeasonValues::default(),
227            baseline: climate.baseline,
228            baseline_target: climate.baseline,
229            noise: PerlinNoise::new(NOISE_PERSISTENCE, NOISE_OCTAVES, 0, 0),
230            bias: 0.0,
231            bias_target: 0.0,
232            slice: -1,
233            effects: [None; 2],
234            fade_times: [None; 2],
235            tornado_timer: 0,
236            game_flags: 0,
237            climate,
238        }
239    }
240
241    /// Seeds the temperature noise as the constructor does when the clock reads `clock`
242    /// (`_time64`, seconds since 1970). It builds two `Random`s from the clock and takes the first
243    /// number of each, so within one second both seeds are that number. A loaded game keeps this
244    /// field until the next reseed (slice 0 or 24). With the clock of the original's load, the
245    /// port's weather after a load is the original's.
246    ///
247    /// Original: `FUN_140099430`, with `System::Random::Random` (Runtime `0x1800ca790`).
248    pub fn seed_noise_from_clock(&mut self, clock: u32) {
249        let first = Random::new(clock).rand();
250        // Measured on 2026-10-27: the original loaded Save83 at clock 1793116942, and its
251        // temperature 5,480 iterations later is this field's to the last bit but one.
252        self.noise = PerlinNoise::new(NOISE_PERSISTENCE, NOISE_OCTAVES, first as i32, first as i32);
253    }
254
255    // Game/Game +0xd8; +0x70; FUN_1400ae760 (climate +0x108)
256    /// One simulation iteration. `elapsed` is the calendar's time into the current year in seconds,
257    /// already advanced for this iteration; `dt` is the iteration's step; `rng` is the game's
258    /// shared random stream (`Game/Game`).
259    ///
260    /// Returns whether a tornado forms (step 6): this can happen while it rains above 34 °F with
261    /// tornadoes on. The caller then creates the environment template's entity.
262    ///
263    /// Original: `FUN_1400999b0`, `FUN_1400c8bf0`, `FUN_1400c9d70`.
264    pub fn update(&mut self, elapsed: f32, dt: f32, rng: &mut Random) -> bool {
265        self.step_effects(dt);
266        self.baseline = self.baseline_target * SMOOTH_NEW + self.baseline * SMOOTH_OLD;
267        self.bias = self.bias_target * SMOOTH_NEW + self.bias * SMOOTH_OLD;
268        self.update_temperature(elapsed);
269        self.update_season(elapsed);
270        let slice = weather_slice(elapsed);
271        if slice != self.slice {
272            self.slice = slice;
273            self.next_weather(slice, rng);
274        }
275        self.switch_effects();
276        self.tornado_timer += crate::scheduler::ticks(dt);
277        if RAIN_SNOW_THRESHOLD < self.temperature && self.state == 0 && self.game_flags & 0x80 == 0
278        {
279            let (years, odds) = self.climate.tornado;
280            return crate::chance::once_in_years(&mut self.tornado_timer, years, odds, rng);
281        }
282        false
283    }
284
285    /// `FUN_1400999b0`'s first loop: each effect geometry's update (`FUN_1400d8330`) moves its
286    /// intensity by `dt / fade × direction`, clamped to 0..1; the emitter's volume follows. At
287    /// intensity 0 (or with weather effects off) the geometry and its emitter are removed.
288    fn step_effects(&mut self, dt: f32) {
289        for (slot, fade) in self.effects.iter_mut().zip(self.fade_times) {
290            let Some(e) = slot else { continue };
291            let v = dt / fade.unwrap_or(1.0) * e.direction + e.intensity;
292            e.intensity = if v > 1.0 {
293                1.0
294            } else if v < 0.0 {
295                0.0
296            } else {
297                v
298            };
299            if e.intensity == 0.0 || !WEATHER_EFFECTS {
300                *slot = None;
301            }
302        }
303    }
304
305    /// `FUN_1400999b0` → `FUN_140099790` for slots 0 and 1: a slot is wanted when weather
306    /// effects are on, the state is 0 and the temperature picks it (Rain above 34°F, Snow at or
307    /// below). An unwanted existing slot fades out and forces the state to 3; a wanted missing
308    /// slot starts at intensity 0 fading in and sets the state to 0.
309    fn switch_effects(&mut self) {
310        // setbe at 0x140099c54: 34 °F or below, or a NaN temperature, snows.
311        #[allow(clippy::neg_cmp_op_on_partial_ord)]
312        let snow = !(RAIN_SNOW_THRESHOLD < self.temperature);
313        for i in 0..2 {
314            let on = WEATHER_EFFECTS && self.state == 0 && snow == (i == 1);
315            if !on {
316                if let Some(e) = &mut self.effects[i] {
317                    e.direction = -1.0;
318                    self.state = 3;
319                }
320            } else if self.effects[i].is_none() && self.fade_times[i].is_some() {
321                self.effects[i] = Some(WeatherEffect {
322                    intensity: 0.0,
323                    direction: 1.0,
324                });
325                self.state = 0;
326            }
327        }
328    }
329
330    /// Which weather effect slot is active: only in state 0 with weather enabled; slot 0 Rain above
331    /// 34°, slot 1 Snow at or below.
332    ///
333    /// Original: `FUN_1400999b0`, `FUN_140099790`.
334    pub fn active_effect(&self, weather_enabled: bool) -> Option<usize> {
335        if !weather_enabled || self.state != 0 {
336            return None;
337        }
338        // As the setbe at 0x140099c54: a NaN temperature snows.
339        #[allow(clippy::neg_cmp_op_on_partial_ord)]
340        Some(if !(RAIN_SNOW_THRESHOLD < self.temperature) {
341            1
342        } else {
343            0
344        })
345    }
346
347    /// `FUN_140098ce0`: smoothed baseline + yearly sine + Perlin noise.
348    fn update_temperature(&mut self, elapsed: f32) {
349        let noise = self.noise.generate(elapsed / NOISE_PERIOD, 0.0);
350        // `FUN_140137160`: sine of `((t − 300) / 3600) × 360 × π/180`.
351        let phase = ((elapsed - MONTH_SECONDS) / YEAR_SECONDS) * 360.0 * 0.017_453_292;
352        let sine = crate::crt::sinf(phase);
353        let t = sine * self.climate.seasonal + self.baseline;
354        self.temperature = noise * self.climate.noise + t;
355    }
356
357    /// `FUN_1400988f0`: snow cover, autumn tint, leaf loss and rain for the shaders.
358    fn update_season(&mut self, elapsed: f32) {
359        let intensities: Vec<f32> = self.effects.iter().flatten().map(|e| e.intensity).collect();
360        self.season = season_values(self.temperature, elapsed, &intensities);
361    }
362
363    /// At slices 0 and 24, reseed the noise and pick new annual targets. Then draw the weather
364    /// state from the month's biased cutoffs, and move the level up or down.
365    ///
366    /// Measured: `tools/emu/weather_pick.py` (the original on 2,000 cases).
367    ///
368    /// Original: `FUN_140098ac0`.
369    fn next_weather(&mut self, slice: i32, rng: &mut Random) {
370        if slice == 0 || slice == 24 {
371            let first = rng.rand();
372            let second = rng.rand();
373            self.noise = PerlinNoise::new(
374                NOISE_PERSISTENCE,
375                NOISE_OCTAVES,
376                second as i32,
377                first as i32,
378            );
379            let (mut bias, mut baseline) = (0.0f32, 0.0f32);
380            for _ in 0..12 {
381                bias += rng.rand_float_tol() * TWELFTH;
382                baseline += rng.rand_float_tol() * TWELFTH;
383            }
384            self.baseline_target = baseline * self.climate.baseline_range + self.climate.baseline;
385            self.bias_target = bias * self.climate.bias_range;
386        }
387        let sample = rng.rand_float();
388        let month = &self.climate.months[(slice / 4) as usize];
389        self.state = 0;
390        // jb at 0x140098c75: below the threshold, or a NaN one, stops at this state.
391        while self.bias + month[self.state as usize] <= sample {
392            self.state += 1;
393            if self.state >= 3 {
394                break;
395            }
396        }
397        match self.state {
398            0 => self.level += 1,
399            3 => self.level -= 1,
400            _ => {}
401        }
402        self.level = self.level.clamp(0, 5);
403    }
404}
405
406// Environment +0x18 temperature; +0x1c..+0x28 the values; the effects at +0x50 (count +0x58),
407// each one's intensity at +0xc0.
408/// The renderer's seasonal values for a temperature and a time into the year: snow below 32 °F,
409/// the autumn tint from month 6, the leaves lost after month 7.5 and before month 0.5, and the
410/// rain as the strongest weather effect's intensity.
411///
412/// Measured: `tools/emu/season.py` (the original on 2,000 cases).
413///
414/// Original: `FUN_1400988f0`.
415pub fn season_values(temperature: f32, elapsed: f32, intensities: &[f32]) -> SeasonValues {
416    let clamp = |v: f32| v.clamp(0.0, 1.0);
417    // `(t − 32) × −1` with mulss: −0 at 32 °F, and a NaN comes out unchanged. LLVM turns a
418    // multiply by −1 into a negation, which would flip a NaN's sign, so a NaN is left as it is.
419    let d = temperature - FREEZING;
420    let snow = clamp(if d.is_nan() { d } else { -d });
421    let month = elapsed / MONTH_SECONDS;
422    let autumn = if month >= 6.0 {
423        clamp((month - 6.0) / 1.5)
424    } else {
425        0.0
426    };
427    let leaf_loss = if month < 0.5 {
428        1.0 - clamp(month / 0.5)
429    } else if month <= 7.5 {
430        0.0
431    } else {
432        clamp((month - 7.5) * 2.0)
433    };
434    let rain = intensities
435        .iter()
436        .fold(0.0f32, |m, &i| if m < i { i } else { m });
437    SeasonValues {
438        snow,
439        autumn,
440        leaf_loss,
441        rain,
442    }
443}
444
445#[cfg(test)]
446mod tests;