Skip to main content

nil_core/military/
mod.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4#[cfg(test)]
5mod tests;
6
7pub mod army;
8pub mod maneuver;
9pub mod squad;
10pub mod unit;
11
12use crate::continent::coord::Coord;
13use crate::continent::index::{ContinentIndex, ContinentKey};
14use crate::continent::size::ContinentSize;
15use crate::error::{Error, Result};
16use crate::military::army::personnel::ArmyPersonnel;
17use crate::military::army::{Army, ArmyId, collapse_armies};
18use crate::military::maneuver::{Maneuver, ManeuverId};
19use crate::military::squad::Squad;
20use crate::military::unit::stats::power::{AttackPower, DefensePower, Power};
21use crate::ranking::score::Score;
22use crate::resources::maintenance::Maintenance;
23use crate::ruler::Ruler;
24use itertools::Itertools;
25use serde::{Deserialize, Serialize};
26use std::collections::HashMap;
27
28#[derive(Clone, Debug, Deserialize, Serialize)]
29#[serde(rename_all = "camelCase")]
30#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
31pub struct Military {
32  continent: HashMap<ContinentIndex, Vec<Army>>,
33  continent_size: ContinentSize,
34  maneuvers: HashMap<ManeuverId, Maneuver>,
35}
36
37impl Military {
38  pub(crate) fn new(size: ContinentSize) -> Self {
39    Self {
40      continent: HashMap::new(),
41      continent_size: size,
42      maneuvers: HashMap::new(),
43    }
44  }
45
46  pub(crate) fn spawn<K, R>(&mut self, key: K, owner: R, personnel: ArmyPersonnel)
47  where
48    K: ContinentKey,
49    R: Into<Ruler>,
50  {
51    let ruler: Ruler = owner.into();
52    let army = Army::builder()
53      .owner(ruler)
54      .personnel(personnel)
55      .build();
56
57    let index = key.into_index(self.continent_size);
58    self
59      .continent
60      .entry(index)
61      .or_default()
62      .push(army);
63
64    self.collapse_armies_in(index);
65  }
66
67  pub fn collapse_armies(&mut self) {
68    self
69      .continent
70      .values_mut()
71      .for_each(collapse_armies);
72
73    self
74      .continent
75      .retain(|_, armies| !armies.is_empty());
76  }
77
78  pub fn collapse_armies_in<K>(&mut self, key: K)
79  where
80    K: ContinentKey,
81  {
82    let index = key.into_index(self.continent_size);
83    if let Some(armies) = self.continent.get_mut(&index) {
84      collapse_armies(armies);
85    }
86  }
87
88  /// Creates a new instance containing only entries related to a given set of coords.
89  pub fn intersection<K, I>(&self, keys: I) -> Result<Self>
90  where
91    K: ContinentKey,
92    I: IntoIterator<Item = K>,
93  {
94    let mut military = Self::new(self.continent_size);
95    for key in keys {
96      let coord = key.into_coord(self.continent_size)?;
97      let index = coord.into_index(self.continent_size);
98      if let Some(armies) = self.continent.get(&index).cloned() {
99        military.continent.insert(index, armies);
100      }
101
102      let maneuvers = self
103        .maneuvers_at(coord)
104        .map(|maneuver| (maneuver.id(), maneuver.clone()));
105
106      military.maneuvers.extend(maneuvers);
107    }
108
109    Ok(military)
110  }
111
112  pub(crate) fn remove_army(&mut self, id: ArmyId) -> Result<Army> {
113    let (curr_vec, pos) = self
114      .continent
115      .values_mut()
116      .find_map(|armies| {
117        armies
118          .iter()
119          .position(|army| army.id() == id)
120          .map(|pos| (armies, pos))
121      })
122      .ok_or(Error::ArmyNotFound(id))?;
123
124    Ok(curr_vec.swap_remove(pos))
125  }
126
127  pub(crate) fn remove_armies<I>(&mut self, armies: I) -> Result<Vec<Army>>
128  where
129    I: IntoIterator<Item = ArmyId>,
130  {
131    armies
132      .into_iter()
133      .map(|id| self.remove_army(id))
134      .try_collect()
135  }
136
137  pub(crate) fn relocate_army<K>(&mut self, id: ArmyId, new_key: K) -> Result<()>
138  where
139    K: ContinentKey,
140  {
141    let army = self.remove_army(id)?;
142    let index = new_key.into_index(self.continent_size);
143    self
144      .continent
145      .entry(index)
146      .or_default()
147      .push(army);
148
149    self.collapse_armies_in(index);
150
151    Ok(())
152  }
153
154  pub fn army(&self, id: ArmyId) -> Result<&Army> {
155    self
156      .armies()
157      .find(|army| army.id() == id)
158      .ok_or(Error::ArmyNotFound(id))
159  }
160
161  pub(crate) fn army_mut(&mut self, id: ArmyId) -> Result<&mut Army> {
162    self
163      .armies_mut()
164      .find(|army| army.id() == id)
165      .ok_or(Error::ArmyNotFound(id))
166  }
167
168  pub fn armies(&self) -> impl Iterator<Item = &Army> {
169    self.continent.values().flatten()
170  }
171
172  pub(crate) fn armies_mut(&mut self) -> impl Iterator<Item = &mut Army> {
173    self.continent.values_mut().flatten()
174  }
175
176  #[inline]
177  pub fn count_armies(&self) -> usize {
178    self.armies().count()
179  }
180
181  pub fn armies_at<K>(&self, key: K) -> &[Army]
182  where
183    K: ContinentKey,
184  {
185    let index = key.into_index(self.continent_size);
186    self
187      .continent
188      .get(&index)
189      .map(Vec::as_slice)
190      .unwrap_or_default()
191  }
192
193  pub(crate) fn armies_mut_at<K>(&mut self, key: K) -> &mut [Army]
194  where
195    K: ContinentKey,
196  {
197    let index = key.into_index(self.continent_size);
198    self
199      .continent
200      .get_mut(&index)
201      .map(Vec::as_mut_slice)
202      .unwrap_or_default()
203  }
204
205  pub fn count_armies_at<K>(&self, key: K) -> usize
206  where
207    K: ContinentKey,
208  {
209    self.armies_at(key).iter().count()
210  }
211
212  pub fn idle_armies_at<K>(&self, key: K) -> impl Iterator<Item = &Army>
213  where
214    K: ContinentKey,
215  {
216    self
217      .armies_at(key)
218      .iter()
219      .filter(|army| army.is_idle())
220  }
221
222  pub(crate) fn idle_armies_mut_at<K>(&mut self, key: K) -> impl Iterator<Item = &mut Army>
223  where
224    K: ContinentKey,
225  {
226    self
227      .armies_mut_at(key)
228      .iter_mut()
229      .filter(|army| army.is_idle())
230  }
231
232  pub fn armies_of<R>(&self, owner: R) -> impl Iterator<Item = &Army>
233  where
234    R: Into<Ruler>,
235  {
236    let owner: Ruler = owner.into();
237    self
238      .continent
239      .values()
240      .flatten()
241      .filter(move |army| army.is_owned_by(&owner))
242  }
243
244  #[inline]
245  pub fn personnel(&self, id: ArmyId) -> Result<&ArmyPersonnel> {
246    self.army(id).map(Army::personnel)
247  }
248
249  pub fn personnel_of<R>(&self, owner: R) -> impl Iterator<Item = &ArmyPersonnel>
250  where
251    R: Into<Ruler>,
252  {
253    self.armies_of(owner).map(Army::personnel)
254  }
255
256  pub fn fold_personnel_of<R>(&self, owner: R) -> ArmyPersonnel
257  where
258    R: Into<Ruler>,
259  {
260    self.personnel_of(owner).sum()
261  }
262
263  pub fn idle_personnel_at<K>(&self, key: K) -> impl Iterator<Item = &ArmyPersonnel>
264  where
265    K: ContinentKey,
266  {
267    self.idle_armies_at(key).map(Army::personnel)
268  }
269
270  pub fn fold_idle_personnel_at<K>(&self, key: K) -> ArmyPersonnel
271  where
272    K: ContinentKey,
273  {
274    self.idle_personnel_at(key).sum()
275  }
276
277  #[inline]
278  pub fn squads(&self, id: ArmyId) -> Result<Vec<Squad>> {
279    self
280      .personnel(id)
281      .cloned()
282      .map(ArmyPersonnel::to_vec)
283  }
284
285  pub fn idle_squads_at<K>(&self, key: K) -> Vec<Squad>
286  where
287    K: ContinentKey,
288  {
289    self.fold_idle_personnel_at(key).to_vec()
290  }
291
292  #[inline]
293  pub fn maneuver(&self, id: ManeuverId) -> Result<&Maneuver> {
294    self
295      .maneuvers
296      .get(&id)
297      .ok_or(Error::ManeuverNotFound(id))
298  }
299
300  fn maneuver_mut(&mut self, id: ManeuverId) -> Result<&mut Maneuver> {
301    self
302      .maneuvers
303      .get_mut(&id)
304      .ok_or(Error::ManeuverNotFound(id))
305  }
306
307  pub fn maneuvers(&self) -> impl Iterator<Item = &Maneuver> {
308    self.maneuvers.values()
309  }
310
311  /// Find all maneuvers whose origin or destination matches the specified coord.
312  pub fn maneuvers_at(&self, coord: Coord) -> impl Iterator<Item = &Maneuver> {
313    self
314      .maneuvers()
315      .filter(move |maneuver| maneuver.matches_coord(coord))
316  }
317
318  pub(crate) fn insert_maneuver(&mut self, maneuver: Maneuver) {
319    self
320      .maneuvers
321      .insert(maneuver.id(), maneuver);
322  }
323
324  pub(crate) fn advance_maneuvers(&mut self) -> Result<Vec<Maneuver>> {
325    let mut done = Vec::new();
326    for (id, maneuver) in &mut self.maneuvers {
327      maneuver.advance()?;
328
329      if maneuver.is_done() {
330        done.push(*id);
331      }
332    }
333
334    let done = done
335      .into_iter()
336      .filter_map(|id| self.maneuvers.remove(&id))
337      .collect_vec();
338
339    self.maneuvers.shrink_to_fit();
340
341    Ok(done)
342  }
343
344  pub(crate) fn cancel_maneuver(&mut self, id: ManeuverId) -> Result<()> {
345    self.maneuver_mut(id)?.cancel()
346  }
347
348  /// Retains only the maneuvers specified by the predicate.
349  pub(crate) fn retain_maneuvers<F>(&mut self, f: F)
350  where
351    F: Fn(&Maneuver) -> bool,
352  {
353    self
354      .maneuvers
355      .retain(|_, maneuver| f(maneuver));
356  }
357
358  pub fn score_of<R>(&self, owner: R) -> Score
359  where
360    R: Into<Ruler>,
361  {
362    self.armies_of(owner).sum()
363  }
364
365  pub fn maintenance_of<R>(&self, owner: R) -> Maintenance
366  where
367    R: Into<Ruler>,
368  {
369    self.armies_of(owner).sum()
370  }
371
372  pub fn power_of<R>(&self, owner: R) -> Power
373  where
374    R: Into<Ruler>,
375  {
376    self.armies_of(owner).sum()
377  }
378
379  pub fn attack_of<R>(&self, owner: R) -> AttackPower
380  where
381    R: Into<Ruler>,
382  {
383    self.armies_of(owner).sum()
384  }
385
386  pub fn defense_of<R>(&self, owner: R) -> DefensePower
387  where
388    R: Into<Ruler>,
389  {
390    self.armies_of(owner).sum()
391  }
392}