nil-core 0.4.23

Multiplayer strategy game
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
// Copyright (C) Call of Nil contributors
// SPDX-License-Identifier: AGPL-3.0-only

pub mod academy;
pub mod farm;
pub mod iron_mine;
pub mod prefecture;
pub mod quarry;
pub mod sawmill;
pub mod silo;
pub mod stable;
pub mod wall;
pub mod warehouse;
pub mod workshop;

use crate::error::{Error, Result};
use crate::infrastructure::requirements::InfrastructureRequirements;
use crate::ranking::score::Score;
use crate::resources::prelude::*;
use derive_more::{Deref, Into};
use nil_num::growth::growth;
use serde::{Deserialize, Serialize};
use std::cmp;
use std::collections::HashMap;
use std::ops::{Add, AddAssign, Neg, Sub, SubAssign};
use strum::{EnumIs, EnumIter};
use subenum::subenum;

pub trait Building: Send + Sync {
  fn id(&self) -> BuildingId;

  /// Checks whether the building is enabled.
  fn is_enabled(&self) -> bool;
  /// Enables or disables the building.
  fn toggle(&mut self, enabled: bool);

  /// Current building level.
  fn level(&self) -> BuildingLevel;
  /// Minimum building level.
  fn min_level(&self) -> BuildingLevel;
  /// Maximum building level.
  fn max_level(&self) -> BuildingLevel;
  /// Sets the building's level while ensuring it remains within the level limit.
  fn set_level(&mut self, level: BuildingLevel);

  /// Sets the building to its **minimum** level.
  fn set_min_level(&mut self) {
    self.set_level(self.min_level());
  }

  /// Sets the building to its **maximum** level.
  fn set_max_level(&mut self) {
    self.set_level(self.max_level());
  }

  /// Increases the building level by one, if possible.
  fn increase_level(&mut self) {
    self.increase_level_by(1);
  }

  /// Increases the level of the building by a certain amount, if possible.
  fn increase_level_by(&mut self, amount: u8);

  /// Decreases the building level by one, if possible.
  fn decrease_level(&mut self) {
    self.decrease_level_by(1);
  }

  /// Decreases the level of the building by a certain amount, if possible.
  fn decrease_level_by(&mut self, amount: u8);

  /// Checks whether the building is at its minimum level.
  fn is_min_level(&self) -> bool {
    self.level() == self.min_level()
  }

  /// Checks whether the building is at its maximum level.
  fn is_max_level(&self) -> bool {
    self.level() >= self.max_level()
  }

  /// Total cost for the **minimum** level of the building.
  fn min_cost(&self) -> Cost;
  /// Total cost for the **maximum** level of the building.
  fn max_cost(&self) -> Cost;
  /// Percentage of the total cost related to wood.
  fn wood_ratio(&self) -> ResourceRatio;
  /// Percentage of the total cost related to stone.
  fn stone_ratio(&self) -> ResourceRatio;
  /// Percentage of the total cost related to iron.
  fn iron_ratio(&self) -> ResourceRatio;

  /// Building maintenance tax at its current level.
  fn maintenance(&self, stats: &BuildingStatsTable) -> Result<Maintenance>;
  /// Proportion of the base cost used as a maintenance tax.
  fn maintenance_ratio(&self) -> MaintenanceRatio;

  /// Workforce required for the **minimum** level of the building.
  fn min_workforce(&self) -> Workforce;
  /// Workforce required for the **maximum** level of the building.
  fn max_workforce(&self) -> Workforce;

  // Current score.
  fn score(&self, stats: &BuildingStatsTable) -> Result<Score>;
  // Building score at its **minimum** level.
  fn min_score(&self) -> Score;
  // Building score at its **maximum** level.
  fn max_score(&self) -> Score;

  /// Levels required to construct the building.
  fn infrastructure_requirements(&self) -> &InfrastructureRequirements;

  fn is_civil(&self) -> bool {
    self.id().is_civil()
  }

  fn is_military(&self) -> bool {
    self.id().is_military()
  }

  fn is_mine(&self) -> bool {
    self.id().is_mine()
  }

  fn is_storage(&self) -> bool {
    self.id().is_storage()
  }
}

#[subenum(CivilBuildingId, MilitaryBuildingId, MineId, StorageId)]
#[derive(
  Clone, Copy, Debug, strum::Display, EnumIs, EnumIter, PartialEq, Eq, Hash, Deserialize, Serialize,
)]
#[serde(rename_all = "kebab-case")]
#[strum(serialize_all = "kebab-case")]
pub enum BuildingId {
  #[subenum(MilitaryBuildingId)]
  Academy,

  #[subenum(CivilBuildingId, MineId)]
  Farm,

  #[subenum(CivilBuildingId, MineId)]
  IronMine,

  #[subenum(CivilBuildingId)]
  Prefecture,

  #[subenum(CivilBuildingId, MineId)]
  Quarry,

  #[subenum(CivilBuildingId, MineId)]
  Sawmill,

  #[subenum(CivilBuildingId, StorageId)]
  Silo,

  #[subenum(MilitaryBuildingId)]
  Stable,

  Wall,

  #[subenum(CivilBuildingId, StorageId)]
  Warehouse,

  #[subenum(MilitaryBuildingId)]
  Workshop,
}

impl BuildingId {
  #[inline]
  pub fn is_civil(self) -> bool {
    CivilBuildingId::try_from(self).is_ok()
  }

  #[inline]
  pub fn is_military(self) -> bool {
    MilitaryBuildingId::try_from(self).is_ok()
  }

  #[inline]
  pub fn is_mine(self) -> bool {
    MineId::try_from(self).is_ok()
  }

  #[inline]
  pub fn is_storage(self) -> bool {
    StorageId::try_from(self).is_ok()
  }
}

/// Information about a building at a given level.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BuildingStats {
  pub level: BuildingLevel,
  pub cost: Cost,
  pub resources: Resources,
  pub maintenance: Maintenance,
  pub workforce: Workforce,
  pub score: Score,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BuildingStatsTable {
  id: BuildingId,
  min_level: BuildingLevel,
  max_level: BuildingLevel,
  table: HashMap<BuildingLevel, BuildingStats>,
}

impl BuildingStatsTable {
  pub(crate) fn new(building: &dyn Building) -> Self {
    let min_level = building.min_level();
    let max_level = building.max_level();
    let mut table = HashMap::with_capacity((max_level.0).into());

    let mut cost = f64::from(building.min_cost());
    let cost_growth = growth()
      .floor(cost)
      .ceil(building.max_cost())
      .max_level(max_level)
      .call();

    let mut workforce = f64::from(building.min_workforce());
    let workforce_growth = growth()
      .floor(workforce)
      .ceil(building.max_workforce())
      .max_level(max_level)
      .call();

    let mut score = f64::from(building.min_score());
    let score_growth = growth()
      .floor(score)
      .ceil(building.max_score())
      .max_level(max_level)
      .call();

    let wood_ratio = *building.wood_ratio();
    let stone_ratio = *building.stone_ratio();
    let iron_ratio = *building.iron_ratio();

    let maintenance_ratio = *building.maintenance_ratio();
    let mut maintenance = cost * maintenance_ratio;

    for level in 1..=max_level.0 {
      let level = BuildingLevel::new(level);
      let resources = Resources {
        food: Food::MIN,
        iron: Iron::from((cost * iron_ratio).round()),
        stone: Stone::from((cost * stone_ratio).round()),
        wood: Wood::from((cost * wood_ratio).round()),
      };

      table.insert(
        level,
        BuildingStats {
          level,
          cost: Cost::from(cost.round()),
          resources,
          maintenance: Maintenance::from(maintenance.round()),
          workforce: Workforce::from(workforce.round()),
          score: Score::from(score.round()),
        },
      );

      debug_assert!(cost.is_normal());
      debug_assert!(workforce.is_normal());

      debug_assert!(maintenance.is_finite());
      debug_assert!(maintenance >= 0.0);

      debug_assert!(score.is_finite());
      debug_assert!(score >= 0.0);

      cost += cost * cost_growth;
      workforce += workforce * workforce_growth;
      score += score * score_growth;

      maintenance = cost * maintenance_ratio;
    }

    table.shrink_to_fit();

    Self {
      id: building.id(),
      min_level,
      max_level,
      table,
    }
  }

  #[inline]
  pub fn id(&self) -> BuildingId {
    self.id
  }

  #[inline]
  pub fn min_level(&self) -> BuildingLevel {
    self.min_level
  }

  #[inline]
  pub fn max_level(&self) -> BuildingLevel {
    self.max_level
  }

  #[inline]
  pub fn get(&self, level: BuildingLevel) -> Result<&BuildingStats> {
    self
      .table
      .get(&level)
      .ok_or(Error::BuildingStatsNotFoundForLevel(self.id, level))
  }
}

#[derive(
  Clone,
  Copy,
  Debug,
  Default,
  Deref,
  derive_more::Display,
  Into,
  PartialEq,
  Eq,
  PartialOrd,
  Ord,
  Hash,
  Deserialize,
  Serialize,
  nil_num::F64Ops,
)]
#[into(i16, i32, u8, u16, u32, u64, usize, f64)]
pub struct BuildingLevel(u8);

impl BuildingLevel {
  pub const ZERO: BuildingLevel = BuildingLevel(0);

  #[inline]
  pub const fn new(level: u8) -> Self {
    Self(level)
  }
}

impl From<BuildingLevel> for i8 {
  fn from(level: BuildingLevel) -> Self {
    debug_assert!(i8::try_from(level.0).is_ok());
    i8::try_from(level.0).unwrap_or(i8::MAX)
  }
}

impl PartialEq<u8> for BuildingLevel {
  fn eq(&self, other: &u8) -> bool {
    self.0.eq(other)
  }
}

impl PartialEq<BuildingLevel> for u8 {
  fn eq(&self, other: &BuildingLevel) -> bool {
    self.eq(&other.0)
  }
}

impl PartialEq<f64> for BuildingLevel {
  fn eq(&self, other: &f64) -> bool {
    f64::from(self.0).eq(other)
  }
}

impl PartialEq<BuildingLevel> for f64 {
  fn eq(&self, other: &BuildingLevel) -> bool {
    self.eq(&f64::from(other.0))
  }
}

impl PartialOrd<u8> for BuildingLevel {
  fn partial_cmp(&self, other: &u8) -> Option<cmp::Ordering> {
    self.0.partial_cmp(other)
  }
}

impl PartialOrd<BuildingLevel> for u8 {
  fn partial_cmp(&self, other: &BuildingLevel) -> Option<cmp::Ordering> {
    self.partial_cmp(&other.0)
  }
}

impl PartialOrd<f64> for BuildingLevel {
  fn partial_cmp(&self, other: &f64) -> Option<cmp::Ordering> {
    f64::from(self.0).partial_cmp(other)
  }
}

impl PartialOrd<BuildingLevel> for f64 {
  fn partial_cmp(&self, other: &BuildingLevel) -> Option<cmp::Ordering> {
    self.partial_cmp(&f64::from(other.0))
  }
}

impl Add for BuildingLevel {
  type Output = Self;

  fn add(self, rhs: Self) -> Self {
    Self(self.0.saturating_add(rhs.0))
  }
}

impl Add<u8> for BuildingLevel {
  type Output = Self;

  fn add(self, rhs: u8) -> Self {
    Self(self.0.saturating_add(rhs))
  }
}

impl Add<i8> for BuildingLevel {
  type Output = Self;

  fn add(self, rhs: i8) -> Self {
    Self(self.0.saturating_add_signed(rhs))
  }
}

impl Add<BuildingLevelDiff> for BuildingLevel {
  type Output = Self;

  fn add(self, rhs: BuildingLevelDiff) -> Self {
    self + rhs.0
  }
}

impl AddAssign for BuildingLevel {
  fn add_assign(&mut self, rhs: Self) {
    *self = *self + rhs;
  }
}

impl AddAssign<u8> for BuildingLevel {
  fn add_assign(&mut self, rhs: u8) {
    *self = *self + rhs;
  }
}

impl AddAssign<i8> for BuildingLevel {
  fn add_assign(&mut self, rhs: i8) {
    *self = *self + rhs;
  }
}

impl AddAssign<BuildingLevelDiff> for BuildingLevel {
  fn add_assign(&mut self, rhs: BuildingLevelDiff) {
    *self = *self + rhs;
  }
}

impl Sub for BuildingLevel {
  type Output = Self;

  fn sub(self, rhs: Self) -> Self {
    Self(self.0.saturating_sub(rhs.0))
  }
}

impl Sub<u8> for BuildingLevel {
  type Output = Self;

  fn sub(self, rhs: u8) -> Self {
    Self(self.0.saturating_sub(rhs))
  }
}

impl Sub<i8> for BuildingLevel {
  type Output = Self;

  fn sub(self, rhs: i8) -> Self {
    Self(self.0.saturating_sub_signed(rhs))
  }
}

impl Sub<BuildingLevelDiff> for BuildingLevel {
  type Output = Self;

  fn sub(self, rhs: BuildingLevelDiff) -> Self {
    self - rhs.0
  }
}

impl SubAssign for BuildingLevel {
  fn sub_assign(&mut self, rhs: Self) {
    *self = *self - rhs;
  }
}

impl SubAssign<u8> for BuildingLevel {
  fn sub_assign(&mut self, rhs: u8) {
    *self = *self - rhs;
  }
}

impl SubAssign<i8> for BuildingLevel {
  fn sub_assign(&mut self, rhs: i8) {
    *self = *self - rhs;
  }
}

impl SubAssign<BuildingLevelDiff> for BuildingLevel {
  fn sub_assign(&mut self, rhs: BuildingLevelDiff) {
    *self = *self - rhs;
  }
}

impl Neg for BuildingLevel {
  type Output = BuildingLevelDiff;

  fn neg(self) -> BuildingLevelDiff {
    BuildingLevelDiff::new(i8::from(self).neg())
  }
}

#[derive(
  Clone,
  Copy,
  Debug,
  Default,
  Deref,
  derive_more::Display,
  Into,
  PartialEq,
  Eq,
  PartialOrd,
  Ord,
  Hash,
  Deserialize,
  Serialize,
)]
pub struct BuildingLevelDiff(i8);

impl BuildingLevelDiff {
  pub const ZERO: BuildingLevelDiff = BuildingLevelDiff(0);

  #[inline]
  pub const fn new(level_diff: i8) -> Self {
    Self(level_diff)
  }
}

impl From<f64> for BuildingLevelDiff {
  fn from(mut value: f64) -> Self {
    value = value.round();
    debug_assert!(value.is_finite());
    debug_assert!(value >= f64::from(i8::MIN));
    debug_assert!(value <= f64::from(i8::MAX));
    Self::new(value as i8)
  }
}

impl PartialEq<i8> for BuildingLevelDiff {
  fn eq(&self, other: &i8) -> bool {
    self.0.eq(other)
  }
}

impl PartialOrd<i8> for BuildingLevelDiff {
  fn partial_cmp(&self, other: &i8) -> Option<cmp::Ordering> {
    self.0.partial_cmp(other)
  }
}

/// Shorthand for [`BuildingLevel::new`].
#[macro_export]
macro_rules! lv {
  ($level:expr) => {
    const { $crate::infrastructure::building::BuildingLevel::new($level) }
  };
}

/// Creates a building with a random level.
#[macro_export]
macro_rules! with_random_level {
  ($building:ident) => {{ $crate::infrastructure::prelude::$building::with_random_level() }};
  ($building:ident, $max:expr) => {{
    $crate::infrastructure::prelude::$building::with_random_level_in()
      .max($crate::lv!($max))
      .call()
  }};
  ($building:ident, $min:expr, $max:expr) => {{
    $crate::infrastructure::prelude::$building::with_random_level_in()
      .min($crate::lv!($min))
      .max($crate::lv!($max))
      .call()
  }};
}