Skip to main content

nil_core/world/
savedata.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4use crate::error::{Error, Result};
5use crate::event::Emitter;
6use crate::player::PlayerStatus;
7use crate::savedata::Savedata;
8use crate::world::World;
9
10impl World {
11  pub(super) fn consume_pending_save(&mut self) -> Result<()> {
12    if let Some(handle) = self.save_handle.take() {
13      handle.save(self.to_bytes()?);
14    }
15
16    Ok(())
17  }
18
19  pub fn to_bytes(&self) -> Result<Vec<u8>> {
20    let mut buffer = Vec::new();
21    let mut data = Savedata::from(self);
22
23    for player in data.player_manager.players_mut() {
24      *player.status_mut() = PlayerStatus::Inactive;
25    }
26
27    data.write(&mut buffer)?;
28
29    Ok(buffer)
30  }
31}
32
33impl From<&World> for Savedata {
34  fn from(world: &World) -> Self {
35    Self {
36      round: world.round.to_idle(),
37      continent: world.continent.clone(),
38      player_manager: world.player_manager.clone(),
39      bot_manager: world.bot_manager.clone(),
40      precursor_manager: world.precursor_manager.clone(),
41      military: world.military.clone(),
42      ranking: world.ranking.clone(),
43      report: world.report.clone(),
44      config: world.config.clone(),
45      stats: world.stats.clone(),
46      chat: world.chat.clone(),
47    }
48  }
49}
50
51impl From<Savedata> for World {
52  fn from(savedata: Savedata) -> Self {
53    Self {
54      round: savedata.round,
55      continent: savedata.continent,
56      player_manager: savedata.player_manager,
57      bot_manager: savedata.bot_manager,
58      precursor_manager: savedata.precursor_manager,
59      military: savedata.military,
60      ranking: savedata.ranking,
61      report: savedata.report,
62      config: savedata.config,
63      stats: savedata.stats,
64      chat: savedata.chat,
65
66      emitter: Emitter::default(),
67      save_handle: None,
68      on_next_round: None,
69    }
70  }
71}
72
73impl TryFrom<&World> for Vec<u8> {
74  type Error = Error;
75
76  fn try_from(world: &World) -> Result<Self> {
77    world.to_bytes()
78  }
79}