1pub mod event;
2pub mod rule;
3pub mod tick;
4
5use atomicwrites::{AtomicFile, OverwriteBehavior};
6use common::{
7 grid::Grid,
8 mounting::VolumePos,
9 rtsim::{Actor, ChunkResource, NpcId, RtSimEntity, WorldSettings},
10 terrain::{CoordinateConversions, SpriteKind},
11};
12use common_ecs::{System, dispatch};
13use common_state::BlockDiff;
14use crossbeam_channel::{Receiver, Sender, unbounded};
15use enum_map::EnumMap;
16use rtsim::{
17 RtState,
18 data::{Data, ReadError, npc::SimulationMode},
19 event::{OnDeath, OnHealthChange, OnMountVolume, OnSetup, OnTheft},
20};
21use specs::DispatcherBuilder;
22use std::{
23 fs::{self, File},
24 io,
25 path::PathBuf,
26 thread::{self, JoinHandle},
27 time::Instant,
28};
29use tracing::{debug, error, info, trace, warn};
30use vek::*;
31use world::{IndexRef, World};
32
33pub struct RtSim {
34 file_path: PathBuf,
35 last_saved: Option<Instant>,
36 state: RtState,
37 save_thread: Option<(Sender<Data>, JoinHandle<()>)>,
38}
39
40impl RtSim {
41 pub fn new(
42 settings: &WorldSettings,
43 index: IndexRef,
44 world: &World,
45 data_dir: PathBuf,
46 ) -> Result<Self, ron::Error> {
47 let file_path = Self::get_file_path(data_dir);
48
49 info!("Looking for rtsim data at {}...", file_path.display());
50 let data = 'load: {
51 if std::env::var("RTSIM_NOLOAD").map_or(true, |v| v != "1") {
52 match File::open(&file_path) {
53 Ok(file) => {
54 info!("Rtsim data found. Attempting to load...");
55
56 let ignore_version = std::env::var("RTSIM_IGNORE_VERSION").is_ok();
57
58 match Data::from_reader(io::BufReader::new(file)) {
59 Err(ReadError::VersionMismatch(_)) if !ignore_version => {
60 warn!(
61 "Rtsim data version mismatch (implying a breaking change), \
62 rtsim data will be purged"
63 );
64 },
65 Ok(data) | Err(ReadError::VersionMismatch(data)) => {
66 info!("Rtsim data loaded.");
67 if data.should_purge {
68 warn!(
69 "The should_purge flag was set on the rtsim data, \
70 generating afresh"
71 );
72 } else {
73 break 'load *data;
74 }
75 },
76 Err(ReadError::Load(err)) => {
77 error!("Rtsim data failed to load: {}", err);
78 info!("Old rtsim data will now be moved to a backup file");
79 let mut i = 0;
80 loop {
81 let mut backup_path = file_path.clone();
82 backup_path.set_extension(if i == 0 {
83 "ron_backup".to_string()
84 } else {
85 format!("ron_backup_{}", i)
86 });
87 if !backup_path.exists() {
88 fs::rename(&file_path, &backup_path)?;
89 warn!(
90 "Failed rtsim data was moved to {}",
91 backup_path.display()
92 );
93 info!("A fresh rtsim data will now be generated.");
94 break;
95 } else {
96 info!(
97 "Backup file {} already exists, trying another name...",
98 backup_path.display()
99 );
100 }
101 i += 1;
102 }
103 },
104 }
105 },
106 Err(e) if e.kind() == io::ErrorKind::NotFound => {
107 info!("No rtsim data found. Generating from world...")
108 },
109 Err(e) => return Err(e.into()),
110 }
111 } else {
112 warn!(
113 "'RTSIM_NOLOAD' is set, skipping loading of rtsim state (old state will be \
114 overwritten)."
115 );
116 }
117
118 let data = Data::generate(settings, world, index);
119 info!("Rtsim data generated.");
120 data
121 };
122
123 let mut this = Self {
124 last_saved: None,
125 state: RtState::new(data).with_resource(ChunkStates(Grid::populate_from(
126 world.sim().get_size().as_(),
127 |_| None,
128 ))),
129 file_path,
130 save_thread: None,
131 };
132
133 rule::start_rules(&mut this.state);
134
135 this.state.emit(OnSetup, &mut (), world, index);
136
137 Ok(this)
138 }
139
140 fn get_file_path(mut data_dir: PathBuf) -> PathBuf {
141 let mut path = std::env::var("VELOREN_RTSIM")
142 .map(PathBuf::from)
143 .unwrap_or_else(|_| {
144 data_dir.push("rtsim");
145 data_dir
146 });
147 path.push("data.dat");
148 path
149 }
150
151 pub fn hook_character_mount_volume(
152 &mut self,
153 world: &World,
154 index: IndexRef,
155 pos: VolumePos<NpcId>,
156 actor: Actor,
157 ) {
158 self.state
159 .emit(OnMountVolume { actor, pos }, &mut (), world, index)
160 }
161
162 pub fn hook_pickup_owned_sprite(
163 &mut self,
164 world: &World,
165 index: IndexRef,
166 sprite: SpriteKind,
167 wpos: Vec3<i32>,
168 actor: Actor,
169 ) {
170 let site = world.sim().get(wpos.xy().wpos_to_cpos()).and_then(|chunk| {
171 chunk
172 .sites
173 .iter()
174 .find_map(|site| self.state.data().sites.world_site_map.get(site).copied())
175 });
176
177 self.state.emit(
178 OnTheft {
179 actor,
180 wpos,
181 sprite,
182 site,
183 },
184 &mut (),
185 world,
186 index,
187 )
188 }
189
190 pub fn hook_load_chunk(&mut self, key: Vec2<i32>, max_res: EnumMap<ChunkResource, usize>) {
191 if let Some(chunk_state) = self.state.get_resource_mut::<ChunkStates>().0.get_mut(key) {
192 *chunk_state = Some(LoadedChunkState { max_res });
193 }
194 }
195
196 pub fn hook_unload_chunk(&mut self, key: Vec2<i32>) {
197 if let Some(chunk_state) = self.state.get_resource_mut::<ChunkStates>().0.get_mut(key) {
198 *chunk_state = None;
199 }
200 }
201
202 pub fn hook_block_update(&mut self, world: &World, index: IndexRef, changes: Vec<BlockDiff>) {
205 self.state
206 .emit(event::OnBlockChange { changes }, &mut (), world, index);
207 }
208
209 pub fn hook_rtsim_entity_unload(&mut self, entity: RtSimEntity) {
210 let data = self.state.get_data_mut();
211
212 if let Some(npc) = data.npcs.get_mut(entity.0) {
213 if matches!(npc.mode, SimulationMode::Simulated) {
214 error!("Unloaded already unloaded entity");
215 }
216 npc.mode = SimulationMode::Simulated;
217 }
218 }
219
220 pub fn hook_rtsim_actor_hp_change(
221 &mut self,
222 world: &World,
223 index: IndexRef,
224 actor: Actor,
225 cause: Option<Actor>,
226 new_hp_fraction: f32,
227 ) {
228 self.state.emit(
229 OnHealthChange {
230 actor,
231 cause,
232 new_health_fraction: new_hp_fraction,
233 },
234 &mut (),
235 world,
236 index,
237 )
238 }
239
240 pub fn hook_rtsim_actor_death(
241 &mut self,
242 world: &World,
243 index: IndexRef,
244 actor: Actor,
245 wpos: Option<Vec3<f32>>,
246 killer: Option<Actor>,
247 ) {
248 self.state.emit(
249 OnDeath {
250 wpos,
251 actor,
252 killer,
253 },
254 &mut (),
255 world,
256 index,
257 );
258 }
259
260 pub fn save(&mut self, wait_until_finished: bool) {
261 debug!("Saving rtsim data...");
262
263 let (tx, _) = self.save_thread.get_or_insert_with(|| {
269 trace!("Starting rtsim data save thread...");
270 let (tx, rx) = unbounded();
271 let file_path = self.file_path.clone();
272 (tx, thread::spawn(move || save_thread(file_path, rx)))
273 });
274
275 if let Err(err) = tx.send(self.state.data().clone()) {
277 error!("Failed to perform rtsim save: {}", err);
278 }
279
280 if wait_until_finished {
283 if let Some((tx, handle)) = self.save_thread.take() {
284 drop(tx);
285 info!("Waiting for rtsim save thread to finish...");
286 handle.join().expect("Save thread failed to join");
287 info!("Rtsim save thread finished.");
288 }
289 }
290
291 self.last_saved = Some(Instant::now());
292 }
293
294 pub fn get_chunk_resources(&self, key: Vec2<i32>) -> EnumMap<ChunkResource, f32> {
296 self.state.data().nature.get_chunk_resources(key)
297 }
298
299 pub fn state(&self) -> &RtState { &self.state }
300
301 pub fn set_should_purge(&mut self, should_purge: bool) {
302 self.state.data_mut().should_purge = should_purge;
303 }
304}
305
306fn save_thread(file_path: PathBuf, rx: Receiver<Data>) {
307 if let Some(dir) = file_path.parent() {
308 let _ = fs::create_dir_all(dir);
309 }
310
311 let atomic_file = AtomicFile::new(file_path, OverwriteBehavior::AllowOverwrite);
312 while let Ok(data) = rx.recv() {
313 debug!("Writing rtsim data to file...");
314 match atomic_file.write(move |file| data.write_to(io::BufWriter::new(file))) {
315 Ok(_) => debug!("Rtsim data saved."),
316 Err(e) => error!("Saving rtsim data failed: {}", e),
317 }
318 }
319}
320
321pub struct ChunkStates(pub Grid<Option<LoadedChunkState>>);
322
323pub struct LoadedChunkState {
324 pub max_res: EnumMap<ChunkResource, usize>,
326}
327
328pub fn add_server_systems(dispatch_builder: &mut DispatcherBuilder) {
329 dispatch::<tick::Sys>(dispatch_builder, &[&common_systems::phys::Sys::sys_name()]);
330}