Skip to main content

unbanished_game/nature/seeding/
start.rs

1//! A new map's start: the start structures, the first seeding of trees, rocks and ore from Perlin noise, and registering what is placed.
2
3use super::*;
4
5impl Seeder<'_> {
6    // Game +0xd0 |= 1
7    /// The profile's start structures, relative to the start cell.
8    ///
9    /// Each is built in "instant" mode (`Game |= 1`), so the build component shows the last
10    /// (finished) mesh. Component setup draws nothing from the stream except the model's variant;
11    /// buildings do not stamp the map on activation.
12    ///
13    /// Original: `FUN_1400a7490`, `FUN_14010cfb0`.
14    pub fn place_structures(
15        &mut self,
16        structures: &[(PlacedStructure, Option<usize>)],
17        sx: i32,
18        sy: i32,
19    ) {
20        let n = self.n();
21        let corner = |s: &Self, x: i32, y: i32| {
22            let i = n * y + x;
23            let half = (n >> 1) as f32;
24            let (px, py) = ((i % n) as f32 - half, (i / n) as f32 - half);
25            let (z, _) = s.ground(px, py);
26            [px, py, z]
27        };
28        for (record, template) in structures {
29            let Some(t) = *template else { continue };
30            // Size from the template, otherwise the record's two integers; swapped when turned
31            // by ±90 or 270 degrees.
32            let (mut w, mut h) = self.templates[t].size.unwrap_or((record.a, record.b));
33            if matches!(record.rotation, 90 | -90 | 270) {
34                std::mem::swap(&mut w, &mut h);
35            }
36            let (x, y) = (sx + record.x, sy + record.y);
37            let p0 = corner(self, x, y);
38            let p1 = corner(self, x + w, y + h);
39            let position = [
40                (p1[0] + p0[0]) * HALF,
41                (p1[1] + p0[1]) * HALF,
42                (p1[2] + p0[2]) * HALF,
43            ];
44            self.construct(t);
45            // The yard is an entity with storage/map components but no model. Retain it;
46            // only model-bearing structures consume the model-variant draw.
47            let (variant, mesh) = self.templates[t].model.as_ref().map_or((0, 0), |model| {
48                let variant = self.rng.rand_below(model.variants.len() as u32) as usize;
49                let mesh = model
50                    .variants
51                    .get(variant)
52                    .map_or(0, |v| v.meshes.len().saturating_sub(1));
53                (variant, mesh)
54            });
55            self.placed.push(Placed {
56                template: t,
57                bucket: self.templates[t].bucket,
58                cell: (x, y),
59                footprint: (w, h),
60                position,
61                yaw: record.rotation.rem_euclid(360) as f32,
62                variant,
63                mesh,
64                growth: 0.0,
65                growth_state: None,
66                spawn_state: None,
67                alive: true,
68                removal_requested: false,
69                animation: None,
70                scale: [ONE; 4],
71            });
72        }
73    }
74
75    /// Seed every template of the profile's list over the map, away from the start `(sx, sy)` by
76    /// more than `sqrt(radius_sq)` cells.
77    ///
78    /// Original: `FUN_1400a6780`.
79    pub fn seed(&mut self, list: &[usize], sx: i32, sy: i32, radius_sq: i32) {
80        // Three fields the pass builds and never reads.
81        for _ in 0..3 {
82            self.perlin(ONE, ONE);
83        }
84        let n = self.n();
85        for &template in list {
86            let Some(nr) = self.templates[template].natural.clone() else {
87                continue;
88            };
89            let variants = self.templates[template]
90                .model
91                .as_ref()
92                .map_or(0, |m| m.variants.len());
93            let clusters: Vec<PerlinNoise> = if nr.cluster {
94                (0..variants)
95                    .map(|_| self.perlin(nr.cluster_persistence, nr.cluster_octaves))
96                    .collect()
97            } else {
98                Vec::new()
99            };
100            let field = self.perlin(nr.noise_persistence, nr.noise_octaves);
101            let inv = ONE / nr.noise_scale;
102            for y in 0..n {
103                for x in 0..n {
104                    let v = field.generate(x as f32 * inv, y as f32 * inv);
105                    if nr.noise_min > v * HALF + HALF {
106                        continue;
107                    }
108                    if self.rng.rand_float() > nr.chance {
109                        continue;
110                    }
111                    let index = n * y + x;
112                    if self.cells.objects[index as usize].is_some()
113                        || (y - sy) * (y - sy) + (x - sx) * (x - sx) < radius_sq
114                    {
115                        continue;
116                    }
117                    let (cx, cy) = self.cell_position(index);
118                    let (h, up) = self.ground(cx, cy);
119                    if h < nr.height_min || (nr.height_max <= h && h != nr.height_max) {
120                        continue;
121                    }
122                    if up < nr.normal_min {
123                        continue;
124                    }
125                    if !self.density_ok(template, x, y) {
126                        continue;
127                    }
128                    let (mut variant, mut mesh, max_growth) = self.construct(template);
129                    let (position, yaw) = self.position(template, index);
130                    let (mut growth, mut scale, mut growth_state) = (1.0, [ONE; 4], None);
131                    if self.templates[template].growth.is_some() {
132                        let fraction = self.rng.rand_float();
133                        let (state, value, output) =
134                            self.set_growth(template, max_growth, fraction);
135                        growth = value;
136                        scale = output;
137                        growth_state = Some(state);
138                    }
139                    let id = self.register(Placed {
140                        template,
141                        bucket: self.templates[template].bucket,
142                        cell: (x, y),
143                        footprint: (1, 1),
144                        position,
145                        yaw,
146                        variant,
147                        mesh,
148                        growth,
149                        growth_state,
150                        spawn_state: self.spawn_state(template),
151                        alive: true,
152                        removal_requested: false,
153                        animation: None,
154                        scale,
155                    });
156                    if !self.templates[template].spawn.is_empty() {
157                        self.spawn(id);
158                    }
159                    if nr.cluster {
160                        let inv = ONE / nr.cluster_scale;
161                        variant = 0;
162                        for (k, c) in clusters.iter().enumerate() {
163                            let v = c.generate(x as f32 * inv, y as f32 * inv);
164                            // jbe at 0x1400a7221: at the threshold or above, or NaN, this one.
165                            #[allow(clippy::neg_cmp_op_on_partial_ord)]
166                            if !(v * HALF + HALF < nr.cluster_threshold) {
167                                variant = k;
168                                break;
169                            }
170                        }
171                        if self.rng.rand_below(nr.random_variant_one_in as u32) == 0 {
172                            variant = self.rng.rand_below(variants as u32) as usize;
173                        }
174                        let meshes = self.templates[template].model.as_ref().unwrap().variants
175                            [variant]
176                            .meshes
177                            .len();
178                        mesh = self.rng.rand_below(meshes as u32) as usize;
179                        self.placed[id].variant = variant;
180                        self.placed[id].mesh = mesh;
181                    }
182                }
183            }
184        }
185    }
186
187    pub(super) fn perlin(&mut self, persistence: f32, octaves: f32) -> PerlinNoise {
188        let a = self.rng.rand_tol(0x7ff_ffff);
189        let b = self.rng.rand_tol(0x7ff_ffff);
190        PerlinNoise::new(persistence, octaves, b, a)
191    }
192
193    /// `FUN_1400c8bf0` setup pass for a natural resource: the model component picks a variant
194    /// (`FUN_140129f90`) and the growth component its maximum (`FUN_140125bc0`), in template
195    /// order (map, model, naturalresource, growth, spawn).
196    pub(super) fn construct(&mut self, template: usize) -> (usize, usize, f32) {
197        let t = &self.templates[template];
198        let (mut variant, mut mesh) = (0usize, 0usize);
199        if let Some(m) = &t.model {
200            variant = m.variant.max(0) as usize;
201            if m.random_variant {
202                variant = self.rng.rand_below(m.variants.len() as u32) as usize;
203            }
204            mesh = m.mesh.max(0) as usize;
205        }
206        let mut max_growth = 1.0;
207        if let Some(g) = &t.growth {
208            max_growth = if g.max_base <= 0.0 {
209                -1.0
210            } else {
211                self.rng.rand_float_tol() * g.max_range + g.max_base
212            };
213        }
214        (variant, mesh, max_growth)
215    }
216
217    /// `FUN_14012ba10`: jitter the entity inside its cell and pick a yaw.
218    pub(super) fn position(&mut self, template: usize, index: i32) -> ([f32; 3], f32) {
219        let scale = self.templates[template]
220            .natural
221            .as_ref()
222            .map_or(0.0, |n| n.position_scale);
223        let (x, y) = self.cell_position(index);
224        let (z, _) = self.ground(x, y);
225        let dy = self.rng.rand_float_tol();
226        let dx = self.rng.rand_float_tol();
227        let position = [dx * scale + x, dy * scale + y, z + 0.0];
228        let yaw = self.rng.rand_float_tol() * YAW_RANGE;
229        (position, yaw)
230    }
231
232    /// `FUN_140126280`: set the growth from a 0..1 fraction of the maximum and draw the timer.
233    pub(super) fn set_growth(
234        &mut self,
235        template: usize,
236        max_growth: f32,
237        fraction: f32,
238    ) -> (Growth, f32, [f32; 4]) {
239        Growth::initialise(
240            self.templates[template].growth.as_ref().unwrap(),
241            max_growth,
242            fraction,
243            self.rng,
244        )
245    }
246
247    /// `FUN_1400c9d70` → `FUN_140129840`: register and stamp the map footprint (natural
248    /// resources: one cell of the description's type).
249    pub(super) fn register(&mut self, placed: Placed) -> usize {
250        let id = self.placed.len();
251        if let Some(map) = self.templates[placed.template].map.clone() {
252            if map.stamp && !map.no_stamp {
253                let i = (placed.cell.1 * self.n() + placed.cell.0) as usize;
254                // FUN_1400a30f0 queues the old stamped entity's removal before replacing it.
255                if let Some(old) = self.cells.objects[i] {
256                    self.remove(old);
257                }
258                self.cells.set_type(i, CellType(map.cell_type as u8));
259                self.cells.objects[i] = Some(id);
260            }
261        }
262        self.placed.push(placed);
263        id
264    }
265
266    /// `FUN_140126100`: at most `max_neighbours` occupied cells and `max_same` of the same
267    /// growth type among the 8 neighbours. Cached external-reference identities replace the
268    /// original GrowthDescription pointer comparison (including descriptions shared by templates).
269    pub(crate) fn density_ok(&self, template: usize, x: i32, y: i32) -> bool {
270        let Some(growth) = &self.templates[template].growth else {
271            return true;
272        };
273        let n = self.n();
274        let (mut occupied, mut same) = (0, 0);
275        for cy in y - 1..y + 2 {
276            for cx in x - 1..x + 2 {
277                if (cx == x && cy == y) || cx < 0 || cy < 0 || cx >= n || cy >= n {
278                    continue;
279                }
280                if let Some(o) = self.cells.objects[(cy * n + cx) as usize] {
281                    occupied += 1;
282                    if self.templates[self.placed[o].template].growth_reference
283                        == self.templates[template].growth_reference
284                    {
285                        same += 1;
286                    }
287                }
288            }
289        }
290        !(growth.max_same < same || growth.max_neighbours < occupied)
291    }
292}