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::Into;
6use nil_util::{ConstDeref, F64Math};
7use serde::{Deserialize, Serialize};
8use std::ops::Mul;
9
10/// Base cost of an entity, such as buildings or units.
11#[derive(Copy, Debug, Into, Deserialize, Serialize, ConstDeref, F64Math)]
12#[derive_const(Clone, PartialEq, Eq, PartialOrd, Ord)]
13#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
14pub struct Cost(u32);
15
16impl Cost {
17  #[inline]
18  pub const fn new(value: u32) -> Self {
19    Self(value)
20  }
21}
22
23impl const From<f64> for Cost {
24  fn from(value: f64) -> Self {
25    debug_assert!(value.is_finite());
26    debug_assert!(value >= 0.0);
27    Self::new(value as u32)
28  }
29}
30
31impl const From<Cost> for f64 {
32  fn from(value: Cost) -> Self {
33    f64::from(value.0)
34  }
35}
36
37impl const Mul<ResourceRatio> for Cost {
38  type Output = f64;
39
40  fn mul(self, rhs: ResourceRatio) -> Self::Output {
41    self * rhs.0
42  }
43}
44
45impl const Mul<MaintenanceRatio> for Cost {
46  type Output = f64;
47
48  fn mul(self, rhs: MaintenanceRatio) -> Self::Output {
49    self * f64::from(rhs)
50  }
51}
52
53/// Proportion between the total cost and a given resource.
54#[derive(Copy, Debug, Deserialize, Serialize, ConstDeref, F64Math)]
55#[derive_const(Clone, PartialEq, PartialOrd)]
56#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
57pub struct ResourceRatio(f64);
58
59impl ResourceRatio {
60  #[inline]
61  pub const fn new(value: f64) -> Self {
62    debug_assert!(value.is_finite());
63    Self(value.clamp(0.0, 1.0))
64  }
65}
66
67impl const From<ResourceRatio> for f64 {
68  fn from(value: ResourceRatio) -> Self {
69    value.0
70  }
71}
72
73/// Checks, at compile time, if the sum of the resource ratios equals 1.
74#[doc(hidden)]
75#[macro_export]
76macro_rules! check_total_resource_ratio {
77  ($first:expr, $($other:expr),+ $(,)?) => {
78    const _: () = {
79      let mut first = f64::from($first);
80      $(first += f64::from($other);)+
81      assert!((first - 1.0).abs() < 0.001);
82    };
83  };
84}