veloren_common_state/
state.rs

1#[cfg(feature = "plugins")]
2use crate::plugin::PluginMgr;
3#[cfg(feature = "plugins")]
4use crate::plugin::memory_manager::EcsWorld;
5use crate::{BuildArea, NoDurabilityArea};
6#[cfg(feature = "plugins")]
7use common::uid::IdMaps;
8use common::{
9    calendar::Calendar,
10    comp,
11    event::{EventBus, LocalEvent},
12    interaction,
13    link::Is,
14    mounting::{Mount, Rider, VolumeRider, VolumeRiders},
15    outcome::Outcome,
16    resources::{
17        DeltaTime, EntitiesDiedLastTick, GameMode, PlayerEntity, PlayerPhysicsSettings,
18        ProgramTime, Time, TimeOfDay, TimeScale,
19    },
20    shared_server_config::ServerConstants,
21    slowjob::SlowJobPool,
22    terrain::{Block, MapSizeLg, TerrainChunk, TerrainGrid},
23    tether,
24    time::DayPeriod,
25    trade::Trades,
26    vol::{ReadVol, WriteVol},
27    weather::{Weather, WeatherGrid},
28};
29use common_base::{prof_span, span};
30use common_ecs::{PhysicsMetrics, SysMetrics};
31use common_net::sync::{WorldSyncExt, interpolation as sync_interp};
32use core::{convert::identity, time::Duration};
33use hashbrown::{HashMap, HashSet};
34use rayon::{ThreadPool, ThreadPoolBuilder};
35use specs::{
36    Component, DispatcherBuilder, Entity as EcsEntity, WorldExt,
37    prelude::Resource,
38    shred::{Fetch, FetchMut, SendDispatcher},
39    storage::{MaskedStorage as EcsMaskedStorage, Storage as EcsStorage},
40};
41use std::{sync::Arc, time::Instant};
42use timer_queue::TimerQueue;
43use vek::*;
44
45/// At what point should we stop speeding up physics to compensate for lag? If
46/// we speed physics up too fast, we'd skip important physics events like
47/// collisions. This constant determines the upper limit. If delta time exceeds
48/// this value, the game's physics will begin to produce time lag. Ideally, we'd
49/// avoid such a situation.
50const MAX_DELTA_TIME: f32 = 1.0;
51/// convert seconds to milliseconds to use in TimerQueue
52const SECONDS_TO_MILLISECONDS: f64 = 1000.0;
53
54#[derive(Default)]
55pub struct BlockChange {
56    blocks: HashMap<Vec3<i32>, Block>,
57}
58
59impl BlockChange {
60    pub fn set(&mut self, pos: Vec3<i32>, block: Block) { self.blocks.insert(pos, block); }
61
62    pub fn try_set(&mut self, pos: Vec3<i32>, block: Block) -> Option<()> {
63        if !self.blocks.contains_key(&pos) {
64            self.blocks.insert(pos, block);
65            Some(())
66        } else {
67            None
68        }
69    }
70
71    /// Check if the block at given position `pos` has already been modified
72    /// this tick.
73    pub fn can_set_block(&self, pos: Vec3<i32>) -> bool { !self.blocks.contains_key(&pos) }
74
75    pub fn clear(&mut self) { self.blocks.clear(); }
76}
77
78#[derive(Default)]
79pub struct ScheduledBlockChange {
80    changes: TimerQueue<HashMap<Vec3<i32>, Block>>,
81    outcomes: TimerQueue<HashMap<Vec3<i32>, Block>>,
82    last_poll_time: u64,
83}
84impl ScheduledBlockChange {
85    pub fn set(&mut self, pos: Vec3<i32>, block: Block, replace_time: f64) {
86        let timer = self.changes.insert(
87            (replace_time * SECONDS_TO_MILLISECONDS) as u64,
88            HashMap::new(),
89        );
90        self.changes.get_mut(timer).insert(pos, block);
91    }
92
93    pub fn outcome_set(&mut self, pos: Vec3<i32>, block: Block, replace_time: f64) {
94        let outcome_timer = self.outcomes.insert(
95            (replace_time * SECONDS_TO_MILLISECONDS) as u64,
96            HashMap::new(),
97        );
98        self.outcomes.get_mut(outcome_timer).insert(pos, block);
99    }
100}
101
102#[derive(Default)]
103pub struct TerrainChanges {
104    pub new_chunks: HashSet<Vec2<i32>>,
105    pub modified_chunks: HashSet<Vec2<i32>>,
106    pub removed_chunks: HashSet<Vec2<i32>>,
107    pub modified_blocks: HashMap<Vec3<i32>, Block>,
108}
109
110impl TerrainChanges {
111    pub fn clear(&mut self) {
112        self.new_chunks.clear();
113        self.modified_chunks.clear();
114        self.removed_chunks.clear();
115    }
116}
117
118#[derive(Clone)]
119pub struct BlockDiff {
120    pub wpos: Vec3<i32>,
121    pub old: Block,
122    pub new: Block,
123}
124
125/// A type used to represent game state stored on both the client and the
126/// server. This includes things like entity components, terrain data, and
127/// global states like weather, time of day, etc.
128pub struct State {
129    ecs: specs::World,
130    // Avoid lifetime annotation by storing a thread pool instead of the whole dispatcher
131    thread_pool: Arc<ThreadPool>,
132    dispatcher: SendDispatcher<'static>,
133}
134
135pub type Pools = Arc<ThreadPool>;
136
137impl State {
138    pub fn pools(game_mode: GameMode) -> Pools {
139        let thread_name_infix = match game_mode {
140            GameMode::Server => "s",
141            GameMode::Client => "c",
142            GameMode::Singleplayer => "sp",
143        };
144
145        Arc::new(
146            ThreadPoolBuilder::new()
147                .num_threads(num_cpus::get().max(common::consts::MIN_RECOMMENDED_RAYON_THREADS))
148                .thread_name(move |i| format!("rayon-{}-{}", thread_name_infix, i))
149                .build()
150                .unwrap(),
151        )
152    }
153
154    /// Create a new `State` in client mode.
155    pub fn client(
156        pools: Pools,
157        map_size_lg: MapSizeLg,
158        default_chunk: Arc<TerrainChunk>,
159        add_systems: impl Fn(&mut DispatcherBuilder),
160        #[cfg(feature = "plugins")] plugin_mgr: PluginMgr,
161    ) -> Self {
162        Self::new(
163            GameMode::Client,
164            pools,
165            map_size_lg,
166            default_chunk,
167            add_systems,
168            #[cfg(feature = "plugins")]
169            plugin_mgr,
170        )
171    }
172
173    /// Create a new `State` in server mode.
174    pub fn server(
175        pools: Pools,
176        map_size_lg: MapSizeLg,
177        default_chunk: Arc<TerrainChunk>,
178        add_systems: impl Fn(&mut DispatcherBuilder),
179        #[cfg(feature = "plugins")] plugin_mgr: PluginMgr,
180    ) -> Self {
181        Self::new(
182            GameMode::Server,
183            pools,
184            map_size_lg,
185            default_chunk,
186            add_systems,
187            #[cfg(feature = "plugins")]
188            plugin_mgr,
189        )
190    }
191
192    pub fn new(
193        game_mode: GameMode,
194        pools: Pools,
195        map_size_lg: MapSizeLg,
196        default_chunk: Arc<TerrainChunk>,
197        add_systems: impl Fn(&mut DispatcherBuilder),
198        #[cfg(feature = "plugins")] plugin_mgr: PluginMgr,
199    ) -> Self {
200        prof_span!(guard, "create dispatcher");
201        let mut dispatch_builder =
202            DispatcherBuilder::<'static, 'static>::new().with_pool(Arc::clone(&pools));
203        // TODO: Consider alternative ways to do this
204        add_systems(&mut dispatch_builder);
205        let dispatcher = dispatch_builder
206            .build()
207            .try_into_sendable()
208            .unwrap_or_else(|_| panic!("Thread local systems not allowed"));
209        drop(guard);
210
211        Self {
212            ecs: Self::setup_ecs_world(
213                game_mode,
214                Arc::clone(&pools),
215                map_size_lg,
216                default_chunk,
217                #[cfg(feature = "plugins")]
218                plugin_mgr,
219            ),
220            thread_pool: pools,
221            dispatcher,
222        }
223    }
224
225    /// Creates ecs world and registers all the common components and resources
226    // TODO: Split up registering into server and client (e.g. move
227    // EventBus<ServerEvent> to the server)
228    fn setup_ecs_world(
229        game_mode: GameMode,
230        thread_pool: Arc<ThreadPool>,
231        map_size_lg: MapSizeLg,
232        default_chunk: Arc<TerrainChunk>,
233        #[cfg(feature = "plugins")] mut plugin_mgr: PluginMgr,
234    ) -> specs::World {
235        prof_span!("State::setup_ecs_world");
236        let mut ecs = specs::World::new();
237        // Uids for sync
238        ecs.register_sync_marker();
239        // Register server -> all clients synced components.
240        ecs.register::<comp::Body>();
241        ecs.register::<comp::Hardcore>();
242        ecs.register::<comp::body::parts::Heads>();
243        ecs.register::<comp::Player>();
244        ecs.register::<comp::Stats>();
245        ecs.register::<comp::SkillSet>();
246        ecs.register::<comp::ActiveAbilities>();
247        ecs.register::<comp::Buffs>();
248        ecs.register::<comp::Auras>();
249        ecs.register::<comp::EnteredAuras>();
250        ecs.register::<comp::Energy>();
251        ecs.register::<comp::Combo>();
252        ecs.register::<comp::Health>();
253        ecs.register::<comp::Poise>();
254        ecs.register::<comp::CanBuild>();
255        ecs.register::<comp::LightEmitter>();
256        ecs.register::<comp::PickupItem>();
257        ecs.register::<comp::ThrownItem>();
258        ecs.register::<comp::Scale>();
259        ecs.register::<Is<Mount>>();
260        ecs.register::<Is<Rider>>();
261        ecs.register::<Is<VolumeRider>>();
262        ecs.register::<Is<tether::Leader>>();
263        ecs.register::<Is<tether::Follower>>();
264        ecs.register::<Is<interaction::Interactor>>();
265        ecs.register::<interaction::Interactors>();
266        ecs.register::<comp::Mass>();
267        ecs.register::<comp::Density>();
268        ecs.register::<comp::Collider>();
269        ecs.register::<comp::Sticky>();
270        ecs.register::<comp::Immovable>();
271        ecs.register::<comp::CharacterState>();
272        ecs.register::<comp::CharacterActivity>();
273        ecs.register::<comp::Object>();
274        ecs.register::<comp::Group>();
275        ecs.register::<comp::Shockwave>();
276        ecs.register::<comp::ShockwaveHitEntities>();
277        ecs.register::<comp::Beam>();
278        ecs.register::<comp::Alignment>();
279        ecs.register::<comp::LootOwner>();
280        ecs.register::<comp::Admin>();
281        ecs.register::<comp::Stance>();
282        ecs.register::<comp::Teleporting>();
283        ecs.register::<comp::GizmoSubscriber>();
284
285        // Register components send from clients -> server
286        ecs.register::<comp::Controller>();
287
288        // Register components send directly from server -> all but one client
289        ecs.register::<comp::PhysicsState>();
290
291        // Register components synced from client -> server -> all other clients
292        ecs.register::<comp::Pos>();
293        ecs.register::<comp::Vel>();
294        ecs.register::<comp::Ori>();
295        ecs.register::<comp::Inventory>();
296
297        // Register common unsynced components
298        ecs.register::<comp::PreviousPhysCache>();
299        ecs.register::<comp::PosVelOriDefer>();
300
301        // Register client-local components
302        // TODO: only register on the client
303        ecs.register::<comp::LightAnimation>();
304        ecs.register::<sync_interp::InterpBuffer<comp::Pos>>();
305        ecs.register::<sync_interp::InterpBuffer<comp::Vel>>();
306        ecs.register::<sync_interp::InterpBuffer<comp::Ori>>();
307
308        // Register server-local components
309        // TODO: only register on the server
310        ecs.register::<comp::Last<comp::Pos>>();
311        ecs.register::<comp::Last<comp::Vel>>();
312        ecs.register::<comp::Last<comp::Ori>>();
313        ecs.register::<comp::Agent>();
314        ecs.register::<comp::WaypointArea>();
315        ecs.register::<comp::ForceUpdate>();
316        ecs.register::<comp::InventoryUpdate>();
317        ecs.register::<comp::Waypoint>();
318        ecs.register::<comp::MapMarker>();
319        ecs.register::<comp::Projectile>();
320        ecs.register::<comp::Melee>();
321        ecs.register::<comp::ItemDrops>();
322        ecs.register::<comp::ChatMode>();
323        ecs.register::<comp::Faction>();
324        ecs.register::<comp::invite::Invite>();
325        ecs.register::<comp::invite::PendingInvites>();
326        ecs.register::<VolumeRiders>();
327        ecs.register::<common::combat::DeathEffects>();
328        ecs.register::<common::combat::RiderEffects>();
329
330        // Register synced resources used by the ECS.
331        ecs.insert(TimeOfDay(0.0));
332        ecs.insert(Calendar::default());
333        ecs.insert(WeatherGrid::new(Vec2::zero()));
334        ecs.insert(Time(0.0));
335        ecs.insert(ProgramTime(0.0));
336        ecs.insert(TimeScale(1.0));
337
338        // Register unsynced resources used by the ECS.
339        ecs.insert(DeltaTime(0.0));
340        ecs.insert(PlayerEntity(None));
341        ecs.insert(TerrainGrid::new(map_size_lg, default_chunk).unwrap());
342        ecs.insert(BlockChange::default());
343        ecs.insert(ScheduledBlockChange::default());
344        ecs.insert(crate::special_areas::AreasContainer::<BuildArea>::default());
345        ecs.insert(crate::special_areas::AreasContainer::<NoDurabilityArea>::default());
346        ecs.insert(TerrainChanges::default());
347        ecs.insert(EventBus::<LocalEvent>::default());
348        ecs.insert(game_mode);
349        ecs.insert(EventBus::<Outcome>::default());
350        ecs.insert(common::CachedSpatialGrid::default());
351        ecs.insert(EntitiesDiedLastTick::default());
352
353        let num_cpu = num_cpus::get() as u64;
354        let slow_limit = (num_cpu / 2 + num_cpu / 4).max(1);
355        tracing::trace!(?slow_limit, "Slow Thread limit");
356        ecs.insert(SlowJobPool::new(slow_limit, 10_000, thread_pool));
357
358        // TODO: only register on the server
359        ecs.insert(comp::group::GroupManager::default());
360        ecs.insert(SysMetrics::default());
361        ecs.insert(PhysicsMetrics::default());
362        ecs.insert(Trades::default());
363        ecs.insert(PlayerPhysicsSettings::default());
364        ecs.insert(VolumeRiders::default());
365
366        // Load plugins from asset directory
367        #[cfg(feature = "plugins")]
368        ecs.insert({
369            let ecs_world = EcsWorld {
370                entities: &ecs.entities(),
371                health: ecs.read_component().into(),
372                uid: ecs.read_component().into(),
373                id_maps: &ecs.read_resource::<IdMaps>().into(),
374                player: ecs.read_component().into(),
375            };
376            if let Err(e) = plugin_mgr.load_event(&ecs_world, game_mode) {
377                tracing::debug!(?e, "Failed to run plugin init");
378                tracing::info!("Plugins disabled, enable debug logging for more information.");
379                PluginMgr::default()
380            } else {
381                plugin_mgr
382            }
383        });
384
385        ecs
386    }
387
388    /// Register a component with the state's ECS.
389    #[must_use]
390    pub fn with_component<T: Component>(mut self) -> Self
391    where
392        <T as Component>::Storage: Default,
393    {
394        self.ecs.register::<T>();
395        self
396    }
397
398    /// Write a component attributed to a particular entity, ignoring errors.
399    ///
400    /// This should be used *only* when we can guarantee that the rest of the
401    /// code does not rely on the insert having succeeded (meaning the
402    /// entity is no longer alive!).
403    ///
404    /// Returns None if the entity was dead or there was no previous entry for
405    /// this component; otherwise, returns Some(old_component).
406    pub fn write_component_ignore_entity_dead<C: Component>(
407        &mut self,
408        entity: EcsEntity,
409        comp: C,
410    ) -> Option<C> {
411        self.ecs
412            .write_storage()
413            .insert(entity, comp)
414            .ok()
415            .and_then(identity)
416    }
417
418    /// Delete a component attributed to a particular entity.
419    pub fn delete_component<C: Component>(&mut self, entity: EcsEntity) -> Option<C> {
420        self.ecs.write_storage().remove(entity)
421    }
422
423    /// Read a component attributed to a particular entity.
424    pub fn read_component_cloned<C: Component + Clone>(&self, entity: EcsEntity) -> Option<C> {
425        self.ecs.read_storage().get(entity).cloned()
426    }
427
428    /// Read a component attributed to a particular entity.
429    pub fn read_component_copied<C: Component + Copy>(&self, entity: EcsEntity) -> Option<C> {
430        self.ecs.read_storage().get(entity).copied()
431    }
432
433    /// # Panics
434    /// Panics if `EventBus<E>` is borrowed
435    pub fn emit_event_now<E>(&self, event: E)
436    where
437        EventBus<E>: Resource,
438    {
439        self.ecs.write_resource::<EventBus<E>>().emit_now(event)
440    }
441
442    /// Given mutable access to the resource R, assuming the resource
443    /// component exists (this is already the behavior of functions like `fetch`
444    /// and `write_component_ignore_entity_dead`).  Since all of our resources
445    /// are generated up front, any failure here is definitely a code bug.
446    pub fn mut_resource<R: Resource>(&mut self) -> &mut R {
447        self.ecs.get_mut::<R>().expect(
448            "Tried to fetch an invalid resource even though all our resources should be known at \
449             compile time.",
450        )
451    }
452
453    /// Get a read-only reference to the storage of a particular component type.
454    pub fn read_storage<C: Component>(&self) -> EcsStorage<C, Fetch<EcsMaskedStorage<C>>> {
455        self.ecs.read_storage::<C>()
456    }
457
458    /// Get a reference to the internal ECS world.
459    pub fn ecs(&self) -> &specs::World { &self.ecs }
460
461    /// Get a mutable reference to the internal ECS world.
462    pub fn ecs_mut(&mut self) -> &mut specs::World { &mut self.ecs }
463
464    pub fn thread_pool(&self) -> &Arc<ThreadPool> { &self.thread_pool }
465
466    /// Get a reference to the `TerrainChanges` structure of the state. This
467    /// contains information about terrain state that has changed since the
468    /// last game tick.
469    pub fn terrain_changes(&self) -> Fetch<TerrainChanges> { self.ecs.read_resource() }
470
471    /// Get a reference the current in-game weather grid.
472    pub fn weather_grid(&self) -> Fetch<WeatherGrid> { self.ecs.read_resource() }
473
474    /// Get a mutable reference the current in-game weather grid.
475    pub fn weather_grid_mut(&mut self) -> FetchMut<WeatherGrid> { self.ecs.write_resource() }
476
477    /// Get the current weather at a position in worldspace.
478    pub fn weather_at(&self, pos: Vec2<f32>) -> Weather {
479        self.weather_grid().get_interpolated(pos)
480    }
481
482    /// Get the max weather near a position in worldspace.
483    pub fn max_weather_near(&self, pos: Vec2<f32>) -> Weather {
484        self.weather_grid().get_max_near(pos)
485    }
486
487    /// Get the current in-game time of day.
488    ///
489    /// Note that this should not be used for physics, animations or other such
490    /// localised timings.
491    pub fn get_time_of_day(&self) -> f64 { self.ecs.read_resource::<TimeOfDay>().0 }
492
493    /// Get the current in-game day period (period of the day/night cycle)
494    pub fn get_day_period(&self) -> DayPeriod { self.get_time_of_day().into() }
495
496    /// Get the current in-game time.
497    ///
498    /// Note that this does not correspond to the time of day.
499    pub fn get_time(&self) -> f64 { self.ecs.read_resource::<Time>().0 }
500
501    /// Get the current true in-game time, unaffected by time_scale.
502    ///
503    /// Note that this does not correspond to the time of day.
504    pub fn get_program_time(&self) -> f64 { self.ecs.read_resource::<ProgramTime>().0 }
505
506    /// Get the current delta time.
507    pub fn get_delta_time(&self) -> f32 { self.ecs.read_resource::<DeltaTime>().0 }
508
509    /// Get a reference to this state's terrain.
510    pub fn terrain(&self) -> Fetch<TerrainGrid> { self.ecs.read_resource() }
511
512    /// Get a reference to this state's terrain.
513    pub fn slow_job_pool(&self) -> Fetch<SlowJobPool> { self.ecs.read_resource() }
514
515    /// Get a writable reference to this state's terrain.
516    pub fn terrain_mut(&self) -> FetchMut<TerrainGrid> { self.ecs.write_resource() }
517
518    /// Get a block in this state's terrain.
519    pub fn get_block(&self, pos: Vec3<i32>) -> Option<Block> {
520        self.terrain().get(pos).ok().copied()
521    }
522
523    /// Set a block in this state's terrain.
524    pub fn set_block(&self, pos: Vec3<i32>, block: Block) {
525        self.ecs.write_resource::<BlockChange>().set(pos, block);
526    }
527
528    /// Set a block in this state's terrain (used to delete temporary summoned
529    /// sprites after a timeout).
530    pub fn schedule_set_block(
531        &self,
532        pos: Vec3<i32>,
533        block: Block,
534        sprite_block: Block,
535        replace_time: f64,
536    ) {
537        self.ecs
538            .write_resource::<ScheduledBlockChange>()
539            .set(pos, block, replace_time);
540        self.ecs
541            .write_resource::<ScheduledBlockChange>()
542            .outcome_set(pos, sprite_block, replace_time);
543    }
544
545    /// Check if the block at given position `pos` has already been modified
546    /// this tick.
547    pub fn can_set_block(&self, pos: Vec3<i32>) -> bool {
548        self.ecs.read_resource::<BlockChange>().can_set_block(pos)
549    }
550
551    /// Removes every chunk of the terrain.
552    pub fn clear_terrain(&mut self) -> usize {
553        let removed_chunks = &mut self.ecs.write_resource::<TerrainChanges>().removed_chunks;
554
555        self.terrain_mut()
556            .drain()
557            .map(|(key, _)| {
558                removed_chunks.insert(key);
559            })
560            .count()
561    }
562
563    /// Insert the provided chunk into this state's terrain.
564    pub fn insert_chunk(&mut self, key: Vec2<i32>, chunk: Arc<TerrainChunk>) {
565        if self
566            .ecs
567            .write_resource::<TerrainGrid>()
568            .insert(key, chunk)
569            .is_some()
570        {
571            self.ecs
572                .write_resource::<TerrainChanges>()
573                .modified_chunks
574                .insert(key);
575        } else {
576            self.ecs
577                .write_resource::<TerrainChanges>()
578                .new_chunks
579                .insert(key);
580        }
581    }
582
583    /// Remove the chunk with the given key from this state's terrain, if it
584    /// exists.
585    pub fn remove_chunk(&mut self, key: Vec2<i32>) -> bool {
586        if self
587            .ecs
588            .write_resource::<TerrainGrid>()
589            .remove(key)
590            .is_some()
591        {
592            self.ecs
593                .write_resource::<TerrainChanges>()
594                .removed_chunks
595                .insert(key);
596
597            true
598        } else {
599            false
600        }
601    }
602
603    // Apply terrain changes
604    pub fn apply_terrain_changes(&self, block_update: impl FnMut(&specs::World, Vec<BlockDiff>)) {
605        self.apply_terrain_changes_internal(false, block_update);
606    }
607
608    /// `during_tick` is true if and only if this is called from within
609    /// [State::tick].
610    ///
611    /// This only happens if [State::tick] is asked to update terrain itself
612    /// (using `update_terrain: true`).  [State::tick] is called from within
613    /// both the client and the server ticks, right after handling terrain
614    /// messages; currently, client sets it to true and server to false.
615    fn apply_terrain_changes_internal(
616        &self,
617        during_tick: bool,
618        mut block_update: impl FnMut(&specs::World, Vec<BlockDiff>),
619    ) {
620        span!(
621            _guard,
622            "apply_terrain_changes",
623            "State::apply_terrain_changes"
624        );
625        let mut terrain = self.ecs.write_resource::<TerrainGrid>();
626        let mut modified_blocks =
627            std::mem::take(&mut self.ecs.write_resource::<BlockChange>().blocks);
628
629        let mut scheduled_changes = self.ecs.write_resource::<ScheduledBlockChange>();
630        let current_time: f64 = self.ecs.read_resource::<Time>().0 * SECONDS_TO_MILLISECONDS;
631        let current_time = current_time as u64;
632        // This is important as the poll function has a debug assert that the new poll
633        // is at a more recent time than the old poll. As Time is synced between server
634        // and client, there is a chance that client dt can get slightly ahead of a
635        // server update, so we do not want to panic in that scenario.
636        if scheduled_changes.last_poll_time < current_time {
637            scheduled_changes.last_poll_time = current_time;
638            while let Some(changes) = scheduled_changes.changes.poll(current_time) {
639                modified_blocks.extend(changes.iter());
640            }
641            let outcome = self.ecs.read_resource::<EventBus<Outcome>>();
642            while let Some(outcomes) = scheduled_changes.outcomes.poll(current_time) {
643                for (pos, block) in outcomes.into_iter() {
644                    if let Some(sprite) = block.get_sprite() {
645                        outcome.emit_now(Outcome::SpriteDelete { pos, sprite });
646                    }
647                }
648            }
649        }
650        // Apply block modifications
651        // Only include in `TerrainChanges` if successful
652        let mut updated_blocks = Vec::with_capacity(modified_blocks.len());
653        modified_blocks.retain(|wpos, new| {
654            let res = terrain.map(*wpos, |old| {
655                updated_blocks.push(BlockDiff {
656                    wpos: *wpos,
657                    old,
658                    new: *new,
659                });
660                *new
661            });
662            if let (&Ok(old), true) = (&res, during_tick) {
663                // NOTE: If the changes are applied during the tick, we push the *old* value as
664                // the modified block (since it otherwise can't be recovered after the tick).
665                // Otherwise, the changes will be applied after the tick, so we push the *new*
666                // value.
667                *new = old;
668            }
669            res.is_ok()
670        });
671
672        if !updated_blocks.is_empty() {
673            block_update(&self.ecs, updated_blocks);
674        }
675
676        self.ecs.write_resource::<TerrainChanges>().modified_blocks = modified_blocks;
677    }
678
679    /// Execute a single tick, simulating the game state by the given duration.
680    pub fn tick(
681        &mut self,
682        dt: Duration,
683        update_terrain: bool,
684        mut metrics: Option<&mut StateTickMetrics>,
685        server_constants: &ServerConstants,
686        block_update: impl FnMut(&specs::World, Vec<BlockDiff>),
687    ) {
688        span!(_guard, "tick", "State::tick");
689
690        // Timing code for server metrics
691        macro_rules! section_span {
692            ($guard:ident, $label:literal) => {
693                span!(span_guard, $label);
694                let metrics_guard = metrics.as_mut().map(|m| MetricsGuard::new($label, m));
695                let $guard = (span_guard, metrics_guard);
696            };
697        }
698
699        // Change the time accordingly.
700        let time_scale = self.ecs.read_resource::<TimeScale>().0;
701        self.ecs.write_resource::<TimeOfDay>().0 +=
702            dt.as_secs_f64() * server_constants.day_cycle_coefficient * time_scale;
703        self.ecs.write_resource::<Time>().0 += dt.as_secs_f64() * time_scale;
704        self.ecs.write_resource::<ProgramTime>().0 += dt.as_secs_f64();
705
706        // Update delta time.
707        // Beyond a delta time of MAX_DELTA_TIME, start lagging to avoid skipping
708        // important physics events.
709        self.ecs.write_resource::<DeltaTime>().0 =
710            (dt.as_secs_f32() * time_scale as f32).min(MAX_DELTA_TIME);
711
712        section_span!(guard, "run systems");
713        // This dispatches all the systems in parallel.
714        self.dispatcher.dispatch(&self.ecs);
715        drop(guard);
716
717        self.maintain_ecs();
718
719        if update_terrain {
720            self.apply_terrain_changes_internal(true, block_update);
721        }
722
723        // Process local events
724        section_span!(guard, "process local events");
725
726        let outcomes = self.ecs.read_resource::<EventBus<Outcome>>();
727        let mut outcomes_emitter = outcomes.emitter();
728
729        let events = self.ecs.read_resource::<EventBus<LocalEvent>>().recv_all();
730        for event in events {
731            let mut velocities = self.ecs.write_storage::<comp::Vel>();
732            let physics = self.ecs.read_storage::<comp::PhysicsState>();
733            match event {
734                LocalEvent::Jump(entity, impulse) => {
735                    if let Some(vel) = velocities.get_mut(entity) {
736                        vel.0.z = impulse + physics.get(entity).map_or(0.0, |ps| ps.ground_vel.z);
737                    }
738                },
739                LocalEvent::ApplyImpulse { entity, impulse } => {
740                    if let Some(vel) = velocities.get_mut(entity) {
741                        vel.0 = impulse;
742                    }
743                },
744                LocalEvent::Boost {
745                    entity,
746                    vel: extra_vel,
747                } => {
748                    if let Some(vel) = velocities.get_mut(entity) {
749                        vel.0 += extra_vel;
750                    }
751                },
752                LocalEvent::CreateOutcome(outcome) => {
753                    outcomes_emitter.emit(outcome);
754                },
755            }
756        }
757        drop(guard);
758    }
759
760    pub fn maintain_ecs(&mut self) {
761        span!(_guard, "maintain ecs");
762        self.ecs.maintain();
763    }
764
765    /// Clean up the state after a tick.
766    pub fn cleanup(&mut self) {
767        span!(_guard, "cleanup", "State::cleanup");
768        // Clean up data structures from the last tick.
769        self.ecs.write_resource::<TerrainChanges>().clear();
770    }
771}
772
773// Timing code for server metrics
774#[derive(Default)]
775pub struct StateTickMetrics {
776    pub timings: Vec<(&'static str, Duration)>,
777}
778
779impl StateTickMetrics {
780    fn add(&mut self, label: &'static str, dur: Duration) {
781        // Check for duplicates!
782        debug_assert!(
783            self.timings.iter().all(|(l, _)| *l != label),
784            "Duplicate label in state tick metrics {label}"
785        );
786        self.timings.push((label, dur));
787    }
788}
789
790struct MetricsGuard<'a> {
791    start: Instant,
792    label: &'static str,
793    metrics: &'a mut StateTickMetrics,
794}
795
796impl<'a> MetricsGuard<'a> {
797    fn new(label: &'static str, metrics: &'a mut StateTickMetrics) -> Self {
798        Self {
799            start: Instant::now(),
800            label,
801            metrics,
802        }
803    }
804}
805
806impl Drop for MetricsGuard<'_> {
807    fn drop(&mut self) { self.metrics.add(self.label, self.start.elapsed()); }
808}