Skip to main content

veloren_server/
lib.rs

1#![deny(unsafe_code)]
2#![expect(
3    clippy::option_map_unit_fn,
4    clippy::needless_pass_by_ref_mut // until we find a better way for specs
5)]
6#![deny(clippy::clone_on_ref_ptr)]
7#![feature(box_patterns, option_zip, const_type_name, slice_partition_dedup)]
8
9pub mod automod;
10mod character_creator;
11pub mod chat;
12pub mod chunk_generator;
13mod chunk_serialize;
14pub mod client;
15pub mod cmd;
16pub mod connection_handler;
17mod data_dir;
18pub mod error;
19pub mod events;
20pub mod input;
21pub mod location;
22pub mod lod;
23pub mod login_provider;
24pub mod metrics;
25pub mod persistence;
26mod pet;
27pub mod presence;
28pub mod rtsim;
29pub mod settings;
30pub mod state_ext;
31pub mod sys;
32#[cfg(feature = "persistent_world")]
33pub mod terrain_persistence;
34#[cfg(not(feature = "worldgen"))] mod test_world;
35
36#[cfg(feature = "worldgen")] mod weather;
37
38pub mod wiring;
39
40// Reexports
41pub use crate::{
42    data_dir::DEFAULT_DATA_DIR_NAME,
43    error::Error,
44    events::Event,
45    input::Input,
46    settings::{CalendarMode, EditableSettings, Settings},
47};
48
49#[cfg(feature = "persistent_world")]
50use crate::terrain_persistence::TerrainPersistence;
51use crate::{
52    automod::AutoMod,
53    chunk_generator::ChunkGenerator,
54    client::Client,
55    cmd::ChatCommandExt,
56    connection_handler::ConnectionHandler,
57    data_dir::DataDir,
58    location::Locations,
59    login_provider::LoginProvider,
60    persistence::PersistedComponents,
61    presence::{RegionSubscription, RepositionToFreeSpace},
62    state_ext::StateExt,
63    sys::sentinel::DeletedEntities,
64};
65use authc::Uuid;
66use censor::Censor;
67#[cfg(not(feature = "worldgen"))]
68use common::grid::Grid;
69#[cfg(feature = "worldgen")]
70use common::terrain::CoordinateConversions;
71#[cfg(feature = "worldgen")]
72use common::terrain::TerrainChunkSize;
73use common::{
74    assets::AssetExt,
75    calendar::Calendar,
76    character::{CharacterId, CharacterItem},
77    cmd::ServerChatCommand,
78    comp::{self, ChatType, Content},
79    event::{
80        ClientDisconnectEvent, ClientDisconnectWithoutPersistenceEvent, EventBus, ExitIngameEvent,
81        UpdateCharacterDataEvent,
82    },
83    link::Is,
84    mounting::{Volume, VolumeRider},
85    region::RegionMap,
86    resources::{BattleMode, GameMode, Time, TimeOfDay},
87    shared_server_config::ServerConstants,
88    slowjob::SlowJobPool,
89    terrain::TerrainChunk,
90    uid::Uid,
91    vol::RectRasterableVol,
92};
93use common_base::prof_span;
94use common_ecs::run_now;
95use common_net::{
96    msg::{ClientType, DisconnectReason, PlayerListUpdate, ServerGeneral, ServerInfo, ServerMsg},
97    sync::WorldSyncExt,
98};
99use common_state::{AreasContainer, BlockDiff, BuildArea, State};
100use common_systems::add_local_systems;
101use metrics::{EcsSystemMetrics, GameplayMetrics, PhysicsMetrics, TickMetrics};
102use network::{ListenAddr, Network, Pid};
103use persistence::{
104    character_loader::{CharacterLoader, CharacterUpdaterMessage},
105    character_updater::CharacterUpdater,
106};
107use prometheus::Registry;
108use rustls::pki_types::{CertificateDer, PrivateKeyDer};
109use settings::banlist::NormalizedIpAddr;
110use specs::{
111    Builder, Entity as EcsEntity, Entity, Join, LendJoin, WorldExt, shred::SendDispatcher,
112};
113use std::{
114    ops::{Deref, DerefMut},
115    sync::{Arc, Mutex},
116    time::{Duration, Instant},
117};
118#[cfg(not(feature = "worldgen"))]
119use test_world::{IndexOwned, World};
120use tokio::runtime::Runtime;
121use tracing::{debug, error, info, trace, warn};
122use vek::*;
123use veloren_query_server::server::QueryServer;
124pub use world::{WorldGenerateStage, civ::WorldCivStage, sim::WorldSimStage};
125
126use crate::{
127    persistence::{DatabaseSettings, SqlLogMode},
128    sys::terrain,
129};
130use hashbrown::HashMap;
131use std::sync::RwLock;
132
133use crate::settings::Protocol;
134
135#[cfg(feature = "plugins")]
136use {
137    common::uid::IdMaps,
138    common_state::plugin::{PluginMgr, memory_manager::EcsWorld},
139};
140
141use crate::{chat::ChatCache, persistence::character_loader::CharacterScreenResponseKind};
142use common::comp::Anchor;
143#[cfg(feature = "worldgen")]
144pub use world::{
145    IndexOwned, World,
146    sim::{DEFAULT_WORLD_MAP, DEFAULT_WORLD_SEED, FileOpts, GenOpts, WorldOpts},
147};
148
149/// Number of seconds a player must wait before they can change their battle
150/// mode after each change.
151///
152/// TODO: Discuss time
153const BATTLE_MODE_COOLDOWN: f64 = 60.0 * 5.0;
154
155/// SpawnPoint corresponds to the default location that players are positioned
156/// at if they have no waypoint. Players *should* always have a waypoint, so
157/// this should basically never be used in practice.
158#[derive(Copy, Clone)]
159pub struct SpawnPoint(pub Vec3<f32>);
160
161impl Default for SpawnPoint {
162    fn default() -> Self { Self(Vec3::new(0.0, 0.0, 256.0)) }
163}
164
165// This is the minimum chunk range that is kept loaded around each player
166// server-side. This is independent of the client's view distance and exists to
167// avoid exploits such as small view distance chunk reloading and also to keep
168// various mechanics working fluidly (i.e: not unloading nearby entities).
169pub const MIN_VD: u32 = 6;
170
171// Tick count used for throttling network updates
172// Note this doesn't account for dt (so update rate changes with tick rate)
173#[derive(Copy, Clone, Default)]
174pub struct Tick(u64);
175
176#[derive(Clone)]
177pub struct HwStats {
178    hardware_threads: u32,
179    rayon_threads: u32,
180}
181
182#[derive(Clone, Copy, PartialEq)]
183enum DisconnectType {
184    WithPersistence,
185    WithoutPersistence,
186}
187
188// Start of Tick, used for metrics
189#[derive(Copy, Clone)]
190pub struct TickStart(Instant);
191
192/// Store of BattleMode cooldowns for players while they go offline
193#[derive(Clone, Default, Debug)]
194pub struct BattleModeBuffer {
195    map: HashMap<CharacterId, (BattleMode, Time)>,
196}
197
198impl BattleModeBuffer {
199    pub fn push(&mut self, char_id: CharacterId, save: (BattleMode, Time)) {
200        self.map.insert(char_id, save);
201    }
202
203    pub fn get(&self, char_id: &CharacterId) -> Option<&(BattleMode, Time)> {
204        self.map.get(char_id)
205    }
206
207    pub fn pop(&mut self, char_id: &CharacterId) -> Option<(BattleMode, Time)> {
208        self.map.remove(char_id)
209    }
210}
211
212/// Keeps the IPs of recently logged off clients in memory, only used
213/// for IP bans if the target is no longer online.
214pub struct RecentClientIPs {
215    pub last_addrs: schnellru::LruMap<Uuid, NormalizedIpAddr>,
216}
217
218impl Default for RecentClientIPs {
219    fn default() -> Self {
220        Self {
221            last_addrs: schnellru::LruMap::new(schnellru::ByLength::new(1000)),
222        }
223    }
224}
225
226pub struct ChunkRequest {
227    entity: EcsEntity,
228    key: Vec2<i32>,
229}
230
231#[derive(Debug)]
232pub enum ServerInitStage {
233    DbMigrations,
234    DbVacuum,
235    WorldGen(WorldGenerateStage),
236    StartingSystems,
237}
238
239pub struct Server {
240    state: State,
241    world: Arc<World>,
242    index: IndexOwned,
243
244    connection_handler: ConnectionHandler,
245
246    runtime: Arc<Runtime>,
247
248    metrics_registry: Arc<Registry>,
249    chat_cache: ChatCache,
250    database_settings: Arc<RwLock<DatabaseSettings>>,
251    disconnect_all_clients_requested: bool,
252
253    event_dispatcher: SendDispatcher<'static>,
254}
255
256impl Server {
257    /// Create a new `Server`
258    pub fn new(
259        settings: Settings,
260        editable_settings: EditableSettings,
261        database_settings: DatabaseSettings,
262        data_dir: &std::path::Path,
263        report_stage: &(dyn Fn(ServerInitStage) + Send + Sync),
264        runtime: Arc<Runtime>,
265    ) -> Result<Self, Error> {
266        prof_span!("Server::new");
267        info!("Server data dir is: {}", data_dir.display());
268        if settings.auth_server_address.is_none() {
269            info!("Authentication is disabled");
270        }
271
272        report_stage(ServerInitStage::DbMigrations);
273        // Run pending DB migrations (if any)
274        debug!("Running DB migrations...");
275        persistence::run_migrations(&database_settings);
276
277        report_stage(ServerInitStage::DbVacuum);
278        // Vacuum database
279        debug!("Vacuuming database...");
280        persistence::vacuum_database(&database_settings);
281
282        let database_settings = Arc::new(RwLock::new(database_settings));
283
284        let registry = Arc::new(Registry::new());
285        let chunk_gen_metrics = metrics::ChunkGenMetrics::new(&registry).unwrap();
286        let job_metrics = metrics::JobMetrics::new(&registry).unwrap();
287        let network_request_metrics = metrics::NetworkRequestMetrics::new(&registry).unwrap();
288        let player_metrics = metrics::PlayerMetrics::new(&registry).unwrap();
289        let ecs_system_metrics = EcsSystemMetrics::new(&registry).unwrap();
290        let tick_metrics = TickMetrics::new(&registry).unwrap();
291        let physics_metrics = PhysicsMetrics::new(&registry).unwrap();
292        let server_event_metrics = metrics::ServerEventMetrics::new(&registry).unwrap();
293        let gameplay_metrics = GameplayMetrics::new(&registry).unwrap();
294        let query_server_metrics = metrics::QueryServerMetrics::new(&registry).unwrap();
295
296        let battlemode_buffer = BattleModeBuffer::default();
297
298        let pools = State::pools(GameMode::Server);
299
300        // Load plugins before generating the world.
301        #[cfg(feature = "plugins")]
302        let plugin_mgr = PluginMgr::from_asset_or_default();
303
304        debug!("Generating world, seed: {}", settings.world_seed);
305        #[cfg(feature = "worldgen")]
306        let (world, index) = World::generate(
307            settings.world_seed,
308            WorldOpts {
309                seed_elements: true,
310                world_file: if let Some(ref opts) = settings.map_file {
311                    opts.clone()
312                } else {
313                    // Load default map from assets.
314                    FileOpts::LoadAsset(DEFAULT_WORLD_MAP.into())
315                },
316                calendar: Some(settings.calendar_mode.calendar_now()),
317            },
318            &pools,
319            &|stage| {
320                report_stage(ServerInitStage::WorldGen(stage));
321            },
322        );
323        #[cfg(not(feature = "worldgen"))]
324        let (world, index) = World::generate(settings.world_seed);
325
326        #[cfg(feature = "worldgen")]
327        let map = world.get_map_data(index.as_index_ref(), &pools);
328        #[cfg(not(feature = "worldgen"))]
329        let map = common_net::msg::WorldMapMsg {
330            dimensions_lg: Vec2::zero(),
331            max_height: 1.0,
332            rgba: Grid::new(Vec2::new(1, 1), 1),
333            horizons: [(vec![0], vec![0]), (vec![0], vec![0])],
334            alt: Grid::new(Vec2::new(1, 1), 1),
335            sites: Vec::new(),
336            possible_starting_sites: Vec::new(),
337            pois: Vec::new(),
338            default_chunk: Arc::new(world.generate_oob_chunk()),
339        };
340
341        #[cfg(feature = "worldgen")]
342        let map_size_lg = world.sim().map_size_lg();
343        #[cfg(not(feature = "worldgen"))]
344        let map_size_lg = world.map_size_lg();
345
346        let lod = lod::Lod::from_world(&world, index.as_index_ref(), &pools);
347
348        report_stage(ServerInitStage::StartingSystems);
349
350        let mut state = State::server(
351            Arc::clone(&pools),
352            map_size_lg,
353            Arc::clone(&map.default_chunk),
354            |dispatcher_builder| {
355                add_local_systems(dispatcher_builder);
356                sys::msg::add_server_systems(dispatcher_builder);
357                sys::add_server_systems(dispatcher_builder);
358                #[cfg(feature = "worldgen")]
359                {
360                    rtsim::add_server_systems(dispatcher_builder);
361                    weather::add_server_systems(dispatcher_builder);
362                }
363            },
364            #[cfg(feature = "plugins")]
365            plugin_mgr,
366        );
367        events::register_event_busses(state.ecs_mut());
368        state.ecs_mut().insert(battlemode_buffer);
369        state.ecs_mut().insert(RecentClientIPs::default());
370        state.ecs_mut().insert(settings.clone());
371        state.ecs_mut().insert(editable_settings);
372        state.ecs_mut().insert(DataDir {
373            path: data_dir.to_owned(),
374        });
375
376        state.ecs_mut().insert(Vec::<ChunkRequest>::new());
377        state
378            .ecs_mut()
379            .insert(EventBus::<chunk_serialize::ChunkSendEntry>::default());
380        state.ecs_mut().insert(Locations::default());
381        state.ecs_mut().insert(LoginProvider::new(
382            settings.auth_server_address.clone(),
383            Arc::clone(&runtime),
384        ));
385        state.ecs_mut().insert(HwStats {
386            hardware_threads: num_cpus::get() as u32,
387            rayon_threads: num_cpus::get() as u32,
388        });
389        state.ecs_mut().insert(ServerConstants {
390            day_cycle_coefficient: settings.day_cycle_coefficient(),
391        });
392        state.ecs_mut().insert(Tick(0));
393        state.ecs_mut().insert(TickStart(Instant::now()));
394        state.ecs_mut().insert(job_metrics);
395        state.ecs_mut().insert(network_request_metrics);
396        state.ecs_mut().insert(player_metrics);
397        state.ecs_mut().insert(ecs_system_metrics);
398        state.ecs_mut().insert(tick_metrics);
399        state.ecs_mut().insert(physics_metrics);
400        state.ecs_mut().insert(server_event_metrics);
401        state.ecs_mut().insert(gameplay_metrics);
402        state.ecs_mut().insert(query_server_metrics);
403        if settings.experimental_terrain_persistence {
404            #[cfg(feature = "persistent_world")]
405            {
406                warn!(
407                    "Experimental terrain persistence support is enabled. This feature may break, \
408                     be disabled, or otherwise change under your feet at *any time*. \
409                     Additionally, it is expected to be replaced in the future *without* \
410                     migration or warning. You have been warned."
411                );
412                state
413                    .ecs_mut()
414                    .insert(TerrainPersistence::new(data_dir.to_owned()));
415            }
416            #[cfg(not(feature = "persistent_world"))]
417            error!(
418                "Experimental terrain persistence support was requested, but the server was not \
419                 compiled with the feature. Terrain modifications will *not* be persisted."
420            );
421        }
422        {
423            let pool = state.ecs_mut().write_resource::<SlowJobPool>();
424            pool.configure("CHUNK_DROP", |_n| 1);
425            pool.configure("CHUNK_GENERATOR", |n| n / 2 + n / 4);
426            pool.configure("CHUNK_SERIALIZER", |n| n / 2);
427            pool.configure("RTSIM_SAVE", |_| 1);
428            pool.configure("WEATHER", |_| 1);
429        }
430        state
431            .ecs_mut()
432            .insert(ChunkGenerator::new(chunk_gen_metrics));
433        {
434            let (sender, receiver) =
435                crossbeam_channel::bounded::<chunk_serialize::SerializedChunk>(10_000);
436            state.ecs_mut().insert(sender);
437            state.ecs_mut().insert(receiver);
438        }
439
440        state.ecs_mut().insert(CharacterUpdater::new(
441            Arc::<RwLock<DatabaseSettings>>::clone(&database_settings),
442        )?);
443
444        let ability_map = comp::item::tool::AbilityMap::<comp::AbilityItem>::load_expect_cloned(
445            "common.abilities.ability_set_manifest",
446        );
447        state.ecs_mut().insert(ability_map);
448
449        let msm = comp::inventory::item::MaterialStatManifest::load().cloned();
450        state.ecs_mut().insert(msm);
451
452        let rbm = common::recipe::RecipeBookManifest::load().cloned();
453        state.ecs_mut().insert(rbm);
454
455        state.ecs_mut().insert(CharacterLoader::new(
456            Arc::<RwLock<DatabaseSettings>>::clone(&database_settings),
457        )?);
458
459        // System schedulers to control execution of systems
460        state
461            .ecs_mut()
462            .insert(sys::PersistenceScheduler::every(Duration::from_secs(10)));
463
464        // Region map (spatial structure for entity synchronization)
465        state.ecs_mut().insert(RegionMap::new());
466
467        // Server-only components
468        state.ecs_mut().register::<RegionSubscription>();
469        state.ecs_mut().register::<Client>();
470        state.ecs_mut().register::<comp::Presence>();
471        state.ecs_mut().register::<wiring::WiringElement>();
472        state.ecs_mut().register::<wiring::Circuit>();
473        state.ecs_mut().register::<Anchor>();
474        state.ecs_mut().register::<comp::Pet>();
475        state.ecs_mut().register::<login_provider::PendingLogin>();
476        state.ecs_mut().register::<RepositionToFreeSpace>();
477        state.ecs_mut().register::<common::rtsim::ActorId>();
478
479        // Load banned words list
480        let banned_words = settings.moderation.load_banned_words(data_dir);
481        let censor = Arc::new(Censor::Custom(banned_words.into_iter().collect()));
482        state.ecs_mut().insert(Arc::clone(&censor));
483
484        // Init automod
485        state
486            .ecs_mut()
487            .insert(AutoMod::new(&settings.moderation, censor));
488
489        state.ecs_mut().insert(map);
490
491        #[cfg(feature = "worldgen")]
492        let spawn_point = SpawnPoint({
493            let index = index.as_index_ref();
494            // NOTE: all of these `.map(|e| e as [type])` calls should compile into no-ops,
495            // but are needed to be explicit about casting (and to make the compiler stop
496            // complaining)
497
498            // Search for town defined by spawn_town server setting. If this fails, or is
499            // None, set spawn to the nearest town to the centre of the world
500            let center_chunk = world.sim().map_size_lg().chunks().map(i32::from) / 2;
501            let spawn_chunk = world
502                .civs()
503                .sites()
504                .filter(|site| site.is_settlement())
505                .map(|site| site.center)
506                .min_by_key(|site_pos| site_pos.distance_squared(center_chunk))
507                .unwrap_or(center_chunk);
508
509            world.find_accessible_pos(index, TerrainChunkSize::center_wpos(spawn_chunk), false)
510        });
511        #[cfg(not(feature = "worldgen"))]
512        let spawn_point = SpawnPoint::default();
513
514        // Set the spawn point we calculated above
515        state.ecs_mut().insert(spawn_point);
516
517        // Insert a default AABB for the world
518        // TODO: prevent this from being deleted
519        {
520            #[cfg(feature = "worldgen")]
521            let size = world.sim().get_size();
522            #[cfg(not(feature = "worldgen"))]
523            let size = world.map_size_lg().chunks().map(u32::from);
524
525            let world_size = size.map(|e| e as i32) * TerrainChunk::RECT_SIZE.map(|e| e as i32);
526            let world_aabb = Aabb {
527                min: Vec3::new(0, 0, -32768),
528                max: Vec3::new(world_size.x, world_size.y, 32767),
529            }
530            .made_valid();
531
532            state
533                .ecs()
534                .write_resource::<AreasContainer<BuildArea>>()
535                .insert("world".to_string(), world_aabb)
536                .expect("The initial insert should always work.");
537        }
538
539        // Insert the world into the ECS (todo: Maybe not an Arc?)
540        let world = Arc::new(world);
541        state.ecs_mut().insert(Arc::clone(&world));
542        state.ecs_mut().insert(lod);
543        state.ecs_mut().insert(index.clone());
544
545        // Set starting time for the server.
546        state.ecs_mut().write_resource::<TimeOfDay>().0 = settings.world.start_time;
547
548        // Register trackers
549        sys::sentinel::UpdateTrackers::register(state.ecs_mut());
550
551        state.ecs_mut().insert(DeletedEntities::default());
552
553        // Only allow clients to send us a maximum of 1 MB per uncompressed message, to
554        // reduce the effectiveness of a DoS attack
555        let network = Network::new_with_registry(Pid::new(), &runtime, &registry, 1 << 20);
556        let (chat_cache, chat_tracker) = ChatCache::new(Duration::from_secs(60), &runtime);
557        state.ecs_mut().insert(chat_tracker);
558
559        let mut printed_quic_warning = false;
560        for protocol in &settings.gameserver_protocols {
561            match protocol {
562                Protocol::Tcp { address } => {
563                    runtime.block_on(network.listen(ListenAddr::Tcp(*address)))?;
564                },
565                Protocol::Quic {
566                    address,
567                    cert_file_path,
568                    key_file_path,
569                } => {
570                    use rustls_pemfile::Item;
571                    use std::fs;
572
573                    match || -> Result<_, Box<dyn std::error::Error>> {
574                        let key = fs::read(key_file_path)?;
575                        let key = if key_file_path.extension().is_some_and(|x| x == "der") {
576                            PrivateKeyDer::try_from(key).map_err(|_| "No valid pem key in file")?
577                        } else {
578                            debug!("convert pem key to der");
579                            rustls_pemfile::read_all(&mut key.as_slice())
580                                .find_map(|item| match item {
581                                    Ok(Item::Pkcs1Key(v)) => Some(PrivateKeyDer::Pkcs1(v)),
582                                    Ok(Item::Pkcs8Key(v)) => Some(PrivateKeyDer::Pkcs8(v)),
583                                    Ok(Item::Sec1Key(v)) => Some(PrivateKeyDer::Sec1(v)),
584                                    Ok(Item::Crl(_)) => None,
585                                    Ok(Item::Csr(_)) => None,
586                                    Ok(Item::X509Certificate(_)) => None,
587                                    Ok(_) => None,
588                                    Err(e) => {
589                                        tracing::warn!(?e, "error while reading key_file");
590                                        None
591                                    },
592                                })
593                                .ok_or("No valid pem key in file")?
594                        };
595                        let cert_chain = fs::read(cert_file_path)?;
596                        let cert_chain = if cert_file_path.extension().is_some_and(|x| x == "der") {
597                            vec![CertificateDer::from(cert_chain)]
598                        } else {
599                            debug!("convert pem cert to der");
600                            rustls_pemfile::certs(&mut cert_chain.as_slice())
601                                .filter_map(|item| match item {
602                                    Ok(cert) => Some(cert),
603                                    Err(e) => {
604                                        tracing::warn!(?e, "error while reading cert_file");
605                                        None
606                                    },
607                                })
608                                .collect()
609                        };
610                        let server_config = quinn::ServerConfig::with_single_cert(cert_chain, key)?;
611                        Ok(server_config)
612                    }() {
613                        Ok(server_config) => {
614                            runtime.block_on(
615                                network.listen(ListenAddr::Quic(*address, server_config.clone())),
616                            )?;
617
618                            if !printed_quic_warning {
619                                warn!(
620                                    "QUIC is enabled. This is experimental and not recommended in \
621                                     production"
622                                );
623                                printed_quic_warning = true;
624                            }
625                        },
626                        Err(e) => {
627                            error!(
628                                ?e,
629                                "Failed to load the TLS certificate, running without QUIC {}",
630                                *address
631                            );
632                        },
633                    }
634                },
635            }
636        }
637
638        if let Some(addr) = settings.query_address {
639            use veloren_query_server::proto::ServerInfo;
640
641            const QUERY_SERVER_RATELIMIT: u16 = 120;
642
643            let (query_server_info_tx, query_server_info_rx) =
644                tokio::sync::watch::channel(ServerInfo {
645                    git_hash: *common::util::GIT_HASH,
646                    git_timestamp: *common::util::GIT_TIMESTAMP,
647                    players_count: 0,
648                    player_cap: settings.max_players,
649                    battlemode: settings.gameplay.battle_mode.into(),
650                });
651            let mut query_server =
652                QueryServer::new(addr, query_server_info_rx, QUERY_SERVER_RATELIMIT);
653            let query_server_metrics =
654                Arc::new(Mutex::new(veloren_query_server::server::Metrics::default()));
655            let query_server_metrics2 = Arc::clone(&query_server_metrics);
656            runtime.spawn(async move {
657                let err = query_server.run(query_server_metrics2).await.err();
658                error!(?err, "Query server stopped unexpectedly");
659            });
660            state.ecs_mut().insert(query_server_info_tx);
661            state.ecs_mut().insert(query_server_metrics);
662        }
663
664        runtime.block_on(network.listen(ListenAddr::Mpsc(14004)))?;
665
666        let connection_handler = ConnectionHandler::new(network, &runtime);
667
668        // Init rtsim, loading it from disk if possible
669        #[cfg(feature = "worldgen")]
670        {
671            match rtsim::RtSim::new(
672                &settings.world,
673                index.as_index_ref(),
674                &world,
675                data_dir.to_owned(),
676            ) {
677                Ok(rtsim) => {
678                    state.ecs_mut().insert(rtsim.state().data().time_of_day);
679                    state.ecs_mut().insert(rtsim);
680                },
681                Err(err) => {
682                    error!("Failed to load rtsim: {}", err);
683                    return Err(Error::RtsimError(err));
684                },
685            }
686            weather::init(&mut state);
687        }
688
689        let this = Self {
690            state,
691            world,
692            index,
693            connection_handler,
694            runtime,
695
696            metrics_registry: registry,
697            chat_cache,
698            database_settings,
699            disconnect_all_clients_requested: false,
700
701            event_dispatcher: Self::create_event_dispatcher(pools),
702        };
703
704        debug!(?settings, "created veloren server with");
705
706        info!("Server version: {}", *common::util::DISPLAY_VERSION);
707
708        Ok(this)
709    }
710
711    pub fn get_server_info(&self) -> ServerInfo {
712        let settings = self.state.ecs().fetch::<Settings>();
713
714        ServerInfo {
715            name: settings.server_name.clone(),
716            git_hash: *common::util::GIT_HASH,
717            git_timestamp: *common::util::GIT_TIMESTAMP,
718            auth_provider: settings.auth_server_address.clone(),
719        }
720    }
721
722    /// Get a reference to the server's settings
723    pub fn settings(&self) -> impl Deref<Target = Settings> + '_ {
724        self.state.ecs().fetch::<Settings>()
725    }
726
727    /// Get a mutable reference to the server's settings
728    pub fn settings_mut(&self) -> impl DerefMut<Target = Settings> + '_ {
729        self.state.ecs().fetch_mut::<Settings>()
730    }
731
732    /// Get a mutable reference to the server's editable settings
733    pub fn editable_settings_mut(&self) -> impl DerefMut<Target = EditableSettings> + '_ {
734        self.state.ecs().fetch_mut::<EditableSettings>()
735    }
736
737    /// Get a reference to the server's editable settings
738    pub fn editable_settings(&self) -> impl Deref<Target = EditableSettings> + '_ {
739        self.state.ecs().fetch::<EditableSettings>()
740    }
741
742    /// Get path to the directory that the server info into
743    pub fn data_dir(&self) -> impl Deref<Target = DataDir> + '_ {
744        self.state.ecs().fetch::<DataDir>()
745    }
746
747    /// Get a reference to the server's game state.
748    pub fn state(&self) -> &State { &self.state }
749
750    /// Get a mutable reference to the server's game state.
751    pub fn state_mut(&mut self) -> &mut State { &mut self.state }
752
753    /// Get a reference to the server's world.
754    pub fn world(&self) -> &World { &self.world }
755
756    /// Get a reference to the Metrics Registry
757    pub fn metrics_registry(&self) -> &Arc<Registry> { &self.metrics_registry }
758
759    /// Get a reference to the Chat Cache
760    pub fn chat_cache(&self) -> &ChatCache { &self.chat_cache }
761
762    fn parse_locations(&self, character_list_data: &mut [CharacterItem]) {
763        character_list_data.iter_mut().for_each(|c| {
764            let name = c
765                .location
766                .as_ref()
767                .and_then(|s| {
768                    persistence::parse_waypoint(s)
769                        .ok()
770                        .and_then(|(waypoint, _)| waypoint.map(|w| w.get_pos()))
771                })
772                .and_then(|wpos| {
773                    self.world
774                        .get_location_name(self.index.as_index_ref(), wpos.xy().as_::<i32>())
775                });
776            c.location = name;
777        });
778    }
779
780    /// Execute a single server tick, handle input and update the game state by
781    /// the given duration.
782    pub fn tick(&mut self, _input: Input, dt: Duration) -> Result<Vec<Event>, Error> {
783        self.state.ecs().write_resource::<Tick>().0 += 1;
784        self.state.ecs().write_resource::<TickStart>().0 = Instant::now();
785
786        // Update calendar events as time changes
787        // TODO: If a lot of calendar events get added, this might become expensive.
788        // Maybe don't do this every tick?
789        let new_calendar = self
790            .state
791            .ecs()
792            .read_resource::<Settings>()
793            .calendar_mode
794            .calendar_now();
795        *self.state.ecs_mut().write_resource::<Calendar>() = new_calendar;
796
797        #[cfg(feature = "hot-site")]
798        if let Ok(lib) = world::LIB.lock()
799            && let Some(lib) = &*lib
800        {
801            static LAST_COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
802            let last_count = LAST_COUNT.load(std::sync::atomic::Ordering::Relaxed);
803
804            let new_count = lib.reload_count();
805
806            if new_count > last_count {
807                LAST_COUNT.store(new_count, std::sync::atomic::Ordering::Relaxed);
808
809                let count = cmd::reload_chunks_inner(self, Vec3::zero(), None, true);
810
811                tracing::info!("Reloaded {count} chunks");
812            }
813        }
814
815        // This tick function is the centre of the Veloren universe. Most server-side
816        // things are managed from here, and as such it's important that it
817        // stays organised. Please consult the core developers before making
818        // significant changes to this code. Here is the approximate order of
819        // things. Please update it as this code changes.
820        //
821        // 1) Collect input from the frontend, apply input effects to the state of the
822        //    game
823        // 2) Go through any events (timer-driven or otherwise) that need handling and
824        //    apply them to the state of the game
825        // 3) Go through all incoming client network communications, apply them to the
826        //    game state
827        // 4) Perform a single LocalState tick (i.e: update the world and entities in
828        //    the world)
829        // 5) Go through the terrain update queue and apply all changes to the terrain
830        // 6) Send relevant state updates to all clients
831        // 7) Check for persistence updates related to character data, and message the
832        //    relevant entities
833        // 8) Update Metrics with current data
834        // 9) Finish the tick, passing control of the main thread back to the frontend
835
836        // 1) Build up a list of events for this frame, to be passed to the frontend.
837        let mut frontend_events = Vec::new();
838
839        // 2)
840
841        let before_new_connections = Instant::now();
842
843        // 3) Handle inputs from clients
844        self.handle_new_connections(&mut frontend_events);
845
846        let before_state_tick = Instant::now();
847
848        fn on_block_update(ecs: &specs::World, changes: Vec<BlockDiff>) {
849            // When a resource block updates, inform rtsim
850            if changes
851                .iter()
852                .any(|c| c.old.get_rtsim_resource() != c.new.get_rtsim_resource())
853            {
854                ecs.write_resource::<rtsim::RtSim>().hook_block_update(
855                    &ecs.read_resource::<Arc<world::World>>(),
856                    ecs.read_resource::<world::IndexOwned>().as_index_ref(),
857                    changes,
858                );
859            }
860        }
861
862        // 4) Tick the server's LocalState.
863        // 5) Fetch any generated `TerrainChunk`s and insert them into the terrain.
864        // in sys/terrain.rs
865        let mut state_tick_metrics = Default::default();
866        let server_constants = (*self.state.ecs().read_resource::<ServerConstants>()).clone();
867        self.state.tick(
868            dt,
869            false,
870            Some(&mut state_tick_metrics),
871            &server_constants,
872            on_block_update,
873        );
874
875        let before_handle_events = Instant::now();
876
877        // Process any pending request to disconnect all clients, the disconnections
878        // will be processed once handle_events() is called below
879        let disconnect_type = self.disconnect_all_clients_if_requested();
880
881        // Handle entity links (such as mounting)
882        self.state.maintain_links();
883
884        // Handle game events
885        frontend_events.append(&mut self.handle_events());
886
887        let before_update_terrain_and_regions = Instant::now();
888
889        // Apply terrain changes and update the region map after processing server
890        // events so that changes made by server events will be immediately
891        // visible to client synchronization systems, minimizing the latency of
892        // `ServerEvent` mediated effects
893        self.update_region_map();
894        // NOTE: apply_terrain_changes sends the *new* value since it is not being
895        // synchronized during the tick.
896        self.state.apply_terrain_changes(on_block_update);
897
898        let before_sync = Instant::now();
899
900        // 6) Synchronise clients with the new state of the world.
901        sys::run_sync_systems(self.state.ecs_mut());
902
903        let before_world_tick = Instant::now();
904
905        // Tick the world
906        self.world.tick(dt);
907
908        let before_entity_cleanup = Instant::now();
909
910        // In the event of a request to disconnect all players without persistence, we
911        // must run the terrain system a second time after the messages to
912        // perform client disconnections have been processed. This ensures that any
913        // items on the ground are deleted.
914        if let Some(DisconnectType::WithoutPersistence) = disconnect_type {
915            run_now::<terrain::Sys>(self.state.ecs_mut());
916        }
917
918        // Hook rtsim chunk unloads
919        #[cfg(feature = "worldgen")]
920        {
921            let mut rtsim = self.state.ecs().write_resource::<rtsim::RtSim>();
922            let world = self.state.ecs().read_resource::<Arc<World>>();
923            for chunk in &self.state.terrain_changes().removed_chunks {
924                rtsim.hook_unload_chunk(*chunk, &world);
925            }
926        }
927
928        // Prevent anchor entity chains which are not currently supported due to:
929        // * potential cycles?
930        // * unloading a chain could occur across an unbounded number of ticks with the
931        //   current implementation.
932        // * in particular, we want to be able to unload all entities in a
933        //   limited number of ticks when a database error occurs and kicks all
934        //   players (not quiet sure on exact time frame, since it already
935        //   takes a tick after unloading all chunks for entities to despawn?),
936        //   see this thread and the discussion linked from there:
937        //   https://gitlab.com/veloren/veloren/-/merge_requests/2668#note_634913847
938        let anchors = self.state.ecs().read_storage::<Anchor>();
939        let anchored_anchor_entities: Vec<Entity> = (
940            &self.state.ecs().entities(),
941            &self.state.ecs().read_storage::<Anchor>(),
942        )
943            .join()
944            .filter_map(|(_, anchor)| match anchor {
945                Anchor::Entity(anchor_entity) => Some(*anchor_entity),
946                _ => None,
947            })
948            // We allow Anchor::Entity(_) -> Anchor::Chunk(_) connections, since they can't chain further.
949            //
950            // NOTE: The entity with `Anchor::Entity` will unload one tick after the entity with `Anchor::Chunk`.
951            .filter(|anchor_entity| match anchors.get(*anchor_entity) {
952                Some(Anchor::Entity(_)) => true,
953                Some(Anchor::Chunk(_)) | None => false
954            })
955            .collect();
956        drop(anchors);
957
958        for entity in anchored_anchor_entities {
959            if cfg!(debug_assertions) {
960                panic!("Entity anchor chain detected");
961            }
962            error!(
963                "Detected an anchor entity that itself has an anchor entity - anchor chains are \
964                 not currently supported. The entity's Anchor component has been deleted"
965            );
966            self.state.delete_component::<Anchor>(entity);
967        }
968
969        // Remove NPCs that are outside the view distances of all players
970        // This is done by removing NPCs in unloaded chunks
971        let to_delete = {
972            let terrain = self.state.terrain();
973            (
974                &self.state.ecs().entities(),
975                &self.state.ecs().read_storage::<comp::Pos>(),
976                !&self.state.ecs().read_storage::<comp::Presence>(),
977                self.state.ecs().read_storage::<Anchor>().maybe(),
978                self.state.ecs().read_storage::<Is<VolumeRider>>().maybe(),
979            )
980                .join()
981                .filter(|(_, pos, _, anchor, is_volume_rider)| {
982                    let pos = is_volume_rider
983                        .and_then(|is_volume_rider| match is_volume_rider.pos.kind {
984                            Volume::Terrain => None,
985                            Volume::Entity(e) => {
986                                let e = self.state.ecs().entity_from_uid(e)?;
987                                let pos = self
988                                    .state
989                                    .ecs()
990                                    .read_storage::<comp::Pos>()
991                                    .get(e)
992                                    .copied()?;
993
994                                Some(pos.0)
995                            },
996                        })
997                        .unwrap_or(pos.0);
998                    let chunk_key = terrain.pos_key(pos.map(|e| e.floor() as i32));
999                    match anchor {
1000                        Some(Anchor::Chunk(hc)) => {
1001                            // Check if both this chunk and the NPCs `home_chunk` is unloaded. If
1002                            // so, we delete them. We check for
1003                            // `home_chunk` in order to avoid duplicating
1004                            // the entity under some circumstances.
1005                            terrain.get_key_real(chunk_key).is_none()
1006                                && terrain.get_key_real(*hc).is_none()
1007                        },
1008                        Some(Anchor::Entity(entity)) => !self.state.ecs().is_alive(*entity),
1009                        None => terrain.get_key_real(chunk_key).is_none(),
1010                    }
1011                })
1012                .map(|(entity, _, _, _, _)| entity)
1013                .collect::<Vec<_>>()
1014        };
1015
1016        #[cfg(feature = "worldgen")]
1017        {
1018            let mut rtsim = self.state.ecs().write_resource::<rtsim::RtSim>();
1019            let rtsim_actors = self.state.ecs().read_storage();
1020            for entity in &to_delete {
1021                if let Some(actor) = rtsim_actors.get(*entity) {
1022                    rtsim.hook_rtsim_entity_unload(*actor);
1023                }
1024            }
1025        }
1026
1027        // Actually perform entity deletion
1028        for entity in to_delete {
1029            if let Err(e) = self.state.delete_entity_recorded(entity) {
1030                error!(?e, "Failed to delete agent outside the terrain");
1031            }
1032        }
1033
1034        if let Some(DisconnectType::WithoutPersistence) = disconnect_type {
1035            info!(
1036                "Disconnection of all players without persistence complete, signalling to \
1037                 persistence thread that character updates may continue to be processed"
1038            );
1039            self.state
1040                .ecs()
1041                .fetch_mut::<CharacterUpdater>()
1042                .disconnected_success();
1043        }
1044
1045        // 7 Persistence updates
1046        let before_persistence_updates = Instant::now();
1047
1048        let character_loader = self.state.ecs().read_resource::<CharacterLoader>();
1049
1050        let mut character_updater = self.state.ecs().write_resource::<CharacterUpdater>();
1051        let updater_messages: Vec<CharacterUpdaterMessage> = character_updater.messages().collect();
1052
1053        // Get character-related database responses and notify the requesting client
1054        character_loader
1055            .messages()
1056            .chain(updater_messages)
1057            .for_each(|message| match message {
1058                CharacterUpdaterMessage::DatabaseBatchCompletion(batch_id) => {
1059                    character_updater.process_batch_completion(batch_id);
1060                },
1061                CharacterUpdaterMessage::CharacterScreenResponse(response) => {
1062                    match response.response_kind {
1063                        CharacterScreenResponseKind::CharacterList(result) => match result {
1064                            Ok(mut character_list_data) => {
1065                                self.parse_locations(&mut character_list_data);
1066                                self.notify_client(
1067                                    response.target_entity,
1068                                    ServerGeneral::CharacterListUpdate(character_list_data),
1069                                )
1070                            },
1071                            Err(error) => self.notify_client(
1072                                response.target_entity,
1073                                ServerGeneral::CharacterActionError(error.to_string()),
1074                            ),
1075                        },
1076                        CharacterScreenResponseKind::CharacterCreation(result) => match result {
1077                            Ok((character_id, mut list)) => {
1078                                self.parse_locations(&mut list);
1079                                self.notify_client(
1080                                    response.target_entity,
1081                                    ServerGeneral::CharacterListUpdate(list),
1082                                );
1083                                self.notify_client(
1084                                    response.target_entity,
1085                                    ServerGeneral::CharacterCreated(character_id),
1086                                );
1087                            },
1088                            Err(error) => self.notify_client(
1089                                response.target_entity,
1090                                ServerGeneral::CharacterActionError(error.to_string()),
1091                            ),
1092                        },
1093                        CharacterScreenResponseKind::CharacterEdit(result) => match result {
1094                            Ok((character_id, mut list)) => {
1095                                self.parse_locations(&mut list);
1096                                self.notify_client(
1097                                    response.target_entity,
1098                                    ServerGeneral::CharacterListUpdate(list),
1099                                );
1100                                self.notify_client(
1101                                    response.target_entity,
1102                                    ServerGeneral::CharacterEdited(character_id),
1103                                );
1104                            },
1105                            Err(error) => self.notify_client(
1106                                response.target_entity,
1107                                ServerGeneral::CharacterActionError(error.to_string()),
1108                            ),
1109                        },
1110                        CharacterScreenResponseKind::CharacterData(result) => {
1111                            match *result {
1112                                Ok((character_data, skill_set_persistence_load_error)) => {
1113                                    let PersistedComponents {
1114                                        body,
1115                                        hardcore,
1116                                        stats,
1117                                        skill_set,
1118                                        inventory,
1119                                        waypoint,
1120                                        pets,
1121                                        active_abilities,
1122                                        map_marker,
1123                                    } = character_data;
1124                                    let character_data = (
1125                                        body,
1126                                        hardcore,
1127                                        stats,
1128                                        skill_set,
1129                                        inventory,
1130                                        waypoint,
1131                                        pets,
1132                                        active_abilities,
1133                                        map_marker,
1134                                    );
1135                                    // TODO: Does this need to be a server event? E.g. we could
1136                                    // just handle it here.
1137                                    self.state.emit_event_now(UpdateCharacterDataEvent {
1138                                        entity: response.target_entity,
1139                                        components: character_data,
1140                                        metadata: skill_set_persistence_load_error,
1141                                    })
1142                                },
1143                                Err(error) => {
1144                                    // We failed to load data for the character from the DB. Notify
1145                                    // the client to push the state back to character selection,
1146                                    // with the error to display
1147                                    self.notify_client(
1148                                        response.target_entity,
1149                                        ServerGeneral::CharacterDataLoadResult(Err(
1150                                            error.to_string()
1151                                        )),
1152                                    );
1153
1154                                    // Clean up the entity data on the server
1155                                    self.state.emit_event_now(ExitIngameEvent {
1156                                        entity: response.target_entity,
1157                                    })
1158                                },
1159                            }
1160                        },
1161                    }
1162                },
1163            });
1164
1165        drop(character_loader);
1166        drop(character_updater);
1167
1168        {
1169            // Check for new chunks; cancel and regenerate all chunks if the asset has been
1170            // reloaded. Note that all of these assignments are no-ops, so the
1171            // only work we do here on the fast path is perform a relaxed read on an atomic.
1172            // boolean.
1173            let index = &mut self.index;
1174            let world = &mut self.world;
1175            let ecs = self.state.ecs_mut();
1176            let slow_jobs = ecs.write_resource::<SlowJobPool>();
1177
1178            index.reload_if_changed(|index| {
1179                let mut chunk_generator = ecs.write_resource::<ChunkGenerator>();
1180                let client = ecs.read_storage::<Client>();
1181                let mut terrain = ecs.write_resource::<common::terrain::TerrainGrid>();
1182                #[cfg(feature = "worldgen")]
1183                let rtsim = ecs.read_resource::<rtsim::RtSim>();
1184                #[cfg(not(feature = "worldgen"))]
1185                let rtsim = ();
1186
1187                // Cancel all pending chunks.
1188                chunk_generator.cancel_all();
1189
1190                if client.is_empty() {
1191                    // No clients, so just clear all terrain.
1192                    terrain.clear();
1193                } else {
1194                    // There's at least one client, so regenerate all chunks.
1195                    terrain.iter().for_each(|(pos, _)| {
1196                        chunk_generator.generate_chunk(
1197                            None,
1198                            pos,
1199                            &slow_jobs,
1200                            Arc::clone(world),
1201                            &rtsim,
1202                            index.clone(),
1203                            (
1204                                *ecs.read_resource::<TimeOfDay>(),
1205                                (*ecs.read_resource::<Calendar>()).clone(),
1206                            ),
1207                        );
1208                    });
1209                }
1210            });
1211        }
1212
1213        let end_of_server_tick = Instant::now();
1214
1215        // 8) Update Metrics
1216        run_now::<sys::metrics::Sys>(self.state.ecs());
1217
1218        {
1219            // Report timing info
1220            let tick_metrics = self.state.ecs().read_resource::<TickMetrics>();
1221
1222            let tt = &tick_metrics.tick_time;
1223            tt.with_label_values(&["new connections"])
1224                .set((before_state_tick - before_new_connections).as_nanos() as i64);
1225            tt.with_label_values(&["handle server events"])
1226                .set((before_update_terrain_and_regions - before_handle_events).as_nanos() as i64);
1227            tt.with_label_values(&["update terrain and region map"])
1228                .set((before_sync - before_update_terrain_and_regions).as_nanos() as i64);
1229            tt.with_label_values(&["state"])
1230                .set((before_handle_events - before_state_tick).as_nanos() as i64);
1231            tt.with_label_values(&["world tick"])
1232                .set((before_entity_cleanup - before_world_tick).as_nanos() as i64);
1233            tt.with_label_values(&["entity cleanup"])
1234                .set((before_persistence_updates - before_entity_cleanup).as_nanos() as i64);
1235            tt.with_label_values(&["persistence_updates"])
1236                .set((end_of_server_tick - before_persistence_updates).as_nanos() as i64);
1237            for (label, duration) in state_tick_metrics.timings {
1238                tick_metrics
1239                    .state_tick_time
1240                    .with_label_values(&[label])
1241                    .set(duration.as_nanos() as i64);
1242            }
1243            tick_metrics.tick_time_hist.observe(
1244                end_of_server_tick
1245                    .duration_since(before_state_tick)
1246                    .as_secs_f64(),
1247            );
1248        }
1249
1250        // 9) Finish the tick, pass control back to the frontend.
1251
1252        Ok(frontend_events)
1253    }
1254
1255    /// Clean up the server after a tick.
1256    pub fn cleanup(&mut self) {
1257        // Cleanup the local state
1258        self.state.cleanup();
1259
1260        // Maintain persisted terrain
1261        #[cfg(feature = "persistent_world")]
1262        self.state
1263            .ecs()
1264            .try_fetch_mut::<TerrainPersistence>()
1265            .map(|mut t| t.maintain());
1266    }
1267
1268    // Run RegionMap tick to update entity region occupancy
1269    fn update_region_map(&mut self) {
1270        prof_span!("Server::update_region_map");
1271        let ecs = self.state().ecs();
1272        ecs.write_resource::<RegionMap>().tick(
1273            ecs.read_storage::<comp::Pos>(),
1274            ecs.read_storage::<comp::Vel>(),
1275            ecs.read_storage::<comp::Presence>(),
1276            ecs.entities(),
1277        );
1278    }
1279
1280    fn initialize_client(&mut self, client: connection_handler::IncomingClient) -> Entity {
1281        let entity = self
1282            .state
1283            .ecs_mut()
1284            .create_entity_synced()
1285            .with(client)
1286            .build();
1287        self.state
1288            .ecs()
1289            .read_resource::<metrics::PlayerMetrics>()
1290            .clients_connected
1291            .inc();
1292        entity
1293    }
1294
1295    /// Disconnects all clients if requested by either an admin command or
1296    /// due to a persistence transaction failure and returns the processed
1297    /// DisconnectionType
1298    fn disconnect_all_clients_if_requested(&mut self) -> Option<DisconnectType> {
1299        let mut character_updater = self.state.ecs().fetch_mut::<CharacterUpdater>();
1300
1301        let disconnect_type = self.get_disconnect_all_clients_requested(&mut character_updater);
1302        if let Some(disconnect_type) = disconnect_type {
1303            let with_persistence = disconnect_type == DisconnectType::WithPersistence;
1304            let clients = self.state.ecs().read_storage::<Client>();
1305            let entities = self.state.ecs().entities();
1306
1307            info!(
1308                "Disconnecting all clients ({} persistence) as requested",
1309                if with_persistence { "with" } else { "without" }
1310            );
1311            for (_, entity) in (&clients, &entities).join() {
1312                info!("Emitting client disconnect event for entity: {:?}", entity);
1313                if with_persistence {
1314                    self.state.emit_event_now(ClientDisconnectEvent(
1315                        entity,
1316                        comp::DisconnectReason::Kicked,
1317                    ))
1318                } else {
1319                    self.state
1320                        .emit_event_now(ClientDisconnectWithoutPersistenceEvent(entity))
1321                };
1322            }
1323
1324            self.disconnect_all_clients_requested = false;
1325        }
1326
1327        disconnect_type
1328    }
1329
1330    fn get_disconnect_all_clients_requested(
1331        &self,
1332        character_updater: &mut CharacterUpdater,
1333    ) -> Option<DisconnectType> {
1334        let without_persistence_requested = character_updater.disconnect_all_clients_requested();
1335        let with_persistence_requested = self.disconnect_all_clients_requested;
1336
1337        if without_persistence_requested {
1338            return Some(DisconnectType::WithoutPersistence);
1339        };
1340        if with_persistence_requested {
1341            return Some(DisconnectType::WithPersistence);
1342        };
1343        None
1344    }
1345
1346    /// Handle new client connections.
1347    fn handle_new_connections(&mut self, frontend_events: &mut Vec<Event>) {
1348        while let Ok(sender) = self.connection_handler.info_requester_receiver.try_recv() {
1349            // can fail, e.g. due to timeout or network prob.
1350            trace!("sending info to connection_handler");
1351            let _ = sender.send(connection_handler::ServerInfoPacket {
1352                info: self.get_server_info(),
1353                time: self.state.get_time(),
1354            });
1355        }
1356
1357        while let Ok(incoming) = self.connection_handler.client_receiver.try_recv() {
1358            let entity = self.initialize_client(incoming);
1359            frontend_events.push(Event::ClientConnected { entity });
1360        }
1361    }
1362
1363    pub fn notify_client<S>(&self, entity: EcsEntity, msg: S)
1364    where
1365        S: Into<ServerMsg>,
1366    {
1367        if let Some(client) = self.state.ecs().read_storage::<Client>().get(entity) {
1368            client.send_fallible(msg);
1369        }
1370    }
1371
1372    pub fn notify_players(&mut self, msg: ServerGeneral) { self.state.notify_players(msg); }
1373
1374    fn process_command(&mut self, entity: EcsEntity, name: String, args: Vec<String>) {
1375        // Find the command object and run its handler.
1376        if let Ok(command) = name.parse::<ServerChatCommand>() {
1377            command.execute(self, entity, args);
1378        } else {
1379            #[cfg(feature = "plugins")]
1380            {
1381                let mut plugin_manager = self.state.ecs().write_resource::<PluginMgr>();
1382                let ecs_world = EcsWorld {
1383                    entities: &self.state.ecs().entities(),
1384                    health: self.state.ecs().read_component().into(),
1385                    uid: self.state.ecs().read_component().into(),
1386                    id_maps: &self.state.ecs().read_resource::<IdMaps>().into(),
1387                    player: self.state.ecs().read_component().into(),
1388                };
1389                let uid = if let Some(uid) = ecs_world.uid.get(entity).copied() {
1390                    uid
1391                } else {
1392                    self.notify_client(
1393                        entity,
1394                        ServerGeneral::server_msg(
1395                            comp::ChatType::CommandError,
1396                            common::comp::Content::Plain(
1397                                "Can't get player UUID (player may be disconnected?)".to_string(),
1398                            ),
1399                        ),
1400                    );
1401                    return;
1402                };
1403                match plugin_manager.command_event(&ecs_world, &name, args.as_slice(), uid) {
1404                    Err(common_state::plugin::CommandResults::UnknownCommand) => self
1405                        .notify_client(
1406                            entity,
1407                            ServerGeneral::server_msg(
1408                                comp::ChatType::CommandError,
1409                                common::comp::Content::Plain(format!(
1410                                    "Unknown command '/{name}'.\nType '/help' for available \
1411                                     commands",
1412                                )),
1413                            ),
1414                        ),
1415                    Ok(value) => {
1416                        self.notify_client(
1417                            entity,
1418                            ServerGeneral::server_msg(
1419                                comp::ChatType::CommandInfo,
1420                                common::comp::Content::Plain(value.join("\n")),
1421                            ),
1422                        );
1423                    },
1424                    Err(common_state::plugin::CommandResults::PluginError(err)) => {
1425                        self.notify_client(
1426                            entity,
1427                            ServerGeneral::server_msg(
1428                                comp::ChatType::CommandError,
1429                                common::comp::Content::Plain(format!(
1430                                    "Error occurred while executing command '/{name}'.\n{err}"
1431                                )),
1432                            ),
1433                        );
1434                    },
1435                    Err(common_state::plugin::CommandResults::HostError(err)) => {
1436                        error!(?err, ?name, ?args, "Can't execute command");
1437                        self.notify_client(
1438                            entity,
1439                            ServerGeneral::server_msg(
1440                                comp::ChatType::CommandError,
1441                                common::comp::Content::Plain(format!(
1442                                    "Internal error {err:?} while executing '/{name}'.\nContact \
1443                                     the server administrator",
1444                                )),
1445                            ),
1446                        );
1447                    },
1448                }
1449            }
1450        }
1451    }
1452
1453    fn entity_admin_role(&self, entity: EcsEntity) -> Option<comp::AdminRole> {
1454        self.state
1455            .read_component_copied::<comp::Admin>(entity)
1456            .map(|admin| admin.0)
1457    }
1458
1459    pub fn number_of_players(&self) -> i64 {
1460        self.state.ecs().read_storage::<Client>().join().count() as i64
1461    }
1462
1463    /// NOTE: Do *not* allow this to be called from any command that doesn't go
1464    /// through the CLI!
1465    pub fn add_admin(&mut self, username: &str, role: comp::AdminRole) {
1466        let mut editable_settings = self.editable_settings_mut();
1467        let login_provider = self.state.ecs().fetch::<LoginProvider>();
1468        let data_dir = self.data_dir();
1469        if let Some(entity) = add_admin(
1470            username,
1471            role,
1472            &login_provider,
1473            &mut editable_settings,
1474            &data_dir.path,
1475        )
1476        .and_then(|uuid| {
1477            let state = &self.state;
1478            (
1479                &state.ecs().entities(),
1480                &state.read_storage::<comp::Player>(),
1481            )
1482                .join()
1483                .find(|(_, player)| player.uuid() == uuid)
1484                .map(|(e, _)| e)
1485        }) {
1486            drop((data_dir, login_provider, editable_settings));
1487            // Add admin component if the player is ingame; if they are not, we can ignore
1488            // the write failure.
1489            self.state
1490                .write_component_ignore_entity_dead(entity, comp::Admin(role));
1491        };
1492    }
1493
1494    /// NOTE: Do *not* allow this to be called from any command that doesn't go
1495    /// through the CLI!
1496    pub fn remove_admin(&self, username: &str) {
1497        let mut editable_settings = self.editable_settings_mut();
1498        let login_provider = self.state.ecs().fetch::<LoginProvider>();
1499        let data_dir = self.data_dir();
1500        if let Some(entity) = remove_admin(
1501            username,
1502            &login_provider,
1503            &mut editable_settings,
1504            &data_dir.path,
1505        )
1506        .and_then(|uuid| {
1507            let state = &self.state;
1508            (
1509                &state.ecs().entities(),
1510                &state.read_storage::<comp::Player>(),
1511            )
1512                .join()
1513                .find(|(_, player)| player.uuid() == uuid)
1514                .map(|(e, _)| e)
1515        }) {
1516            // Remove admin component if the player is ingame
1517            self.state
1518                .ecs()
1519                .write_storage::<comp::Admin>()
1520                .remove(entity);
1521        };
1522    }
1523
1524    /// Useful for testing without a client
1525    /// view_distance: distance in chunks that are persisted, this acts like the
1526    /// player view distance so it is actually a bit farther due to a buffer
1527    /// zone
1528    #[cfg(feature = "worldgen")]
1529    pub fn create_centered_persister(&mut self, view_distance: u32) {
1530        let world_dims_chunks = self.world.sim().get_size();
1531        let world_dims_blocks = TerrainChunkSize::blocks(world_dims_chunks);
1532        // NOTE: origin is in the corner of the map
1533        // TODO: extend this function to have picking a random position or specifying a
1534        // position as options
1535        //let mut rng = rand::rng();
1536        // // Pick a random position but not to close to the edge
1537        // let rand_pos = world_dims_blocks.map(|e| e as i32).map(|e| e / 2 +
1538        // rng.random_range(-e/2..e/2 + 1));
1539        let pos = comp::Pos(Vec3::from(world_dims_blocks.map(|e| e as f32 / 2.0)));
1540        self.state
1541            .create_persister(pos, view_distance, &self.world, &self.index)
1542            .build();
1543    }
1544
1545    /// Used by benchmarking code.
1546    pub fn chunks_pending(&mut self) -> bool {
1547        self.state_mut()
1548            .mut_resource::<ChunkGenerator>()
1549            .pending_chunks()
1550            .next()
1551            .is_some()
1552    }
1553
1554    /// Sets the SQL log mode at runtime
1555    pub fn set_sql_log_mode(&mut self, sql_log_mode: SqlLogMode) {
1556        // Unwrap is safe here because we only perform a variable assignment with the
1557        // RwLock taken meaning that no panic can occur that would cause the
1558        // RwLock to become poisoned. This justification also means that calling
1559        // unwrap() on the associated read() calls for this RwLock is also safe
1560        // as long as no code that can panic is introduced here.
1561        let mut database_settings = self.database_settings.write().unwrap();
1562        database_settings.sql_log_mode = sql_log_mode;
1563        // Drop the RwLockWriteGuard to avoid performing unnecessary actions (logging)
1564        // with the lock taken.
1565        drop(database_settings);
1566        info!("SQL log mode changed to {:?}", sql_log_mode);
1567    }
1568
1569    pub fn disconnect_all_clients(&mut self) {
1570        info!("Disconnecting all clients due to local console command");
1571        self.disconnect_all_clients_requested = true;
1572    }
1573
1574    /// Sends the given client a message with their current battle mode and
1575    /// whether they can change it.
1576    ///
1577    /// This function expects the `EcsEntity` to represent a player, otherwise
1578    /// it will log an error.
1579    pub fn get_battle_mode_for(&mut self, client: EcsEntity) {
1580        let ecs = self.state.ecs();
1581        let time = ecs.read_resource::<Time>();
1582        let settings = ecs.read_resource::<Settings>();
1583        let players = ecs.read_storage::<comp::Player>();
1584        let get_player_result = players.get(client).ok_or_else(|| {
1585            error!("Can't get player component for client.");
1586
1587            Content::Plain("Can't get player component for client.".to_string())
1588        });
1589        let player = match get_player_result {
1590            Ok(player) => player,
1591            Err(content) => {
1592                self.notify_client(
1593                    client,
1594                    ServerGeneral::server_msg(ChatType::CommandError, content),
1595                );
1596                return;
1597            },
1598        };
1599
1600        let mut msg = format!("Current battle mode: {:?}.", player.battle_mode);
1601
1602        if settings.gameplay.battle_mode.allow_choosing() {
1603            msg.push_str(" Possible to change.");
1604        } else {
1605            msg.push_str(" Global.");
1606        }
1607
1608        if let Some(change) = player.last_battlemode_change {
1609            let Time(time) = *time;
1610            let Time(change) = change;
1611            let elapsed = time - change;
1612            let next = BATTLE_MODE_COOLDOWN - elapsed;
1613
1614            if next > 0.0 {
1615                let notice = format!(" Next change will be available in: {:.0} seconds", next);
1616                msg.push_str(&notice);
1617            }
1618        }
1619
1620        self.notify_client(
1621            client,
1622            ServerGeneral::server_msg(ChatType::CommandInfo, Content::Plain(msg)),
1623        );
1624    }
1625
1626    /// Sets the battle mode for the given client or informs them if they are
1627    /// not allowed to change it.
1628    ///
1629    /// This function expects the `EcsEntity` to represent a player, otherwise
1630    /// it will log an error.
1631    pub fn set_battle_mode_for(&mut self, client: EcsEntity, battle_mode: BattleMode) {
1632        let ecs = self.state.ecs();
1633        let time = ecs.read_resource::<Time>();
1634        let settings = ecs.read_resource::<Settings>();
1635
1636        if !settings.gameplay.battle_mode.allow_choosing() {
1637            self.notify_client(
1638                client,
1639                ServerGeneral::server_msg(
1640                    ChatType::CommandInfo,
1641                    Content::localized("command-disabled-by-settings"),
1642                ),
1643            );
1644
1645            return;
1646        }
1647
1648        #[cfg(feature = "worldgen")]
1649        let in_town = {
1650            let pos = if let Some(pos) = self
1651                .state
1652                .ecs()
1653                .read_storage::<comp::Pos>()
1654                .get(client)
1655                .copied()
1656            {
1657                pos
1658            } else {
1659                self.notify_client(
1660                    client,
1661                    ServerGeneral::server_msg(
1662                        ChatType::CommandInfo,
1663                        Content::localized_with_args("command-position-unavailable", [(
1664                            "target", "target",
1665                        )]),
1666                    ),
1667                );
1668
1669                return;
1670            };
1671
1672            let wpos = pos.0.xy().map(|x| x as i32);
1673            let chunk_pos = wpos.wpos_to_cpos();
1674            self.world.civs().sites().any(|site| {
1675                // empirical
1676                const RADIUS: f32 = 9.0;
1677                let delta = site
1678                    .center
1679                    .map(|x| x as f32)
1680                    .distance(chunk_pos.map(|x| x as f32));
1681                delta < RADIUS
1682            })
1683        };
1684
1685        #[cfg(not(feature = "worldgen"))]
1686        let in_town = true;
1687
1688        if !in_town {
1689            self.notify_client(
1690                client,
1691                ServerGeneral::server_msg(
1692                    ChatType::CommandInfo,
1693                    Content::localized("command-battlemode-intown"),
1694                ),
1695            );
1696
1697            return;
1698        }
1699
1700        let mut players = ecs.write_storage::<comp::Player>();
1701        let mut player = if let Some(info) = players.get_mut(client) {
1702            info
1703        } else {
1704            error!("Failed to get info for player.");
1705
1706            return;
1707        };
1708
1709        if let Some(Time(last_change)) = player.last_battlemode_change {
1710            let Time(time) = *time;
1711            let elapsed = time - last_change;
1712            if elapsed < BATTLE_MODE_COOLDOWN {
1713                let next = BATTLE_MODE_COOLDOWN - elapsed;
1714
1715                self.notify_client(
1716                    client,
1717                    ServerGeneral::server_msg(
1718                        ChatType::CommandInfo,
1719                        Content::Plain(format!(
1720                            "Next change will be available in {next:.0} seconds."
1721                        )),
1722                    ),
1723                );
1724
1725                return;
1726            }
1727        }
1728
1729        if player.battle_mode == battle_mode {
1730            self.notify_client(
1731                client,
1732                ServerGeneral::server_msg(
1733                    ChatType::CommandInfo,
1734                    Content::localized("command-battlemode-same"),
1735                ),
1736            );
1737
1738            return;
1739        }
1740
1741        player.battle_mode = battle_mode;
1742        player.last_battlemode_change = Some(*time);
1743
1744        self.notify_client(
1745            client,
1746            ServerGeneral::server_msg(
1747                ChatType::CommandInfo,
1748                Content::localized_with_args("command-battlemode-updated", [(
1749                    "battlemode",
1750                    format!("{battle_mode:?}"),
1751                )]),
1752            ),
1753        );
1754
1755        drop(players);
1756
1757        let uid = ecs.read_storage::<Uid>().get(client).copied().unwrap();
1758
1759        self.state().notify_players(ServerGeneral::PlayerListUpdate(
1760            PlayerListUpdate::UpdateBattleMode(uid, battle_mode),
1761        ));
1762    }
1763}
1764
1765impl Drop for Server {
1766    fn drop(&mut self) {
1767        self.state
1768            .notify_players(ServerGeneral::Disconnect(DisconnectReason::Shutdown));
1769
1770        #[cfg(feature = "persistent_world")]
1771        self.state
1772            .ecs()
1773            .try_fetch_mut::<TerrainPersistence>()
1774            .map(|mut terrain_persistence| {
1775                info!("Unloading terrain persistence...");
1776                terrain_persistence.unload_all()
1777            });
1778
1779        #[cfg(feature = "worldgen")]
1780        {
1781            debug!("Saving rtsim state...");
1782            self.state.ecs().write_resource::<rtsim::RtSim>().save(true);
1783        }
1784    }
1785}
1786
1787#[must_use]
1788pub fn handle_edit<T, S: settings::EditableSetting>(
1789    data: T,
1790    result: Option<(String, Result<(), settings::SettingError<S>>)>,
1791) -> Option<T> {
1792    use crate::settings::SettingError;
1793    let (info, result) = result?;
1794    match result {
1795        Ok(()) => {
1796            info!("{}", info);
1797            Some(data)
1798        },
1799        Err(SettingError::Io(err)) => {
1800            warn!(
1801                ?err,
1802                "Failed to write settings file to disk, but succeeded in memory (success message: \
1803                 {})",
1804                info,
1805            );
1806            Some(data)
1807        },
1808        Err(SettingError::Integrity(err)) => {
1809            error!(?err, "Encountered an error while validating the request",);
1810            None
1811        },
1812    }
1813}
1814
1815/// If successful returns the Some(uuid) of the added admin
1816///
1817/// NOTE: Do *not* allow this to be called from any command that doesn't go
1818/// through the CLI!
1819#[must_use]
1820pub fn add_admin(
1821    username: &str,
1822    role: comp::AdminRole,
1823    login_provider: &LoginProvider,
1824    editable_settings: &mut EditableSettings,
1825    data_dir: &std::path::Path,
1826) -> Option<common::uuid::Uuid> {
1827    use crate::settings::EditableSetting;
1828    let role_ = role.into();
1829    match login_provider.username_to_uuid(username) {
1830        Ok(uuid) => handle_edit(
1831            uuid,
1832            editable_settings.admins.edit(data_dir, |admins| {
1833                match admins.insert(uuid, settings::AdminRecord {
1834                    username_when_admined: Some(username.into()),
1835                    date: chrono::Utc::now(),
1836                    role: role_,
1837                }) {
1838                    None => Some(format!(
1839                        "Successfully added {} ({}) as {:?}!",
1840                        username, uuid, role
1841                    )),
1842                    Some(old_admin) if old_admin.role == role_ => {
1843                        info!("{} ({}) already has role: {:?}!", username, uuid, role);
1844                        None
1845                    },
1846                    Some(old_admin) => Some(format!(
1847                        "{} ({}) role changed from {:?} to {:?}!",
1848                        username, uuid, old_admin.role, role
1849                    )),
1850                }
1851            }),
1852        ),
1853        Err(err) => {
1854            error!(
1855                ?err,
1856                "Could not find uuid for this name; either the user does not exist or there was \
1857                 an error communicating with the auth server."
1858            );
1859            None
1860        },
1861    }
1862}
1863
1864/// If successful returns the Some(uuid) of the removed admin
1865///
1866/// NOTE: Do *not* allow this to be called from any command that doesn't go
1867/// through the CLI!
1868#[must_use]
1869pub fn remove_admin(
1870    username: &str,
1871    login_provider: &LoginProvider,
1872    editable_settings: &mut EditableSettings,
1873    data_dir: &std::path::Path,
1874) -> Option<common::uuid::Uuid> {
1875    use crate::settings::EditableSetting;
1876    match login_provider.username_to_uuid(username) {
1877        Ok(uuid) => handle_edit(
1878            uuid,
1879            editable_settings.admins.edit(data_dir, |admins| {
1880                if let Some(admin) = admins.remove(&uuid) {
1881                    Some(format!(
1882                        "Successfully removed {} ({}) with role {:?} from the admins list",
1883                        username, uuid, admin.role,
1884                    ))
1885                } else {
1886                    info!("{} ({}) is not an admin!", username, uuid);
1887                    None
1888                }
1889            }),
1890        ),
1891        Err(err) => {
1892            error!(
1893                ?err,
1894                "Could not find uuid for this name; either the user does not exist or there was \
1895                 an error communicating with the auth server."
1896            );
1897            None
1898        },
1899    }
1900}