Skip to main content

nil_core/resources/
cost.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4use super::maintenance::MaintenanceRatio;
5use derive_more::{Deref, Into};
6use serde::{Deserialize, Serialize};
7use std::ops::Mul;
8
9/// Base cost of an entity, such as buildings or units.
10#[derive(Clone, Copy, Debug, Deref, Into, Deserialize, Serialize, nil_num::F64Ops)]
11#[into(u32, f64)]
12pub struct Cost(u32);
13
14impl Cost {
15  #[inline]
16  pub const fn new(value: u32) -> Self {
17    Self(value)
18  }
19}
20
21impl From<f64> for Cost {
22  fn from(value: f64) -> Self {
23    debug_assert!(value.is_finite());
24    Self::new(value as u32)
25  }
26}
27
28impl Mul<ResourceRatio> for Cost {
29  type Output = f64;
30
31  fn mul(self, rhs: ResourceRatio) -> Self::Output {
32    self * rhs.0
33  }
34}
35
36impl Mul<MaintenanceRatio> for Cost {
37  type Output = f64;
38
39  fn mul(self, rhs: MaintenanceRatio) -> Self::Output {
40    self * f64::from(rhs)
41  }
42}
43
44/// Proportion between the total cost and a given resource.
45#[derive(Clone, Copy, Debug, Deref, Into, Deserialize, Serialize, nil_num::F64Ops)]
46pub struct ResourceRatio(f64);
47
48impl ResourceRatio {
49  #[inline]
50  pub const fn new(value: f64) -> Self {
51    debug_assert!(value.is_finite());
52    Self(value.clamp(0.0, 1.0))
53  }
54
55  #[inline]
56  pub const fn as_f64(self) -> f64 {
57    self.0
58  }
59}
60
61/// Checks, at compile time, if the sum of the resource ratios equals 1.
62#[doc(hidden)]
63#[macro_export]
64macro_rules! check_total_resource_ratio {
65  ($first:expr, $($other:expr),+ $(,)?) => {
66    const _: () = {
67      let mut first = $first.as_f64();
68      $(first += $other.as_f64();)+
69      assert!((first - 1.0).abs() < 0.001);
70    };
71  };
72}