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::{self, gizmos::RtsimGizmos},
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        ecs.register::<comp::SpectatingEntity>();
330
331        // Register synced resources used by the ECS.
332        ecs.insert(TimeOfDay(0.0));
333        ecs.insert(Calendar::default());
334        ecs.insert(WeatherGrid::new(Vec2::zero()));
335        ecs.insert(Time(0.0));
336        ecs.insert(ProgramTime(0.0));
337        ecs.insert(TimeScale(1.0));
338
339        // Register unsynced resources used by the ECS.
340        ecs.insert(DeltaTime(0.0));
341        ecs.insert(PlayerEntity(None));
342        ecs.insert(TerrainGrid::new(map_size_lg, default_chunk).unwrap());
343        ecs.insert(BlockChange::default());
344        ecs.insert(ScheduledBlockChange::default());
345        ecs.insert(crate::special_areas::AreasContainer::<BuildArea>::default());
346        ecs.insert(crate::special_areas::AreasContainer::<NoDurabilityArea>::default());
347        ecs.insert(TerrainChanges::default());
348        ecs.insert(EventBus::<LocalEvent>::default());
349        ecs.insert(game_mode);
350        ecs.insert(EventBus::<Outcome>::default());
351        ecs.insert(common::CachedSpatialGrid::default());
352        ecs.insert(EntitiesDiedLastTick::default());
353        ecs.insert(RtsimGizmos::default());
354
355        let num_cpu = num_cpus::get() as u64;
356        let slow_limit = (num_cpu / 2 + num_cpu / 4).max(1);
357        tracing::trace!(?slow_limit, "Slow Thread limit");
358        ecs.insert(SlowJobPool::new(slow_limit, 10_000, thread_pool));
359
360        // TODO: only register on the server
361        ecs.insert(comp::group::GroupManager::default());
362        ecs.insert(SysMetrics::default());
363        ecs.insert(PhysicsMetrics::default());
364        ecs.insert(Trades::default());
365        ecs.insert(PlayerPhysicsSettings::default());
366        ecs.insert(VolumeRiders::default());
367
368        // Load plugins from asset directory
369        #[cfg(feature = "plugins")]
370        ecs.insert({
371            let ecs_world = EcsWorld {
372                entities: &ecs.entities(),
373                health: ecs.read_component().into(),
374                uid: ecs.read_component().into(),
375                id_maps: &ecs.read_resource::<IdMaps>().into(),
376                player: ecs.read_component().into(),
377            };
378            if let Err(e) = plugin_mgr.load_event(&ecs_world, game_mode) {
379                tracing::debug!(?e, "Failed to run plugin init");
380                tracing::info!("Plugins disabled, enable debug logging for more information.");
381                PluginMgr::default()
382            } else {
383                plugin_mgr
384            }
385        });
386
387        ecs
388    }
389
390    /// Register a component with the state's ECS.
391    #[must_use]
392    pub fn with_component<T: Component>(mut self) -> Self
393    where
394        <T as Component>::Storage: Default,
395    {
396        self.ecs.register::<T>();
397        self
398    }
399
400    /// Write a component attributed to a particular entity, ignoring errors.
401    ///
402    /// This should be used *only* when we can guarantee that the rest of the
403    /// code does not rely on the insert having succeeded (meaning the
404    /// entity is no longer alive!).
405    ///
406    /// Returns None if the entity was dead or there was no previous entry for
407    /// this component; otherwise, returns Some(old_component).
408    pub fn write_component_ignore_entity_dead<C: Component>(
409        &mut self,
410        entity: EcsEntity,
411        comp: C,
412    ) -> Option<C> {
413        self.ecs
414            .write_storage()
415            .insert(entity, comp)
416            .ok()
417            .and_then(identity)
418    }
419
420    /// Delete a component attributed to a particular entity.
421    pub fn delete_component<C: Component>(&mut self, entity: EcsEntity) -> Option<C> {
422        self.ecs.write_storage().remove(entity)
423    }
424
425    /// Read a component attributed to a particular entity.
426    pub fn read_component_cloned<C: Component + Clone>(&self, entity: EcsEntity) -> Option<C> {
427        self.ecs.read_storage().get(entity).cloned()
428    }
429
430    /// Read a component attributed to a particular entity.
431    pub fn read_component_copied<C: Component + Copy>(&self, entity: EcsEntity) -> Option<C> {
432        self.ecs.read_storage().get(entity).copied()
433    }
434
435    /// # Panics
436    /// Panics if `EventBus<E>` is borrowed
437    pub fn emit_event_now<E>(&self, event: E)
438    where
439        EventBus<E>: Resource,
440    {
441        self.ecs.write_resource::<EventBus<E>>().emit_now(event)
442    }
443
444    /// Given mutable access to the resource R, assuming the resource
445    /// component exists (this is already the behavior of functions like `fetch`
446    /// and `write_component_ignore_entity_dead`).  Since all of our resources
447    /// are generated up front, any failure here is definitely a code bug.
448    pub fn mut_resource<R: Resource>(&mut self) -> &mut R {
449        self.ecs.get_mut::<R>().expect(
450            "Tried to fetch an invalid resource even though all our resources should be known at \
451             compile time.",
452        )
453    }
454
455    /// Get a read-only reference to the storage of a particular component type.
456    pub fn read_storage<C: Component>(&self) -> EcsStorage<'_, C, Fetch<'_, EcsMaskedStorage<C>>> {
457        self.ecs.read_storage::<C>()
458    }
459
460    /// Get a reference to the internal ECS world.
461    pub fn ecs(&self) -> &specs::World { &self.ecs }
462
463    /// Get a mutable reference to the internal ECS world.
464    pub fn ecs_mut(&mut self) -> &mut specs::World { &mut self.ecs }
465
466    pub fn thread_pool(&self) -> &Arc<ThreadPool> { &self.thread_pool }
467
468    /// Get a reference to the `TerrainChanges` structure of the state. This
469    /// contains information about terrain state that has changed since the
470    /// last game tick.
471    pub fn terrain_changes(&self) -> Fetch<'_, TerrainChanges> { self.ecs.read_resource() }
472
473    /// Get a reference the current in-game weather grid.
474    pub fn weather_grid(&self) -> Fetch<'_, WeatherGrid> { self.ecs.read_resource() }
475
476    /// Get a mutable reference the current in-game weather grid.
477    pub fn weather_grid_mut(&mut self) -> FetchMut<'_, WeatherGrid> { self.ecs.write_resource() }
478
479    /// Get the current weather at a position in worldspace.
480    pub fn weather_at(&self, pos: Vec2<f32>) -> Weather {
481        self.weather_grid().get_interpolated(pos)
482    }
483
484    /// Get the max weather near a position in worldspace.
485    pub fn max_weather_near(&self, pos: Vec2<f32>) -> Weather {
486        self.weather_grid().get_max_near(pos)
487    }
488
489    /// Get the current in-game time of day.
490    ///
491    /// Note that this should not be used for physics, animations or other such
492    /// localised timings.
493    pub fn get_time_of_day(&self) -> f64 { self.ecs.read_resource::<TimeOfDay>().0 }
494
495    /// Get the current in-game day period (period of the day/night cycle)
496    pub fn get_day_period(&self) -> DayPeriod { self.get_time_of_day().into() }
497
498    /// Get the current in-game time.
499    ///
500    /// Note that this does not correspond to the time of day.
501    pub fn get_time(&self) -> f64 { self.ecs.read_resource::<Time>().0 }
502
503    /// Get the current true in-game time, unaffected by time_scale.
504    ///
505    /// Note that this does not correspond to the time of day.
506    pub fn get_program_time(&self) -> f64 { self.ecs.read_resource::<ProgramTime>().0 }
507
508    /// Get the current delta time.
509    pub fn get_delta_time(&self) -> f32 { self.ecs.read_resource::<DeltaTime>().0 }
510
511    /// Get a reference to this state's terrain.
512    pub fn terrain(&self) -> Fetch<'_, TerrainGrid> { self.ecs.read_resource() }
513
514    /// Get a reference to this state's terrain.
515    pub fn slow_job_pool(&self) -> Fetch<'_, SlowJobPool> { self.ecs.read_resource() }
516
517    /// Get a writable reference to this state's terrain.
518    pub fn terrain_mut(&self) -> FetchMut<'_, TerrainGrid> { self.ecs.write_resource() }
519
520    /// Get a block in this state's terrain.
521    pub fn get_block(&self, pos: Vec3<i32>) -> Option<Block> {
522        self.terrain().get(pos).ok().copied()
523    }
524
525    /// Set a block in this state's terrain.
526    pub fn set_block(&self, pos: Vec3<i32>, block: Block) {
527        self.ecs.write_resource::<BlockChange>().set(pos, block);
528    }
529
530    /// Set a block in this state's terrain (used to delete temporary summoned
531    /// sprites after a timeout).
532    pub fn schedule_set_block(
533        &self,
534        pos: Vec3<i32>,
535        block: Block,
536        sprite_block: Block,
537        replace_time: f64,
538    ) {
539        self.ecs
540            .write_resource::<ScheduledBlockChange>()
541            .set(pos, block, replace_time);
542        self.ecs
543            .write_resource::<ScheduledBlockChange>()
544            .outcome_set(pos, sprite_block, replace_time);
545    }
546
547    /// Check if the block at given position `pos` has already been modified
548    /// this tick.
549    pub fn can_set_block(&self, pos: Vec3<i32>) -> bool {
550        self.ecs.read_resource::<BlockChange>().can_set_block(pos)
551    }
552
553    /// Removes every chunk of the terrain.
554    pub fn clear_terrain(&mut self) -> usize {
555        let removed_chunks = &mut self.ecs.write_resource::<TerrainChanges>().removed_chunks;
556
557        self.terrain_mut()
558            .drain()
559            .map(|(key, _)| {
560                removed_chunks.insert(key);
561            })
562            .count()
563    }
564
565    /// Insert the provided chunk into this state's terrain.
566    pub fn insert_chunk(&mut self, key: Vec2<i32>, chunk: Arc<TerrainChunk>) {
567        if self
568            .ecs
569            .write_resource::<TerrainGrid>()
570            .insert(key, chunk)
571            .is_some()
572        {
573            self.ecs
574                .write_resource::<TerrainChanges>()
575                .modified_chunks
576                .insert(key);
577        } else {
578            self.ecs
579                .write_resource::<TerrainChanges>()
580                .new_chunks
581                .insert(key);
582        }
583    }
584
585    /// Remove the chunk with the given key from this state's terrain, if it
586    /// exists.
587    pub fn remove_chunk(&mut self, key: Vec2<i32>) -> bool {
588        if self
589            .ecs
590            .write_resource::<TerrainGrid>()
591            .remove(key)
592            .is_some()
593        {
594            self.ecs
595                .write_resource::<TerrainChanges>()
596                .removed_chunks
597                .insert(key);
598
599            true
600        } else {
601            false
602        }
603    }
604
605    // Apply terrain changes
606    pub fn apply_terrain_changes(&self, block_update: impl FnMut(&specs::World, Vec<BlockDiff>)) {
607        self.apply_terrain_changes_internal(false, block_update);
608    }
609
610    /// `during_tick` is true if and only if this is called from within
611    /// [State::tick].
612    ///
613    /// This only happens if [State::tick] is asked to update terrain itself
614    /// (using `update_terrain: true`).  [State::tick] is called from within
615    /// both the client and the server ticks, right after handling terrain
616    /// messages; currently, client sets it to true and server to false.
617    fn apply_terrain_changes_internal(
618        &self,
619        during_tick: bool,
620        mut block_update: impl FnMut(&specs::World, Vec<BlockDiff>),
621    ) {
622        span!(
623            _guard,
624            "apply_terrain_changes",
625            "State::apply_terrain_changes"
626        );
627        let mut terrain = self.ecs.write_resource::<TerrainGrid>();
628        let mut modified_blocks =
629            std::mem::take(&mut self.ecs.write_resource::<BlockChange>().blocks);
630
631        let mut scheduled_changes = self.ecs.write_resource::<ScheduledBlockChange>();
632        let current_time: f64 = self.ecs.read_resource::<Time>().0 * SECONDS_TO_MILLISECONDS;
633        let current_time = current_time as u64;
634        // This is important as the poll function has a debug assert that the new poll
635        // is at a more recent time than the old poll. As Time is synced between server
636        // and client, there is a chance that client dt can get slightly ahead of a
637        // server update, so we do not want to panic in that scenario.
638        if scheduled_changes.last_poll_time < current_time {
639            scheduled_changes.last_poll_time = current_time;
640            while let Some(changes) = scheduled_changes.changes.poll(current_time) {
641                modified_blocks.extend(changes.iter());
642            }
643            let outcome = self.ecs.read_resource::<EventBus<Outcome>>();
644            while let Some(outcomes) = scheduled_changes.outcomes.poll(current_time) {
645                for (pos, block) in outcomes.into_iter() {
646                    if let Some(sprite) = block.get_sprite() {
647                        outcome.emit_now(Outcome::SpriteDelete { pos, sprite });
648                    }
649                }
650            }
651        }
652        // Apply block modifications
653        // Only include in `TerrainChanges` if successful
654        let mut updated_blocks = Vec::with_capacity(modified_blocks.len());
655        modified_blocks.retain(|wpos, new| {
656            let res = terrain.map(*wpos, |old| {
657                updated_blocks.push(BlockDiff {
658                    wpos: *wpos,
659                    old,
660                    new: *new,
661                });
662                *new
663            });
664            if let (&Ok(old), true) = (&res, during_tick) {
665                // NOTE: If the changes are applied during the tick, we push the *old* value as
666                // the modified block (since it otherwise can't be recovered after the tick).
667                // Otherwise, the changes will be applied after the tick, so we push the *new*
668                // value.
669                *new = old;
670            }
671            res.is_ok()
672        });
673
674        if !updated_blocks.is_empty() {
675            block_update(&self.ecs, updated_blocks);
676        }
677
678        self.ecs.write_resource::<TerrainChanges>().modified_blocks = modified_blocks;
679    }
680
681    /// Execute a single tick, simulating the game state by the given duration.
682    pub fn tick(
683        &mut self,
684        dt: Duration,
685        update_terrain: bool,
686        mut metrics: Option<&mut StateTickMetrics>,
687        server_constants: &ServerConstants,
688        block_update: impl FnMut(&specs::World, Vec<BlockDiff>),
689    ) {
690        span!(_guard, "tick", "State::tick");
691
692        // Timing code for server metrics
693        macro_rules! section_span {
694            ($guard:ident, $label:literal) => {
695                span!(span_guard, $label);
696                let metrics_guard = metrics.as_mut().map(|m| MetricsGuard::new($label, m));
697                let $guard = (span_guard, metrics_guard);
698            };
699        }
700
701        // Change the time accordingly.
702        let time_scale = self.ecs.read_resource::<TimeScale>().0;
703        self.ecs.write_resource::<TimeOfDay>().0 +=
704            dt.as_secs_f64() * server_constants.day_cycle_coefficient * time_scale;
705        self.ecs.write_resource::<Time>().0 += dt.as_secs_f64() * time_scale;
706        self.ecs.write_resource::<ProgramTime>().0 += dt.as_secs_f64();
707
708        // Update delta time.
709        // Beyond a delta time of MAX_DELTA_TIME, start lagging to avoid skipping
710        // important physics events.
711        self.ecs.write_resource::<DeltaTime>().0 =
712            (dt.as_secs_f32() * time_scale as f32).min(MAX_DELTA_TIME);
713
714        section_span!(guard, "run systems");
715        // This dispatches all the systems in parallel.
716        self.dispatcher.dispatch(&self.ecs);
717        drop(guard);
718
719        self.maintain_ecs();
720
721        if update_terrain {
722            self.apply_terrain_changes_internal(true, block_update);
723        }
724
725        // Process local events
726        section_span!(guard, "process local events");
727
728        let outcomes = self.ecs.read_resource::<EventBus<Outcome>>();
729        let mut outcomes_emitter = outcomes.emitter();
730
731        let events = self.ecs.read_resource::<EventBus<LocalEvent>>().recv_all();
732        for event in events {
733            let mut velocities = self.ecs.write_storage::<comp::Vel>();
734            let physics = self.ecs.read_storage::<comp::PhysicsState>();
735            match event {
736                LocalEvent::Jump(entity, impulse) => {
737                    if let Some(vel) = velocities.get_mut(entity) {
738                        vel.0.z = impulse + physics.get(entity).map_or(0.0, |ps| ps.ground_vel.z);
739                    }
740                },
741                LocalEvent::ApplyImpulse { entity, impulse } => {
742                    if let Some(vel) = velocities.get_mut(entity) {
743                        vel.0 = impulse;
744                    }
745                },
746                LocalEvent::Boost {
747                    entity,
748                    vel: extra_vel,
749                } => {
750                    if let Some(vel) = velocities.get_mut(entity) {
751                        vel.0 += extra_vel;
752                    }
753                },
754                LocalEvent::CreateOutcome(outcome) => {
755                    outcomes_emitter.emit(outcome);
756                },
757            }
758        }
759        drop(guard);
760    }
761
762    pub fn maintain_ecs(&mut self) {
763        span!(_guard, "maintain ecs");
764        self.ecs.maintain();
765    }
766
767    /// Clean up the state after a tick.
768    pub fn cleanup(&mut self) {
769        span!(_guard, "cleanup", "State::cleanup");
770        // Clean up data structures from the last tick.
771        self.ecs.write_resource::<TerrainChanges>().clear();
772    }
773}
774
775// Timing code for server metrics
776#[derive(Default)]
777pub struct StateTickMetrics {
778    pub timings: Vec<(&'static str, Duration)>,
779}
780
781impl StateTickMetrics {
782    fn add(&mut self, label: &'static str, dur: Duration) {
783        // Check for duplicates!
784        debug_assert!(
785            self.timings.iter().all(|(l, _)| *l != label),
786            "Duplicate label in state tick metrics {label}"
787        );
788        self.timings.push((label, dur));
789    }
790}
791
792struct MetricsGuard<'a> {
793    start: Instant,
794    label: &'static str,
795    metrics: &'a mut StateTickMetrics,
796}
797
798impl<'a> MetricsGuard<'a> {
799    fn new(label: &'static str, metrics: &'a mut StateTickMetrics) -> Self {
800        Self {
801            start: Instant::now(),
802            label,
803            metrics,
804        }
805    }
806}
807
808impl Drop for MetricsGuard<'_> {
809    fn drop(&mut self) { self.metrics.add(self.label, self.start.elapsed()); }
810}