Skip to main content

unbanished_game/production/
farm.rs

1//! Crop fields: CropFieldComponent, and the works `PlantArea`, `TendArea` and the harvest work. See
2//! docs/FARMING.md.
3//!
4//! A field waits for spring (state 2), plants its crop on every cell (9), tends it while it grows
5//! (10) and harvests it when ripe or in autumn (11). The ClearArea controller's state 0x15 then
6//! clears what is left before the field waits again.
7//!
8//! Original: `FUN_140120620`, `0x140167cb0`, `0x140167db0`, `0x1401678c0`.
9mod harvest;
10mod planting;
11
12// vtable 0x1401692f0
13
14use std::collections::{BTreeMap, BTreeSet};
15
16use crate::behaviour::character::{Action, Component, Message, MoveTo};
17use crate::pathfind::{nearest_neighbour, WALKABLE};
18use crate::scheduler::{seconds, ticks};
19use crate::town::Sim;
20use crate::work::construction::Callbacks;
21use crate::work::jobs::{Work, WorkKind};
22
23/// `DAT_1401788d4`: the warmth planting and the autumn harvest need (°F).
24const WARM: f32 = 33.0;
25
26// +0x58
27/// One cell of a field (0x20 bytes).
28#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
29pub struct CropCell {
30    // +0x00
31    /// The map cell.
32    pub cell: i32,
33    // +0x04
34    /// 0 to plant, 1 growing, 2 done (harvested or lost).
35    pub state: i32,
36    // +0x08
37    /// The crop entity.
38    pub entity: Option<usize>,
39    // +0x18
40    /// Harvesting this cell leaves a pile.
41    pub pile: bool,
42}
43
44// +0x48..+0x60
45/// CropFieldComponent.
46#[derive(Debug, Clone, Default, PartialEq)]
47pub struct CropField {
48    // +0x48
49    /// Farming on (the field's toggle).
50    pub enabled: bool,
51    // +0x49
52    /// The crop leaves piles (its natural resource names a raw material).
53    pub piles: bool,
54    // +0x50
55    /// The crop (natural-resource template), chosen in the field's window.
56    pub crop: Option<usize>,
57    /// The field's cells.
58    pub cells: Vec<CropCell>,
59}
60
61// +0x24; +0x20
62/// CropFieldDescription (versioned): a tending visit's growth (as a share of the crop's growing
63/// time) and, from version 1, the stock slot.
64///
65/// Original: `FUN_140120740`.
66#[derive(Debug, Clone, Copy, Default, PartialEq)]
67pub struct CropFieldTemplate {
68    /// A tending visit's growth, as a share of the crop's growing time.
69    pub tend: f32,
70    /// The stock slot (version 1).
71    pub group: i32,
72}
73
74// +0x48; +0x58; +0x68
75/// The work of planting (`PlantArea`) or harvesting a field: the cells claimed (index → worker),
76/// the cells still to do, and, for planting, the crop.
77#[derive(Debug, Clone, Default, PartialEq)]
78pub struct AreaWork {
79    /// The cells claimed: cell index → worker.
80    pub claims: BTreeMap<i32, usize>,
81    /// The cells still to do.
82    pub need: Vec<bool>,
83    /// The crop, for planting.
84    pub crop: Option<usize>,
85}
86
87impl Sim<'_, '_> {
88    fn month(&self) -> i32 {
89        (self.calendar / 3600.0 * 12.0) as i32
90    }
91
92    fn field(&self, e: usize) -> Option<&CropField> {
93        self.sites.get(&e)?.crop_field.as_ref()
94    }
95
96    fn field_mut(&mut self, e: usize) -> Option<&mut CropField> {
97        self.sites.get_mut(&e)?.crop_field.as_mut()
98    }
99
100    fn set_workplace_enabled(&mut self, e: usize, on: bool) {
101        self.enable_workplace(e, on);
102    }
103
104    /// State 2 enter (`FUN_14011fdf0`): the workplace follows the toggle.
105    pub(crate) fn crop_enter2(&mut self, e: usize) {
106        let on = self.field(e).is_some_and(|f| f.enabled);
107        self.set_workplace_enabled(e, on);
108    }
109
110    /// State 2 update (`FUN_14011fd30`): switched on, warm and in spring (months 0–2), plant.
111    pub(crate) fn crop_update2(&mut self, e: usize) {
112        // jb at 0x14011fd6b: a NaN temperature is too cold to plant.
113        #[allow(clippy::neg_cmp_op_on_partial_ord)]
114        if !self.field(e).is_some_and(|f| f.enabled) || !(WARM <= self.temperature) {
115            return;
116        }
117        let month = self.month();
118        if month >= 0 && 8 < (month - 3) as u32 {
119            self.crop_plant_now(e);
120        }
121    }
122
123    /// Plant now (also the field's message 3 in state 2).
124    ///
125    /// Original: `FUN_14011fc80`.
126    pub fn crop_plant_now(&mut self, e: usize) {
127        let on = self.field(e).is_some_and(|f| f.enabled);
128        self.set_workplace_enabled(e, on);
129        self.machine(e).request(9);
130    }
131
132    // +0x58
133    /// CropUI slot.
134    ///
135    /// Original: `FUN_1400b7df0`.
136    pub fn set_crop(&mut self, e: usize, crop: Option<usize>) {
137        let Some(old) = self.field(e).map(|f| f.crop) else {
138            return;
139        };
140        if old.is_none() && crop.is_some() {
141            self.field_action(e, 2);
142        }
143        if let Some(f) = self.field_mut(e) {
144            f.crop = crop;
145        }
146    }
147
148    // +0x70
149    /// CropFieldComponent slot: 0 sends the machine message 3 (handled in state 2: plant now), 1
150    /// message 4 (state 10: harvest now), 2 switches farming on or off.
151    ///
152    /// Original: `FUN_140120190`.
153    pub fn field_action(&mut self, e: usize, action: i32) {
154        let Some(m) = self.sites.get(&e).map(|s| &s.machine) else {
155            return;
156        };
157        let state = m.state;
158        match action {
159            0 if state == 2 => self.crop_plant_now(e),
160            1 if state == 0xa => self.crop_harvest_now(e),
161            2 => {
162                let on = match self.field_mut(e) {
163                    Some(f) => {
164                        f.enabled = !f.enabled;
165                        f.enabled
166                    }
167                    None => return,
168                };
169                self.set_workplace_enabled(e, on);
170            }
171            _ => {}
172        }
173    }
174
175    /// The field's message 4 in state 10: harvest now.
176    ///
177    /// Original: `FUN_14011f3d0`.
178    pub fn crop_harvest_now(&mut self, e: usize) {
179        self.machine(e).request(0xb);
180    }
181
182    /// State 9 enter (`FUN_14011f7e0`): one cell per footprint cell (rows, then columns);
183    /// every `pile_spacing`-th cell leaves a pile, shuffled with `Rand(count)` swaps; then the
184    /// planting work.
185    pub(crate) fn crop_enter9(&mut self, jobs: &mut crate::work::jobs::Jobs, e: usize) {
186        let n = self.size as i32;
187        let (x0, y0) = self.placed[e].cell;
188        let (w, h) = self.placed[e].footprint;
189        let mut cells = Vec::with_capacity((w * h) as usize);
190        for row in 0..h {
191            for col in 0..w {
192                cells.push(CropCell {
193                    cell: (row + y0) * n + col + x0,
194                    ..Default::default()
195                });
196            }
197        }
198        let crop = self.field(e).and_then(|f| f.crop);
199        let spacing = crop
200            .and_then(|t| self.templates[t].pile)
201            .and_then(|p| self.templates[p].pile_material)
202            .map(|m| self.materials[m].pile_spacing);
203        let count = cells.len();
204        let mut flags: Vec<bool> = match spacing {
205            Some(k) => (0..count as i32).map(|i| k != 0 && i % k == 0).collect(),
206            None => vec![false; count],
207        };
208        for i in 0..count {
209            let r = self.rng.rand_below(count as u32) as usize;
210            if i != r {
211                flags.swap(i, r);
212            }
213        }
214        for (c, f) in cells.iter_mut().zip(flags) {
215            c.pile = f;
216        }
217        if let Some(field) = self.field_mut(e) {
218            field.piles = spacing.is_some();
219            field.cells = cells;
220        }
221        // `FUN_140129c20`: the field's footprint is lifted, so crops can stand on it.
222        self.unstamp(e);
223        let profession = self.profession_of(e);
224        let work = Work::new(
225            e,
226            self.rect_cell(e),
227            profession,
228            WorkKind::PlantArea(AreaWork {
229                claims: BTreeMap::new(),
230                need: vec![true; count],
231                crop,
232            }),
233        );
234        self.set_work(jobs, e, work, 1, false);
235    }
236
237    /// The workplace's profession (slot `+0x50` of the works).
238    fn profession_of(&self, e: usize) -> usize {
239        self.workforce
240            .workplaces
241            .get(&e)
242            .and_then(|w| w.profession)
243            .unwrap_or(self.professions.laborer)
244    }
245
246    /// `FUN_14011fef0`: a growing cell whose crop has gone (or been replaced) is done.
247    fn crop_refresh(&mut self, e: usize) {
248        let objects = &self.cells.objects;
249        let placed = &self.placed;
250        let templates = self.templates;
251        let Some(field) = self.sites.get_mut(&e).and_then(|s| s.crop_field.as_mut()) else {
252            return;
253        };
254        for c in field.cells.iter_mut().filter(|c| c.state == 1) {
255            let here = objects[c.cell as usize];
256            let alive = here.is_some_and(|o| {
257                templates[placed[o].template].natural.is_some() && Some(o) == c.entity
258            });
259            if !alive {
260                c.state = 2;
261                c.entity = None;
262            }
263        }
264    }
265
266    fn crop_counts(&mut self, e: usize) -> (usize, usize, usize) {
267        self.crop_refresh(e);
268        let Some(field) = self.field(e) else {
269            return (0, 0, 0);
270        };
271        let growing = field.cells.iter().filter(|c| c.state == 1).count();
272        let done = field.cells.iter().filter(|c| c.state == 2).count();
273        (field.cells.len(), growing, done)
274    }
275
276    /// State 9 update (`FUN_14011f6b0`): everything lost → clear (0x15); everything planted
277    /// or lost → grow (10).
278    pub(crate) fn crop_update9(&mut self, jobs: &mut crate::work::jobs::Jobs, e: usize) {
279        let (total, growing, done) = self.crop_counts(e);
280        if done == total {
281            self.remove_work(jobs, e);
282            self.machine(e).request(0x15);
283        } else if growing + done == total {
284            self.remove_work(jobs, e);
285            self.machine(e).request(10);
286        }
287    }
288
289    /// State 10 enter (`FUN_14011f5d0`): the tending work.
290    pub(crate) fn crop_enter10(&mut self, jobs: &mut crate::work::jobs::Jobs, e: usize) {
291        let profession = self.profession_of(e);
292        let work = Work::new(
293            e,
294            self.rect_cell(e),
295            profession,
296            WorkKind::TendArea(crate::production::herbalist::HerbalistWork::default()),
297        );
298        self.set_work(jobs, e, work, 1, false);
299    }
300
301    /// State 10 exit (`FUN_14011f440`).
302    pub(crate) fn crop_exit10(&mut self, jobs: &mut crate::work::jobs::Jobs, e: usize) {
303        let id = self.sites[&e].work_id;
304        if id >= 0 && jobs.works.contains_key(&id) {
305            self.remove_work(jobs, e);
306        }
307    }
308
309    /// `FUN_1401208e0`: the mean growth of the growing cells (at most 1 each) over all cells.
310    fn crop_ripeness(&mut self, e: usize) -> f32 {
311        self.crop_counts(e);
312        self.field(e).map_or(0.0, |f| ripeness(f, self.placed))
313    }
314
315    /// State 10 update (`FUN_14011f4a0`): everything lost → clear; with piles and switched
316    /// on, harvest when ripe, or when warm in months 6–11.
317    pub(crate) fn crop_update10(&mut self, e: usize) {
318        let (total, _, done) = self.crop_counts(e);
319        if done == total {
320            self.machine(e).request(0x15);
321        }
322        let Some(field) = self.field(e) else { return };
323        if !field.enabled || !field.piles {
324            return;
325        }
326        let month = self.month();
327        let autumn = self.temperature >= WARM && month >= 0 && (month - 6) as u32 <= 5;
328        if !autumn && self.crop_ripeness(e) <= 0.99 {
329            return;
330        }
331        self.crop_harvest_now(e);
332    }
333
334    /// State 11 enter (`FUN_14011f330`): the harvest work (`FUN_1400f2990`).
335    pub(crate) fn crop_enter11(&mut self, jobs: &mut crate::work::jobs::Jobs, e: usize) {
336        let count = self.field(e).map_or(0, |f| f.cells.len());
337        let profession = self.profession_of(e);
338        let work = Work::new(
339            e,
340            self.rect_cell(e),
341            profession,
342            WorkKind::Harvest(AreaWork {
343                claims: BTreeMap::new(),
344                need: vec![true; count],
345                crop: None,
346            }),
347        );
348        self.set_work(jobs, e, work, 1, false);
349    }
350
351    /// State 11 update (`FUN_14011f250`): everything harvested → clear.
352    pub(crate) fn crop_update11(&mut self, jobs: &mut crate::work::jobs::Jobs, e: usize) {
353        let (total, _, done) = self.crop_counts(e);
354        if done == total {
355            self.remove_work(jobs, e);
356            self.machine(e).request(0x15);
357        }
358    }
359
360    // +0x2d
361    /// CropFieldComponent's message slot. Message 0: cell `index` was planted (its crop keeps the
362    /// cell's pile flag, NaturalResource); message 1: a tending visit advances the cell's crop by
363    /// `growing time × 300 s × tend`.
364    ///
365    /// Original: `FUN_140120020`.
366    pub fn crop_message(&mut self, e: usize, message: i32, index: i32) {
367        let Some(field) = self.field(e) else { return };
368        let Some(&c) = field.cells.get(index as usize) else {
369            return;
370        };
371        let here = self.cells.objects[c.cell as usize];
372        match message {
373            0 => {
374                if let Some(o) = here {
375                    self.keep_piles.insert(o, c.pile);
376                }
377                if let Some(cell) = self
378                    .field_mut(e)
379                    .and_then(|f| f.cells.get_mut(index as usize))
380                {
381                    cell.state = 1;
382                    cell.entity = here;
383                }
384            }
385            1 => {
386                let Some(o) = here else { return };
387                let tend = self.site_templates[self.sites[&e].template]
388                    .crop_field
389                    .map_or(0.0, |d| d.tend);
390                let template = self.placed[o].template;
391                let Some(g) = self.templates[template].growth.clone() else {
392                    return;
393                };
394                let dt = ticks(g.f28 * 300.0 * tend);
395                let temperature = self.temperature;
396                let p = &mut self.placed[o];
397                let Some(state) = &mut p.growth_state else {
398                    return;
399                };
400                let result = state.update(&g, &mut p.growth, dt, temperature, false);
401                // A terminal transition reached by tending, as the scheduled update handles
402                // it (`FUN_140125940`): the map byte, then the crop falls or goes (on the next
403                // animation pass).
404                if let Some(adjustment) = result.map_adjustment {
405                    let n = self.size;
406                    let (x, y) = self.placed[o].cell;
407                    let i = y as usize * n + x as usize;
408                    self.cells.growth_bytes[i] = crate::nature::growth::adjust_map_byte(
409                        self.cells.growth_bytes[i],
410                        adjustment,
411                    );
412                    self.cells.previous_template[i] = Some(template);
413                    let falls = self.templates[template]
414                        .natural
415                        .as_ref()
416                        .is_some_and(|nr| nr.flag);
417                    let p = &mut self.placed[o];
418                    p.removal_requested = true;
419                    if falls {
420                        p.animation = self.templates[template]
421                            .animations
422                            .get(p.variant)
423                            .and_then(Option::as_ref)
424                            .and_then(|g| g.clips.get(2))
425                            .map(|_| crate::behaviour::animation::Playback::new(2, 0));
426                    }
427                    *self.models_dirty = true;
428                }
429            }
430            _ => {}
431        }
432    }
433}
434
435/// `Sim::crop_ripeness` after the cells' refresh.
436///
437/// Original: `FUN_14011fef0`.
438pub fn ripeness(field: &CropField, placed: &[crate::nature::seeding::Placed]) -> f32 {
439    if field.cells.is_empty() {
440        return 0.0;
441    }
442    let sum: f32 = field
443        .cells
444        .iter()
445        .filter(|c| c.state == 1)
446        .filter_map(|c| c.entity)
447        .map(|o| placed[o].growth.min(1.0))
448        .sum();
449    sum / field.cells.len() as f32
450}