Skip to main content

unbanished_game/production/
orchard.rs

1//! Orchards: OrchardComponent, FruitComponent on the trees, and the works PlantOrchard, TendArea
2//! (as an orchard's) and fruit picking. See docs/FARMING.md "Orchards".
3//!
4//! Original: `FUN_140052a40`, `0x14015f5a0`, `0x140167d30`, `0x140167940`.
5mod states;
6mod work;
7
8// vtable 0x1401602a0
9
10use std::collections::BTreeMap;
11
12use crate::behaviour::character::{Action, Component, Message, MoveTo};
13use crate::pathfind::{nearest_neighbour, WALKABLE};
14use crate::production::farm::AreaWork;
15use crate::scheduler::{seconds, ticks};
16use crate::town::Sim;
17use crate::work::construction::Callbacks;
18use crate::work::jobs::{Jobs, Work, WorkKind};
19
20// +0x24; +0x28; +0x2c; +0x20
21/// OrchardDescription (versioned): the tree spacing, a tending visit's ripening (share of the
22/// ripening time), the stock slot (version 1).
23///
24/// Original: `FUN_140052c60`.
25#[derive(Debug, Clone, Copy, Default, PartialEq)]
26pub struct OrchardTemplate {
27    /// The tree spacing.
28    pub spacing: (i32, i32),
29    /// A tending visit's ripening, as a share of the ripening time.
30    pub tend: f32,
31    /// The stock slot (version 1).
32    pub group: i32,
33}
34
35// +0x50
36/// One tree slot (0x28 bytes).
37#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
38pub struct TreeSlot {
39    // +0x00
40    /// The map cell.
41    pub cell: i32,
42    // +0x04
43    /// 0 to plant, 1 standing, 2 lost.
44    pub state: i32,
45    // +0x08
46    /// The tree.
47    pub entity: Option<usize>,
48    // +0x20
49    /// Picked this harvest.
50    pub picked: bool,
51}
52
53// +0x48..+0x60
54/// OrchardComponent.
55#[derive(Debug, Clone, Default, PartialEq)]
56pub struct Orchard {
57    // +0x48
58    /// Tending on.
59    pub enabled: bool,
60    // +0x4c
61    /// The calendar year of the last harvest.
62    pub year: u32,
63    /// The tree slots.
64    pub trees: Vec<TreeSlot>,
65    // +0x60
66    /// The tree (natural-resource template), chosen in the orchard's window.
67    pub tree: Option<usize>,
68}
69
70// +0x30; +0x34
71/// FruitComponent ripeness (0–1) and picked this season.
72#[derive(Debug, Clone, Copy, Default, PartialEq)]
73pub struct Fruit {
74    /// The ripeness, from 0 to 1.
75    pub ripeness: f32,
76    /// Whether it was picked this season.
77    pub picked: bool,
78}
79
80// +0x20; +0x24; +0x28; +0x30
81/// FruitDescription: ripening time (× 300 s), the best temperature and its range, the fruit's raw
82/// material (pile template).
83///
84/// Original: `FUN_14004ab40`.
85#[derive(Debug, Clone, Copy, Default, PartialEq)]
86pub struct FruitTemplate {
87    /// The ripening time, in months of 300 seconds.
88    pub months: f32,
89    /// The best temperature.
90    pub best: f32,
91    /// The range of temperatures around the best one.
92    pub range: f32,
93    /// The fruit's pile template.
94    pub pile: Option<usize>,
95}
96
97/// FruitComponent's scheduled update. A picked tree waits for the next season (months 7–11 keep it
98/// picked). A grown tree ripens at `1 / (months × 300)` per second scaled by `1 − ((t − best) /
99/// range)²` (0 outside the range, −10 at or below 32 °F).
100///
101/// Measured: `tools/emu/ripen.py` (the original on 2,000 trees, NaN growths and ranges of 0
102/// among them).
103///
104/// Original: `FUN_14004a740`.
105pub fn ripen(f: &mut Fruit, d: &FruitTemplate, growth: f32, dt: i64, calendar: f32, t: f32) {
106    let rate = 1.0 / (d.months * 300.0);
107    let month = (calendar / 3600.0 * 12.0) as i32;
108    if f.picked && 4 < (month - 7) as u32 {
109        f.picked = false;
110    }
111    let distance = (t - d.best).abs() / d.range;
112    // ja at 0x14004a841 skips only when 1 > growth: a NaN growth counts as grown.
113    #[allow(clippy::neg_cmp_op_on_partial_ord)]
114    let weight = if !f.picked && !(growth < 1.0) {
115        if !(0.0..=1.0).contains(&distance) {
116            if t <= 32.0 {
117                -10.0
118            } else {
119                0.0
120            }
121        } else {
122            1.0 - distance * distance
123        }
124    } else {
125        0.0
126    };
127    let g = growth.min(1.0);
128    f.ripeness += seconds(dt) * g * rate * weight;
129    if f.ripeness < 0.0 {
130        f.ripeness = 0.0;
131    }
132    if 1.0 < f.ripeness {
133        f.ripeness = 1.0;
134    }
135}
136
137impl Sim<'_, '_> {
138    fn orchard(&self, e: usize) -> Option<&Orchard> {
139        self.sites.get(&e)?.orchard.as_ref()
140    }
141
142    fn orchard_mut(&mut self, e: usize) -> Option<&mut Orchard> {
143        self.sites.get_mut(&e)?.orchard.as_mut()
144    }
145
146    fn orchard_desc(&self, e: usize) -> OrchardTemplate {
147        self.site_templates[self.sites[&e].template]
148            .orchard
149            .unwrap_or_default()
150    }
151
152    /// `FUN_140052190`: a standing tree that has gone (or been replaced) is lost.
153    fn orchard_refresh(&mut self, e: usize) {
154        let objects = &self.cells.objects;
155        let placed = &self.placed;
156        let templates = self.templates;
157        let Some(o) = self.sites.get_mut(&e).and_then(|s| s.orchard.as_mut()) else {
158            return;
159        };
160        for t in o.trees.iter_mut().filter(|t| t.state == 1) {
161            let here = objects[t.cell as usize];
162            let alive = here.is_some_and(|x| {
163                templates[placed[x].template].natural.is_some() && Some(x) == t.entity
164            });
165            if !alive {
166                t.state = 2;
167                t.entity = None;
168            }
169        }
170    }
171
172    fn orchard_count(&mut self, e: usize, state: i32) -> usize {
173        self.orchard_refresh(e);
174        self.orchard(e)
175            .map_or(0, |o| o.trees.iter().filter(|t| t.state == state).count())
176    }
177
178    /// State 2 enter (`FUN_140051e90`): the workplace is off.
179    pub(crate) fn orchard_enter2(&mut self, e: usize) {
180        self.enable_workplace(e, false);
181    }
182
183    /// State 2 update (`FUN_140051e20`) and message 3 (`FUN_140051db0`): switched on, plant.
184    pub(crate) fn orchard_update2(&mut self, e: usize) {
185        if self.orchard(e).is_some_and(|o| o.enabled) {
186            self.machine(e).request(9);
187        }
188    }
189
190    /// Message 5: clear the orchard (0x14).
191    ///
192    /// Original: `FUN_140051d40`.
193    pub fn orchard_clear_now(&mut self, e: usize) {
194        self.machine(e).request(0x14);
195    }
196
197    /// Message 4: harvest now; nothing is picked yet this harvest.
198    ///
199    /// Original: `FUN_140051260`.
200    pub fn orchard_harvest_now(&mut self, e: usize) {
201        self.machine(e).request(0xb);
202        let year = self.year;
203        if let Some(o) = self.orchard_mut(e) {
204            for t in &mut o.trees {
205                t.picked = false;
206            }
207            o.year = year;
208        }
209    }
210
211    /// `FUN_140051fa0`: the mean ripeness of the standing trees (at most 1 each) over all.
212    fn orchard_ripeness(&self, e: usize) -> f32 {
213        self.orchard(e)
214            .map_or(0.0, |o| ripeness(o, &self.cells.objects, self.fruits))
215    }
216
217    /// `FUN_140051ee0`: switched on and not yet harvested this year, harvest when warm in months
218    /// 7–11 with any fruit, or when all is ripe (> 0.99).
219    fn orchard_harvest_due(&mut self, e: usize) -> bool {
220        let Some(o) = self.orchard(e) else {
221            return false;
222        };
223        if !o.enabled || self.year == o.year {
224            return false;
225        }
226        let month = (self.calendar / 3600.0 * 12.0) as i32;
227        let ripe = self.orchard_ripeness(e);
228        let autumn = self.temperature >= 33.0 && month >= 0 && ((month - 7) as u32) < 5;
229        if (autumn && 0.0 < ripe) || 0.99 < ripe {
230            self.orchard_harvest_now(e);
231            return true;
232        }
233        false
234    }
235
236    /// OrchardComponent's message slot. 0: slot `index` was planted (a tree with fruit stands, else
237    /// it is lost); 1: the tree was picked (its fruit starts again); 2: a tending visit ripens its
238    /// fruit by `ripening time × 300 s × tend`.
239    ///
240    /// Original: `FUN_1400522f0`.
241    pub fn orchard_message(&mut self, e: usize, message: i32, index: i32) {
242        let Some(slot) = self
243            .orchard(e)
244            .and_then(|o| o.trees.get(index as usize))
245            .copied()
246        else {
247            return;
248        };
249        let here = self.cells.objects[slot.cell as usize];
250        match message {
251            0 => {
252                let fruit = here.is_some_and(|x| {
253                    let t = &self.templates[self.placed[x].template];
254                    t.natural.is_some() && t.fruit.is_some()
255                });
256                if let Some(t) = self
257                    .orchard_mut(e)
258                    .and_then(|o| o.trees.get_mut(index as usize))
259                {
260                    if fruit {
261                        t.state = 1;
262                        t.entity = here;
263                    } else {
264                        t.state = 2;
265                    }
266                }
267            }
268            1 => {
269                self.orchard_refresh(e);
270                let Some(t) = self
271                    .orchard_mut(e)
272                    .and_then(|o| o.trees.get_mut(index as usize))
273                else {
274                    return;
275                };
276                t.picked = true;
277                if let Some(x) = t.entity {
278                    let f = self.fruits.entry(x).or_default();
279                    f.ripeness = 0.0;
280                    f.picked = true;
281                }
282            }
283            2 => {
284                self.orchard_refresh(e);
285                let Some(x) = here else { return };
286                let Some(fd) = self.templates[self.placed[x].template].fruit else {
287                    return;
288                };
289                let tend = self.orchard_desc(e).tend;
290                let dt = ticks(fd.months * 300.0 * tend);
291                let growth = self.placed[x].growth;
292                let (calendar, t) = (self.calendar, self.temperature);
293                ripen(
294                    self.fruits.entry(x).or_default(),
295                    &fd,
296                    growth,
297                    dt,
298                    calendar,
299                    t,
300                );
301            }
302            _ => {}
303        }
304    }
305
306    /// The orchard's buttons: 0 plant now (message 3, state 2), 1 harvest now (message 4, states 10
307    /// and 12), 2 tending on/off, 3 clear (message 5, states 9–12).
308    ///
309    /// Original: `FUN_140052500`.
310    pub fn orchard_action(&mut self, e: usize, action: i32) {
311        let Some(state) = self.sites.get(&e).map(|s| s.machine.state) else {
312            return;
313        };
314        match action {
315            0 if state == 2 => self.machine(e).request(9),
316            1 if state == 0xa || state == 0xc => self.orchard_harvest_now(e),
317            2 => {
318                let on = match self.orchard_mut(e) {
319                    Some(o) => {
320                        o.enabled = !o.enabled;
321                        o.enabled
322                    }
323                    None => return,
324                };
325                self.enable_workplace(e, on);
326            }
327            3 if matches!(state, 9..=0xc) => self.orchard_clear_now(e),
328            _ => {}
329        }
330    }
331
332    // +0x58
333    /// The orchard's tree list (as CropUI's slot): choosing the first tree switches tending on.
334    pub fn set_orchard_tree(&mut self, e: usize, tree: Option<usize>) {
335        let Some(old) = self.orchard(e).map(|o| o.tree) else {
336            return;
337        };
338        if old.is_none() && tree.is_some() {
339            self.orchard_action(e, 2);
340        }
341        if let Some(o) = self.orchard_mut(e) {
342            o.tree = tree;
343        }
344    }
345}
346
347/// `Sim::orchard_ripeness` of an orchard: with no trees, 1.
348pub fn ripeness(
349    o: &Orchard,
350    objects: &[Option<usize>],
351    fruits: &std::collections::BTreeMap<usize, Fruit>,
352) -> f32 {
353    if o.trees.is_empty() {
354        return 1.0;
355    }
356    let sum: f32 = o
357        .trees
358        .iter()
359        .filter(|t| t.state == 1 && t.entity.is_some())
360        .filter(|t| objects[t.cell as usize] == t.entity)
361        .map(|t| {
362            let x = t.entity.unwrap();
363            fruits.get(&x).map_or(0.0, |f| f.ripeness.min(1.0))
364        })
365        .sum();
366    sum / o.trees.len() as f32
367}