Skip to main content

nil_core/infrastructure/building/
mod.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4pub mod academy;
5pub mod farm;
6pub mod iron_mine;
7pub mod prefecture;
8pub mod quarry;
9pub mod sawmill;
10pub mod silo;
11pub mod stable;
12pub mod wall;
13pub mod warehouse;
14pub mod workshop;
15
16use crate::error::{Error, Result};
17use crate::infrastructure::requirements::InfrastructureRequirements;
18use crate::ranking::score::Score;
19use crate::resources::prelude::*;
20use derive_more::{Deref, Into};
21use nil_num::growth::growth;
22use serde::{Deserialize, Serialize};
23use std::cmp;
24use std::collections::HashMap;
25use std::ops::{Add, AddAssign, Neg, Sub, SubAssign};
26use strum::{EnumIs, EnumIter};
27use subenum::subenum;
28
29pub trait Building: Send + Sync {
30  fn id(&self) -> BuildingId;
31
32  /// Checks whether the building is enabled.
33  fn is_enabled(&self) -> bool;
34  /// Enables or disables the building.
35  fn toggle(&mut self, enabled: bool);
36
37  /// Current building level.
38  fn level(&self) -> BuildingLevel;
39  /// Minimum building level.
40  fn min_level(&self) -> BuildingLevel;
41  /// Maximum building level.
42  fn max_level(&self) -> BuildingLevel;
43  /// Sets the building's level while ensuring it remains within the level limit.
44  fn set_level(&mut self, level: BuildingLevel);
45
46  /// Sets the building to its **minimum** level.
47  fn set_min_level(&mut self) {
48    self.set_level(self.min_level());
49  }
50
51  /// Sets the building to its **maximum** level.
52  fn set_max_level(&mut self) {
53    self.set_level(self.max_level());
54  }
55
56  /// Increases the building level by one, if possible.
57  fn increase_level(&mut self) {
58    self.increase_level_by(1);
59  }
60
61  /// Increases the level of the building by a certain amount, if possible.
62  fn increase_level_by(&mut self, amount: u8);
63
64  /// Decreases the building level by one, if possible.
65  fn decrease_level(&mut self) {
66    self.decrease_level_by(1);
67  }
68
69  /// Decreases the level of the building by a certain amount, if possible.
70  fn decrease_level_by(&mut self, amount: u8);
71
72  /// Checks whether the building is at its minimum level.
73  fn is_min_level(&self) -> bool {
74    self.level() == self.min_level()
75  }
76
77  /// Checks whether the building is at its maximum level.
78  fn is_max_level(&self) -> bool {
79    self.level() >= self.max_level()
80  }
81
82  /// Total cost for the **minimum** level of the building.
83  fn min_cost(&self) -> Cost;
84  /// Total cost for the **maximum** level of the building.
85  fn max_cost(&self) -> Cost;
86  /// Percentage of the total cost related to wood.
87  fn wood_ratio(&self) -> ResourceRatio;
88  /// Percentage of the total cost related to stone.
89  fn stone_ratio(&self) -> ResourceRatio;
90  /// Percentage of the total cost related to iron.
91  fn iron_ratio(&self) -> ResourceRatio;
92
93  /// Building maintenance tax at its current level.
94  fn maintenance(&self, stats: &BuildingStatsTable) -> Result<Maintenance>;
95  /// Proportion of the base cost used as a maintenance tax.
96  fn maintenance_ratio(&self) -> MaintenanceRatio;
97
98  /// Workforce required for the **minimum** level of the building.
99  fn min_workforce(&self) -> Workforce;
100  /// Workforce required for the **maximum** level of the building.
101  fn max_workforce(&self) -> Workforce;
102
103  // Current score.
104  fn score(&self, stats: &BuildingStatsTable) -> Result<Score>;
105  // Building score at its **minimum** level.
106  fn min_score(&self) -> Score;
107  // Building score at its **maximum** level.
108  fn max_score(&self) -> Score;
109
110  /// Levels required to construct the building.
111  fn infrastructure_requirements(&self) -> &InfrastructureRequirements;
112
113  fn is_civil(&self) -> bool {
114    self.id().is_civil()
115  }
116
117  fn is_military(&self) -> bool {
118    self.id().is_military()
119  }
120
121  fn is_mine(&self) -> bool {
122    self.id().is_mine()
123  }
124
125  fn is_storage(&self) -> bool {
126    self.id().is_storage()
127  }
128}
129
130#[subenum(CivilBuildingId, MilitaryBuildingId, MineId, StorageId)]
131#[derive(
132  Clone, Copy, Debug, strum::Display, EnumIs, EnumIter, PartialEq, Eq, Hash, Deserialize, Serialize,
133)]
134#[serde(rename_all = "kebab-case")]
135#[strum(serialize_all = "kebab-case")]
136pub enum BuildingId {
137  #[subenum(MilitaryBuildingId)]
138  Academy,
139
140  #[subenum(CivilBuildingId, MineId)]
141  Farm,
142
143  #[subenum(CivilBuildingId, MineId)]
144  IronMine,
145
146  #[subenum(CivilBuildingId)]
147  Prefecture,
148
149  #[subenum(CivilBuildingId, MineId)]
150  Quarry,
151
152  #[subenum(CivilBuildingId, MineId)]
153  Sawmill,
154
155  #[subenum(CivilBuildingId, StorageId)]
156  Silo,
157
158  #[subenum(MilitaryBuildingId)]
159  Stable,
160
161  Wall,
162
163  #[subenum(CivilBuildingId, StorageId)]
164  Warehouse,
165
166  #[subenum(MilitaryBuildingId)]
167  Workshop,
168}
169
170impl BuildingId {
171  #[inline]
172  pub fn is_civil(self) -> bool {
173    CivilBuildingId::try_from(self).is_ok()
174  }
175
176  #[inline]
177  pub fn is_military(self) -> bool {
178    MilitaryBuildingId::try_from(self).is_ok()
179  }
180
181  #[inline]
182  pub fn is_mine(self) -> bool {
183    MineId::try_from(self).is_ok()
184  }
185
186  #[inline]
187  pub fn is_storage(self) -> bool {
188    StorageId::try_from(self).is_ok()
189  }
190}
191
192/// Information about a building at a given level.
193#[derive(Clone, Debug, Deserialize, Serialize)]
194#[serde(rename_all = "camelCase")]
195pub struct BuildingStats {
196  pub level: BuildingLevel,
197  pub cost: Cost,
198  pub resources: Resources,
199  pub maintenance: Maintenance,
200  pub workforce: Workforce,
201  pub score: Score,
202}
203
204#[derive(Clone, Debug, Deserialize, Serialize)]
205#[serde(rename_all = "camelCase")]
206pub struct BuildingStatsTable {
207  id: BuildingId,
208  min_level: BuildingLevel,
209  max_level: BuildingLevel,
210  table: HashMap<BuildingLevel, BuildingStats>,
211}
212
213impl BuildingStatsTable {
214  pub(crate) fn new(building: &dyn Building) -> Self {
215    let min_level = building.min_level();
216    let max_level = building.max_level();
217    let mut table = HashMap::with_capacity((max_level.0).into());
218
219    let mut cost = f64::from(building.min_cost());
220    let cost_growth = growth()
221      .floor(cost)
222      .ceil(building.max_cost())
223      .max_level(max_level)
224      .call();
225
226    let mut workforce = f64::from(building.min_workforce());
227    let workforce_growth = growth()
228      .floor(workforce)
229      .ceil(building.max_workforce())
230      .max_level(max_level)
231      .call();
232
233    let mut score = f64::from(building.min_score());
234    let score_growth = growth()
235      .floor(score)
236      .ceil(building.max_score())
237      .max_level(max_level)
238      .call();
239
240    let wood_ratio = *building.wood_ratio();
241    let stone_ratio = *building.stone_ratio();
242    let iron_ratio = *building.iron_ratio();
243
244    let maintenance_ratio = *building.maintenance_ratio();
245    let mut maintenance = cost * maintenance_ratio;
246
247    for level in 1..=max_level.0 {
248      let level = BuildingLevel::new(level);
249      let resources = Resources {
250        food: Food::MIN,
251        iron: Iron::from((cost * iron_ratio).round()),
252        stone: Stone::from((cost * stone_ratio).round()),
253        wood: Wood::from((cost * wood_ratio).round()),
254      };
255
256      table.insert(
257        level,
258        BuildingStats {
259          level,
260          cost: Cost::from(cost.round()),
261          resources,
262          maintenance: Maintenance::from(maintenance.round()),
263          workforce: Workforce::from(workforce.round()),
264          score: Score::from(score.round()),
265        },
266      );
267
268      debug_assert!(cost.is_normal());
269      debug_assert!(workforce.is_normal());
270
271      debug_assert!(maintenance.is_finite());
272      debug_assert!(maintenance >= 0.0);
273
274      debug_assert!(score.is_finite());
275      debug_assert!(score >= 0.0);
276
277      cost += cost * cost_growth;
278      workforce += workforce * workforce_growth;
279      score += score * score_growth;
280
281      maintenance = cost * maintenance_ratio;
282    }
283
284    table.shrink_to_fit();
285
286    Self {
287      id: building.id(),
288      min_level,
289      max_level,
290      table,
291    }
292  }
293
294  #[inline]
295  pub fn id(&self) -> BuildingId {
296    self.id
297  }
298
299  #[inline]
300  pub fn min_level(&self) -> BuildingLevel {
301    self.min_level
302  }
303
304  #[inline]
305  pub fn max_level(&self) -> BuildingLevel {
306    self.max_level
307  }
308
309  #[inline]
310  pub fn get(&self, level: BuildingLevel) -> Result<&BuildingStats> {
311    self
312      .table
313      .get(&level)
314      .ok_or(Error::BuildingStatsNotFoundForLevel(self.id, level))
315  }
316}
317
318#[derive(
319  Clone,
320  Copy,
321  Debug,
322  Default,
323  Deref,
324  derive_more::Display,
325  Into,
326  PartialEq,
327  Eq,
328  PartialOrd,
329  Ord,
330  Hash,
331  Deserialize,
332  Serialize,
333  nil_num::F64Ops,
334)]
335#[into(i16, i32, u8, u16, u32, u64, usize, f64)]
336pub struct BuildingLevel(u8);
337
338impl BuildingLevel {
339  pub const ZERO: BuildingLevel = BuildingLevel(0);
340
341  #[inline]
342  pub const fn new(level: u8) -> Self {
343    Self(level)
344  }
345}
346
347impl From<BuildingLevel> for i8 {
348  fn from(level: BuildingLevel) -> Self {
349    debug_assert!(i8::try_from(level.0).is_ok());
350    i8::try_from(level.0).unwrap_or(i8::MAX)
351  }
352}
353
354impl PartialEq<u8> for BuildingLevel {
355  fn eq(&self, other: &u8) -> bool {
356    self.0.eq(other)
357  }
358}
359
360impl PartialEq<BuildingLevel> for u8 {
361  fn eq(&self, other: &BuildingLevel) -> bool {
362    self.eq(&other.0)
363  }
364}
365
366impl PartialEq<f64> for BuildingLevel {
367  fn eq(&self, other: &f64) -> bool {
368    f64::from(self.0).eq(other)
369  }
370}
371
372impl PartialEq<BuildingLevel> for f64 {
373  fn eq(&self, other: &BuildingLevel) -> bool {
374    self.eq(&f64::from(other.0))
375  }
376}
377
378impl PartialOrd<u8> for BuildingLevel {
379  fn partial_cmp(&self, other: &u8) -> Option<cmp::Ordering> {
380    self.0.partial_cmp(other)
381  }
382}
383
384impl PartialOrd<BuildingLevel> for u8 {
385  fn partial_cmp(&self, other: &BuildingLevel) -> Option<cmp::Ordering> {
386    self.partial_cmp(&other.0)
387  }
388}
389
390impl PartialOrd<f64> for BuildingLevel {
391  fn partial_cmp(&self, other: &f64) -> Option<cmp::Ordering> {
392    f64::from(self.0).partial_cmp(other)
393  }
394}
395
396impl PartialOrd<BuildingLevel> for f64 {
397  fn partial_cmp(&self, other: &BuildingLevel) -> Option<cmp::Ordering> {
398    self.partial_cmp(&f64::from(other.0))
399  }
400}
401
402impl Add for BuildingLevel {
403  type Output = Self;
404
405  fn add(self, rhs: Self) -> Self {
406    Self(self.0.saturating_add(rhs.0))
407  }
408}
409
410impl Add<u8> for BuildingLevel {
411  type Output = Self;
412
413  fn add(self, rhs: u8) -> Self {
414    Self(self.0.saturating_add(rhs))
415  }
416}
417
418impl Add<i8> for BuildingLevel {
419  type Output = Self;
420
421  fn add(self, rhs: i8) -> Self {
422    Self(self.0.saturating_add_signed(rhs))
423  }
424}
425
426impl Add<BuildingLevelDiff> for BuildingLevel {
427  type Output = Self;
428
429  fn add(self, rhs: BuildingLevelDiff) -> Self {
430    self + rhs.0
431  }
432}
433
434impl AddAssign for BuildingLevel {
435  fn add_assign(&mut self, rhs: Self) {
436    *self = *self + rhs;
437  }
438}
439
440impl AddAssign<u8> for BuildingLevel {
441  fn add_assign(&mut self, rhs: u8) {
442    *self = *self + rhs;
443  }
444}
445
446impl AddAssign<i8> for BuildingLevel {
447  fn add_assign(&mut self, rhs: i8) {
448    *self = *self + rhs;
449  }
450}
451
452impl AddAssign<BuildingLevelDiff> for BuildingLevel {
453  fn add_assign(&mut self, rhs: BuildingLevelDiff) {
454    *self = *self + rhs;
455  }
456}
457
458impl Sub for BuildingLevel {
459  type Output = Self;
460
461  fn sub(self, rhs: Self) -> Self {
462    Self(self.0.saturating_sub(rhs.0))
463  }
464}
465
466impl Sub<u8> for BuildingLevel {
467  type Output = Self;
468
469  fn sub(self, rhs: u8) -> Self {
470    Self(self.0.saturating_sub(rhs))
471  }
472}
473
474impl Sub<i8> for BuildingLevel {
475  type Output = Self;
476
477  fn sub(self, rhs: i8) -> Self {
478    Self(self.0.saturating_sub_signed(rhs))
479  }
480}
481
482impl Sub<BuildingLevelDiff> for BuildingLevel {
483  type Output = Self;
484
485  fn sub(self, rhs: BuildingLevelDiff) -> Self {
486    self - rhs.0
487  }
488}
489
490impl SubAssign for BuildingLevel {
491  fn sub_assign(&mut self, rhs: Self) {
492    *self = *self - rhs;
493  }
494}
495
496impl SubAssign<u8> for BuildingLevel {
497  fn sub_assign(&mut self, rhs: u8) {
498    *self = *self - rhs;
499  }
500}
501
502impl SubAssign<i8> for BuildingLevel {
503  fn sub_assign(&mut self, rhs: i8) {
504    *self = *self - rhs;
505  }
506}
507
508impl SubAssign<BuildingLevelDiff> for BuildingLevel {
509  fn sub_assign(&mut self, rhs: BuildingLevelDiff) {
510    *self = *self - rhs;
511  }
512}
513
514impl Neg for BuildingLevel {
515  type Output = BuildingLevelDiff;
516
517  fn neg(self) -> BuildingLevelDiff {
518    BuildingLevelDiff::new(i8::from(self).neg())
519  }
520}
521
522#[derive(
523  Clone,
524  Copy,
525  Debug,
526  Default,
527  Deref,
528  derive_more::Display,
529  Into,
530  PartialEq,
531  Eq,
532  PartialOrd,
533  Ord,
534  Hash,
535  Deserialize,
536  Serialize,
537)]
538pub struct BuildingLevelDiff(i8);
539
540impl BuildingLevelDiff {
541  pub const ZERO: BuildingLevelDiff = BuildingLevelDiff(0);
542
543  #[inline]
544  pub const fn new(level_diff: i8) -> Self {
545    Self(level_diff)
546  }
547}
548
549impl From<f64> for BuildingLevelDiff {
550  fn from(mut value: f64) -> Self {
551    value = value.round();
552    debug_assert!(value.is_finite());
553    debug_assert!(value >= f64::from(i8::MIN));
554    debug_assert!(value <= f64::from(i8::MAX));
555    Self::new(value as i8)
556  }
557}
558
559impl PartialEq<i8> for BuildingLevelDiff {
560  fn eq(&self, other: &i8) -> bool {
561    self.0.eq(other)
562  }
563}
564
565impl PartialOrd<i8> for BuildingLevelDiff {
566  fn partial_cmp(&self, other: &i8) -> Option<cmp::Ordering> {
567    self.0.partial_cmp(other)
568  }
569}
570
571/// Shorthand for [`BuildingLevel::new`].
572#[macro_export]
573macro_rules! lv {
574  ($level:expr) => {
575    const { $crate::infrastructure::building::BuildingLevel::new($level) }
576  };
577}
578
579/// Creates a building with a random level.
580#[macro_export]
581macro_rules! with_random_level {
582  ($building:ident) => {{ $crate::infrastructure::prelude::$building::with_random_level() }};
583  ($building:ident, $max:expr) => {{
584    $crate::infrastructure::prelude::$building::with_random_level_in()
585      .max($crate::lv!($max))
586      .call()
587  }};
588  ($building:ident, $min:expr, $max:expr) => {{
589    $crate::infrastructure::prelude::$building::with_random_level_in()
590      .min($crate::lv!($min))
591      .max($crate::lv!($max))
592      .call()
593  }};
594}