Skip to main content

unbanished_game/nature/
seeding.rs

1//! New Game resource seeding: the start structures' draws and the procedural rock, ore and tree
2//! pass with spawned herbs, mushrooms and berries. See docs/RESOURCE-SEEDING.md.
3//!
4//! The original builds full component entities here. This port keeps only what the pass reads and
5//! writes — the map cells it stamps, the growth and model choices and every draw from the game's
6//! shared random stream, in the original order. It also runs scheduled growth, periodic child
7//! placement and natural-resource removal; see docs/GAME-LOOP-STEP-18.md.
8//!
9//! Original: `FUN_1400a87d0`, `FUN_1400a7490`, `FUN_1400a6780`.
10
11mod growth;
12mod spawning;
13mod start;
14
15use unbanished_formats::game::{
16    GrowthDescription, MapDescription, ModelDescription, NaturalResourceDescription,
17    PlacedStructure,
18};
19
20use crate::behaviour::animation::Playback;
21use crate::nature::growth::{adjust_map_byte, Growth};
22use crate::nature::spawn::Spawn;
23use crate::noise::PerlinNoise;
24use crate::random::Random;
25use crate::scheduler::{ticks, EntityScheduler};
26use crate::terrain::{CellType, HeightGrid};
27use std::sync::Arc;
28use unbanished_formats::types::AnimationGroup;
29
30/// The descriptions of one template that seeding reads.
31#[derive(Debug, Clone)]
32pub struct Template {
33    /// `Template\X.rsc:resource`.
34    pub reference: String,
35    // +0x20
36    /// ComponentDescription: scheduled bucket; 6 means unscheduled.
37    pub bucket: usize,
38    /// The MapDescription: the footprint on the map.
39    pub map: Option<MapDescription>,
40    /// The ModelDescription: the model's variants.
41    pub model: Option<ModelDescription>,
42    /// ModelDescription variant animation groups, cached in the original ExternalFactory.
43    pub animations: Vec<Option<Arc<AnimationGroup>>>,
44    /// The `AnimAudioEvent`s its clips fire: event resource, SoundEffect and probability.
45    pub audio_events: Vec<(String, Option<String>, f32)>,
46    /// The NaturalResourceDescription (trees, rocks, crops).
47    pub natural: Option<NaturalResourceDescription>,
48    /// The GrowthDescription.
49    pub growth: Option<GrowthDescription>,
50    /// FruitDescription (orchard trees).
51    pub fruit: Option<crate::production::orchard::FruitTemplate>,
52    // Compared by pointer in FUN_140126100.
53    /// The reference of the growth description, to compare two resources' growth.
54    pub growth_reference: Option<String>,
55    /// Spawn entries: (index into the template table, lo, hi).
56    pub spawn: Vec<(usize, f32, f32)>,
57    /// Scheduled component callbacks, in the ComponentDescription's construction order.
58    pub updates: Vec<ScheduledComponent>,
59    // CreatePlacedDescription +0x44/+0x48
60    /// `CreatePlacedDescription`: building footprint size.
61    pub size: Option<(i32, i32)>,
62    // +0x28; +0x24; +0x20
63    /// `StorageDescription`: accepted flags, capacity, capacity per footprint cell.
64    pub storage: Option<(u32, i32, bool)>,
65    /// Has a `StorageLocationDescription` (a town storage the starting goods go to).
66    pub storage_location: bool,
67    /// The `StorageLocationDescription`'s accepted flags.
68    pub storage_location_flags: u32,
69    /// Has a StorageDisplayComponent (its stored goods are drawn on its cells).
70    pub storage_display: bool,
71    /// A market's radius.
72    pub market_radius: Option<i32>,
73    /// Whether it is a market (a town storage with a radius).
74    pub market_location: bool,
75    /// Whether it has an InteractDescription.
76    pub has_interact: bool,
77    /// InteractDescription "use" points in model space (its point list's category 0).
78    pub use_points: Vec<[f32; 3]>,
79    // +0x20
80    /// A natural resource's pile template (NaturalResourceDescription).
81    pub pile: Option<usize>,
82    // +0x40; +0x44
83    /// A pile template's raw material (its RawMaterialDescription).
84    pub pile_material: Option<usize>,
85    /// A pile template's yields: (uneducated, educated).
86    pub pile_yield: (i32, i32),
87    /// InteractDescription "build" points in model space (category 1): where builders stand
88    /// and materials are delivered.
89    pub build_points: Vec<[f32; 3]>,
90    /// The "use" points' yaws, in degrees.
91    pub use_yaws: Vec<f32>,
92    /// The "create" points (category 2) where a workplace leaves its output.
93    pub create_points: Vec<[f32; 3]>,
94    /// The InteractDescription's other named points (name, position, yaw): the trading
95    /// post's "boat".
96    pub named_points: Vec<(String, [f32; 3], f32)>,
97    /// FloorDescription: its picking mesh's triangles in model space (bridge pieces, docks,
98    /// porches).
99    pub floor: Option<std::sync::Arc<Vec<[[f32; 3]; 3]>>>,
100    // +0x28
101    /// FloorDescription: the floor is added on activation (bridge pieces); the others are added
102    /// when their MultiObject is built.
103    ///
104    /// Original: `FUN_140124810`, `FUN_14012aa30`.
105    pub floor_on_activate: bool,
106    /// TerraformDescription (tunnels).
107    pub terraform: Option<crate::world::terraform::TerraformTemplate>,
108    /// TornadoDescription.
109    pub tornado: Option<crate::disasters::tornado::TornadoTemplate>,
110    /// QuarryDescription.
111    pub quarry: Option<crate::production::quarry::QuarryTemplate>,
112    /// Has a TradeComponent (the trading post).
113    pub trading_post: bool,
114    /// Has a TrackerComponent (workplaces whose production the window shows).
115    pub tracker: bool,
116    // FUN_1400e02d0 sets only the MapComponent.
117    /// Whether this is a fenced area's template (it has a `createfenced` component). Its model is
118    /// never placed, so it stays at the origin with no rotation; `Placed::yaw` is its rotation on
119    /// the map.
120    pub fenced_area: bool,
121}
122
123/// The kinds of scheduled component the port runs for placed entities.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum ScheduledComponent {
126    /// The growth update.
127    Growth,
128    /// The spawn update.
129    Spawn,
130}
131
132/// A placed entity.
133#[derive(Debug, Clone, PartialEq)]
134pub struct Placed {
135    /// Index into the template table.
136    pub template: usize,
137    // +0x1f
138    /// Entity: actual registration bucket, which can differ from its own template.
139    pub bucket: usize,
140    /// Map cell.
141    pub cell: (i32, i32),
142    // +0x2c/+0x2e
143    /// MapComponent, after rotation; profile yards have variable dimensions.
144    pub footprint: (i32, i32),
145    /// Map position (cells from the terrain centre) and ground height.
146    pub position: [f32; 3],
147    /// The heading, in degrees.
148    pub yaw: f32,
149    /// The model variant.
150    pub variant: usize,
151    /// The mesh.
152    pub mesh: usize,
153    // NaturalResourceComponent +0x28; the constructor FUN_140036eb0 sets 1.0.
154    /// How grown the resource is (1.0 by default).
155    pub growth: f32,
156    /// The growth component, if any.
157    pub growth_state: Option<Growth>,
158    /// The spawn component, if any.
159    pub spawn_state: Option<Spawn>,
160    /// Whether it is still in the world.
161    pub alive: bool,
162    /// NaturalResourceComponent flag 0x200000.
163    ///
164    /// Original: `FUN_14012bc50`.
165    pub removal_requested: bool,
166    /// The animation it plays, if any.
167    pub animation: Option<Playback>,
168    // MeshInstance +0x134
169    /// Mesh instance scale (`MeshInstance`).
170    pub scale: [f32; 4],
171}
172
173impl Placed {
174    // +0x148
175    /// The entity transform: `FromYawPitchOffset(yaw, 0, position)`, or for a fenced area, whose
176    /// model is never placed, the identity at its position.
177    pub fn model(&self, t: &Template) -> crate::math::Transform {
178        if t.fenced_area {
179            crate::math::Transform {
180                q: [0.0, 0.0, 0.0, 1.0],
181                p: self.position,
182            }
183        } else {
184            crate::math::Transform::of_model(self.yaw, self.position)
185        }
186    }
187}
188
189/// Stamps for [`Cells::types_revision`], unique across every `Cells`.
190static TYPES_REVISION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
191
192fn next_types_revision() -> u64 {
193    TYPES_REVISION.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
194}
195
196// Game +0xf8
197/// The gameplay map cells seeding reads and writes (`Game`, 48-byte cells).
198pub struct Cells {
199    /// The map's size in cells.
200    pub size: usize,
201    // +0x29
202    /// The type of each cell. Change it only with [`Cells::set_type`], which keeps [`Cells::types_revision`] current.
203    pub types: Vec<CellType>,
204    /// A new stamp whenever `types` may have changed (a new map, any `set_type`), so readers
205    /// such as the path regions can skip comparing the whole map when it has not.
206    pub types_revision: u64,
207    // +0x08
208    /// Entity on the cell (index into the placed list).
209    pub objects: Vec<Option<usize>>,
210    // +0x00; +0x08; used by FUN_1400a4aa0.
211    /// The entity occupying each cell, for placement checks (separate from the objects stamped
212    /// into the cell).
213    pub occupants: Vec<Option<usize>>,
214    // +0x28
215    /// Placement admission flag, deliberately unnamed.
216    pub flags: Vec<u8>,
217    // +0x10
218    /// External ComponentDescription reference from a growth transition.
219    pub previous_template: Vec<Option<usize>>,
220    // +0x2c; zero in FUN_14001b3f0's constructor.
221    /// A byte per cell that growth adjusts.
222    pub growth_bytes: Vec<u8>,
223    // +0x1c..+0x27
224    /// Per-cell layer counters: 0..=5 the HappinessComponent kinds, 8 the fishing docks.
225    ///
226    /// Original: `FUN_1400a4e60`.
227    pub layers: Vec<[u8; 12]>,
228    // +0x90
229    /// Map: registrations per layer.
230    pub layer_totals: [i16; 12],
231    // +0x2a
232    /// The road kind the cell has or will have (0 stone, 1 dirt; `0xff` none).
233    pub road_kind: Vec<u8>,
234    // +0x2b
235    /// The road kind built (`0x80` while it is being built).
236    pub road_built: Vec<u8>,
237    /// Bumped whenever a road is planned, taken back or finished (the road decals' rebuild).
238    ///
239    /// Original: `FUN_1400b4840`.
240    pub road_revision: u32,
241    // +0x2d
242    /// The floors (bridge decks) that characters walk on.
243    pub floors: crate::world::floor::Floors,
244    /// Cells that turned walkable or unwalkable, in the order they did: the path sectors' marks,
245    /// which every type write in the original makes on the spot.
246    ///
247    /// Original: `FUN_1400ae160`.
248    pub sector_marks: Vec<u32>,
249}
250
251impl Cells {
252    // +0x00; +0x08
253    /// The entity a cell answers for, the occupant if there is one, else the object. EditTool
254    /// selection, the removal tool and the job code all read cells this way.
255    ///
256    /// Original: `FUN_1400a5750`.
257    pub fn entity_at(&self, i: usize) -> Option<usize> {
258        self.occupants[i].or(self.objects[i])
259    }
260
261    /// The cells of a map of `size × size` cells with these natural types.
262    pub fn new(size: usize, types: Vec<CellType>) -> Cells {
263        Cells {
264            size,
265            types_revision: next_types_revision(),
266            objects: vec![None; types.len()],
267            occupants: vec![None; types.len()],
268            flags: vec![0; types.len()],
269            previous_template: vec![None; types.len()],
270            growth_bytes: vec![0; types.len()],
271            layers: vec![[0; 12]; types.len()],
272            layer_totals: [0; 12],
273            road_kind: vec![0xff; types.len()],
274            road_built: vec![0; types.len()],
275            floors: crate::world::floor::Floors::new(types.len()),
276            types,
277            road_revision: 0,
278            sector_marks: Vec::new(),
279        }
280    }
281
282    // +0x29; each writer tests the masks 0xe1f and 0x1e0 before FUN_1400ae160.
283    /// Write a cell's type. When the cell turns walkable or unwalkable, its path sector is marked
284    /// for rebuilding.
285    pub fn set_type(&mut self, i: usize, ty: CellType) {
286        let walk = |t: CellType| (1u32 << (t.0 & 0x1f)) & crate::pathfind::WALKABLE != 0;
287        if walk(self.types[i]) != walk(ty) {
288            self.sector_marks.push(i as u32);
289        }
290        self.types[i] = ty;
291        self.types_revision = next_types_revision();
292    }
293
294    /// Add `delta` to `layer` on every cell within `radius` of `(cx, cy)` (a byte, wrapping) and to
295    /// the layer's total.
296    ///
297    /// Original: `FUN_1400a4e60`.
298    pub fn add_layer(&mut self, layer: usize, cx: i32, cy: i32, radius: i32, delta: i32) {
299        let n = self.size as i32;
300        for y in cy - radius..=cy + radius {
301            for x in cx - radius..=cx + radius {
302                let (dx, dy) = (cx - x, cy - y);
303                if x < 0 || y < 0 || x >= n || y >= n || dx * dx + dy * dy > radius * radius {
304                    continue;
305                }
306                let b = &mut self.layers[(n * y + x) as usize][layer];
307                *b = b.wrapping_add(delta as u8);
308            }
309        }
310        self.layer_totals[layer] = self.layer_totals[layer].wrapping_add(delta as i16);
311    }
312}
313
314/// `DAT_140178814`, `DAT_14017884c`.
315const HALF: f32 = 0.5;
316const ONE: f32 = 1.0;
317/// `DAT_140178920`: yaw range (degrees) of the jittered transform.
318pub(crate) const YAW_RANGE: f32 = 180.0;
319/// `FUN_1400560e0` spot check: normal z and height tolerance (`DAT_140178840`, `DAT_140178948`).
320const SPAWN_NORMAL: f32 = 0.98;
321const SPAWN_HEIGHT_TOLERANCE: f32 = 1000.0;
322
323/// What the growth and spawn updates need: the cells, the templates, the random numbers, and the
324/// lists to fill.
325pub struct Seeder<'a> {
326    /// The object templates.
327    pub templates: &'a [Template],
328    /// The ground's heights.
329    pub terrain: &'a HeightGrid<'a>,
330    /// The gameplay map.
331    pub cells: &'a mut Cells,
332    /// The game's random numbers.
333    pub rng: &'a mut Random,
334    /// The placed objects.
335    pub placed: &'a mut Vec<Placed>,
336    /// The entities to remove, in the order they asked. They are removed after all buckets.
337    ///
338    /// Original: drained by `FUN_1400c9560`.
339    pub removed: &'a mut Vec<usize>,
340    /// `AnimAudioEvent`s that passed their probability: owning entity and the SoundEffect to play
341    /// there.
342    ///
343    /// Original: `FUN_14008d310`.
344    pub animation_events: &'a mut Vec<(usize, String)>,
345}
346
347impl<'a> Seeder<'a> {
348    fn n(&self) -> i32 {
349        self.cells.size as i32
350    }
351
352    /// Map position of a cell centre: `cell − (n/2 − 0.5)`.
353    fn cell_position(&self, index: i32) -> (f32, f32) {
354        let n = self.n();
355        let c = (n >> 1) as f32 - HALF;
356        ((index % n) as f32 - c, (index / n) as f32 - c)
357    }
358
359    /// `FUN_1400a48b0(.., 0, normal)`: the ground, or a floor above it, and the normal's z.
360    fn ground(&self, x: f32, y: f32) -> (f32, f32) {
361        let mut normal = [0.0f32; 3];
362        let h = self
363            .cells
364            .floors
365            .ground_normal(self.cells.size, self.terrain, x, y, &mut normal);
366        (h, normal[2])
367    }
368}
369
370#[cfg(test)]
371mod tests;