forked from luanti-org/luanti
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.cpp
4184 lines (3455 loc) · 111 KB
/
server.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "server.h"
#include <iostream>
#include <queue>
#include <algorithm>
#include "network/connection.h"
#include "network/networkprotocol.h"
#include "network/serveropcodes.h"
#include "ban.h"
#include "environment.h"
#include "map.h"
#include "threading/mutex_auto_lock.h"
#include "constants.h"
#include "voxel.h"
#include "config.h"
#include "version.h"
#include "filesys.h"
#include "mapblock.h"
#include "server/serveractiveobject.h"
#include "settings.h"
#include "profiler.h"
#include "log.h"
#include "scripting_server.h"
#include "nodedef.h"
#include "itemdef.h"
#include "craftdef.h"
#include "emerge.h"
#include "mapgen/mapgen.h"
#include "mapgen/mg_biome.h"
#include "content_mapnode.h"
#include "content_nodemeta.h"
#include "content/mods.h"
#include "modchannels.h"
#include "serverlist.h"
#include "util/string.h"
#include "rollback.h"
#include "util/serialize.h"
#include "util/thread.h"
#include "defaultsettings.h"
#include "server/mods.h"
#include "util/base64.h"
#include "util/sha1.h"
#include "util/hex.h"
#include "database/database.h"
#include "chatmessage.h"
#include "chat_interface.h"
#include "remoteplayer.h"
#include "server/player_sao.h"
#include "server/serverinventorymgr.h"
#include "translation.h"
#include "database/database-sqlite3.h"
#if USE_POSTGRESQL
#include "database/database-postgresql.h"
#endif
#include "database/database-files.h"
#include "database/database-dummy.h"
#include "gameparams.h"
#include "particles.h"
#include "gettext.h"
class ClientNotFoundException : public BaseException
{
public:
ClientNotFoundException(const char *s):
BaseException(s)
{}
};
class ServerThread : public Thread
{
public:
ServerThread(Server *server):
Thread("Server"),
m_server(server)
{}
void *run();
private:
Server *m_server;
};
void *ServerThread::run()
{
BEGIN_DEBUG_EXCEPTION_HANDLER
/*
* The real business of the server happens on the ServerThread.
* How this works:
* AsyncRunStep() runs an actual server step as soon as enough time has
* passed (dedicated_server_loop keeps track of that).
* Receive() blocks at least(!) 30ms waiting for a packet (so this loop
* doesn't busy wait) and will process any remaining packets.
*/
try {
m_server->AsyncRunStep(true);
} catch (con::ConnectionBindFailed &e) {
m_server->setAsyncFatalError(e.what());
} catch (LuaError &e) {
m_server->setAsyncFatalError(e);
}
while (!stopRequested()) {
ScopeProfiler spm(g_profiler, "Server::RunStep() (max)", SPT_MAX);
try {
m_server->AsyncRunStep();
m_server->Receive();
} catch (con::PeerNotFoundException &e) {
infostream<<"Server: PeerNotFoundException"<<std::endl;
} catch (ClientNotFoundException &e) {
} catch (con::ConnectionBindFailed &e) {
m_server->setAsyncFatalError(e.what());
} catch (LuaError &e) {
m_server->setAsyncFatalError(e);
}
}
END_DEBUG_EXCEPTION_HANDLER
return nullptr;
}
v3f ServerPlayingSound::getPos(ServerEnvironment *env, bool *pos_exists) const
{
if (pos_exists)
*pos_exists = false;
switch (type ){
case SoundLocation::Local:
return v3f(0,0,0);
case SoundLocation::Position:
if (pos_exists)
*pos_exists = true;
return pos;
case SoundLocation::Object:
{
if (object == 0)
return v3f(0,0,0);
ServerActiveObject *sao = env->getActiveObject(object);
if (!sao)
return v3f(0,0,0);
if (pos_exists)
*pos_exists = true;
return sao->getBasePosition();
}
}
return v3f(0,0,0);
}
void Server::ShutdownState::reset()
{
m_timer = 0.0f;
message.clear();
should_reconnect = false;
is_requested = false;
}
void Server::ShutdownState::trigger(float delay, const std::string &msg, bool reconnect)
{
m_timer = delay;
message = msg;
should_reconnect = reconnect;
}
void Server::ShutdownState::tick(float dtime, Server *server)
{
if (m_timer <= 0.0f)
return;
// Timed shutdown
static const float shutdown_msg_times[] =
{
1, 2, 3, 4, 5, 10, 20, 40, 60, 120, 180, 300, 600, 1200, 1800, 3600
};
// Automated messages
if (m_timer < shutdown_msg_times[ARRLEN(shutdown_msg_times) - 1]) {
for (float t : shutdown_msg_times) {
// If shutdown timer matches an automessage, shot it
if (m_timer > t && m_timer - dtime < t) {
std::wstring periodicMsg = getShutdownTimerMessage();
infostream << wide_to_utf8(periodicMsg).c_str() << std::endl;
server->SendChatMessage(PEER_ID_INEXISTENT, periodicMsg);
break;
}
}
}
m_timer -= dtime;
if (m_timer < 0.0f) {
m_timer = 0.0f;
is_requested = true;
}
}
std::wstring Server::ShutdownState::getShutdownTimerMessage() const
{
std::wstringstream ws;
ws << L"*** Server shutting down in "
<< duration_to_string(myround(m_timer)).c_str() << ".";
return ws.str();
}
/*
Server
*/
Server::Server(
const std::string &path_world,
const SubgameSpec &gamespec,
bool simple_singleplayer_mode,
Address bind_addr,
bool dedicated,
ChatInterface *iface,
std::string *shutdown_errmsg
):
m_bind_addr(bind_addr),
m_path_world(path_world),
m_gamespec(gamespec),
m_simple_singleplayer_mode(simple_singleplayer_mode),
m_dedicated(dedicated),
m_async_fatal_error(""),
m_con(std::make_shared<con::Connection>(PROTOCOL_ID,
512,
CONNECTION_TIMEOUT,
m_bind_addr.isIPv6(),
this)),
m_itemdef(createItemDefManager()),
m_nodedef(createNodeDefManager()),
m_craftdef(createCraftDefManager()),
m_thread(new ServerThread(this)),
m_clients(m_con),
m_admin_chat(iface),
m_shutdown_errmsg(shutdown_errmsg),
m_modchannel_mgr(new ModChannelMgr())
{
if (m_path_world.empty())
throw ServerError("Supplied empty world path");
if (!gamespec.isValid())
throw ServerError("Supplied invalid gamespec");
#if USE_PROMETHEUS
if (!simple_singleplayer_mode)
m_metrics_backend = std::unique_ptr<MetricsBackend>(createPrometheusMetricsBackend());
else
#else
if (true)
#endif
m_metrics_backend = std::make_unique<MetricsBackend>();
m_uptime_counter = m_metrics_backend->addCounter("minetest_core_server_uptime", "Server uptime (in seconds)");
m_player_gauge = m_metrics_backend->addGauge("minetest_core_player_number", "Number of connected players");
m_timeofday_gauge = m_metrics_backend->addGauge(
"minetest_core_timeofday",
"Time of day value");
m_lag_gauge = m_metrics_backend->addGauge(
"minetest_core_latency",
"Latency value (in seconds)");
const std::string aom_types[] = {"reliable", "unreliable"};
for (u32 i = 0; i < ARRLEN(aom_types); i++) {
std::string help_str("Number of active object messages generated (");
help_str.append(aom_types[i]).append(")");
m_aom_buffer_counter[i] = m_metrics_backend->addCounter(
"minetest_core_aom_generated_count", help_str,
{{"type", aom_types[i]}});
}
m_packet_recv_counter = m_metrics_backend->addCounter(
"minetest_core_server_packet_recv",
"Processable packets received");
m_packet_recv_processed_counter = m_metrics_backend->addCounter(
"minetest_core_server_packet_recv_processed",
"Valid received packets processed");
m_map_edit_event_counter = m_metrics_backend->addCounter(
"minetest_core_map_edit_events",
"Number of map edit events");
m_lag_gauge->set(g_settings->getFloat("dedicated_server_step"));
}
Server::~Server()
{
// Send shutdown message
SendChatMessage(PEER_ID_INEXISTENT, ChatMessage(CHATMESSAGE_TYPE_ANNOUNCE,
L"*** Server shutting down"));
if (m_env) {
MutexAutoLock envlock(m_env_mutex);
infostream << "Server: Saving players" << std::endl;
m_env->saveLoadedPlayers();
infostream << "Server: Kicking players" << std::endl;
std::string kick_msg;
bool reconnect = false;
if (isShutdownRequested()) {
reconnect = m_shutdown_state.should_reconnect;
kick_msg = m_shutdown_state.message;
}
if (kick_msg.empty()) {
kick_msg = g_settings->get("kick_msg_shutdown");
}
m_env->saveLoadedPlayers(true);
m_env->kickAllPlayers(SERVER_ACCESSDENIED_SHUTDOWN,
kick_msg, reconnect);
}
actionstream << "Server: Shutting down" << std::endl;
// Do this before stopping the server in case mapgen callbacks need to access
// server-controlled resources (like ModStorages). Also do them before
// shutdown callbacks since they may modify state that is finalized in a
// callback.
if (m_emerge)
m_emerge->stopThreads();
if (m_env) {
MutexAutoLock envlock(m_env_mutex);
// Execute script shutdown hooks
infostream << "Executing shutdown hooks" << std::endl;
try {
m_script->on_shutdown();
} catch (ModError &e) {
addShutdownError(e);
}
infostream << "Server: Saving environment metadata" << std::endl;
m_env->saveMeta();
}
// Stop threads
if (m_thread) {
stop();
delete m_thread;
}
// Write any changes before deletion.
if (m_mod_storage_database)
m_mod_storage_database->endSave();
// Delete things in the reverse order of creation
delete m_emerge;
delete m_env;
delete m_rollback;
delete m_mod_storage_database;
delete m_banmanager;
delete m_itemdef;
delete m_nodedef;
delete m_craftdef;
// Deinitialize scripting
infostream << "Server: Deinitializing scripting" << std::endl;
delete m_script;
delete m_startup_server_map; // if available
delete m_game_settings;
while (!m_unsent_map_edit_queue.empty()) {
delete m_unsent_map_edit_queue.front();
m_unsent_map_edit_queue.pop();
}
}
void Server::init()
{
infostream << "Server created for gameid \"" << m_gamespec.id << "\"";
if (m_simple_singleplayer_mode)
infostream << " in simple singleplayer mode" << std::endl;
else
infostream << std::endl;
infostream << "- world: " << m_path_world << std::endl;
infostream << "- game: " << m_gamespec.path << std::endl;
m_game_settings = Settings::createLayer(SL_GAME);
// Create world if it doesn't exist
try {
loadGameConfAndInitWorld(m_path_world,
fs::GetFilenameFromPath(m_path_world.c_str()),
m_gamespec, false);
} catch (const BaseException &e) {
throw ServerError(std::string("Failed to initialize world: ") + e.what());
}
// Create emerge manager
m_emerge = new EmergeManager(this, m_metrics_backend.get());
// Create ban manager
std::string ban_path = m_path_world + DIR_DELIM "ipban.txt";
m_banmanager = new BanManager(ban_path);
// Create mod storage database and begin a save for later
m_mod_storage_database = openModStorageDatabase(m_path_world);
m_mod_storage_database->beginSave();
m_modmgr = std::make_unique<ServerModManager>(m_path_world);
// complain about mods with unsatisfied dependencies
if (!m_modmgr->isConsistent()) {
std::string error = m_modmgr->getUnsatisfiedModsError();
throw ServerError(error);
}
//lock environment
MutexAutoLock envlock(m_env_mutex);
// Create the Map (loads map_meta.txt, overriding configured mapgen params)
ServerMap *servermap = new ServerMap(m_path_world, this, m_emerge, m_metrics_backend.get());
m_startup_server_map = servermap;
// Initialize scripting
infostream << "Server: Initializing Lua" << std::endl;
m_script = new ServerScripting(this);
// Must be created before mod loading because we have some inventory creation
m_inventory_mgr = std::make_unique<ServerInventoryManager>();
m_script->loadMod(getBuiltinLuaPath() + DIR_DELIM "init.lua", BUILTIN_MOD_NAME);
m_script->checkSetByBuiltin();
m_gamespec.checkAndLog();
m_modmgr->loadMods(m_script);
m_script->saveGlobals();
// Read Textures and calculate sha1 sums
fillMediaCache();
// Apply item aliases in the node definition manager
m_nodedef->updateAliases(m_itemdef);
// Apply texture overrides from texturepack/override.txt
std::vector<std::string> paths;
fs::GetRecursiveDirs(paths, g_settings->get("texture_path"));
fs::GetRecursiveDirs(paths, m_gamespec.path + DIR_DELIM + "textures");
for (const std::string &path : paths) {
TextureOverrideSource override_source(path + DIR_DELIM + "override.txt");
m_nodedef->applyTextureOverrides(override_source.getNodeTileOverrides());
m_itemdef->applyTextureOverrides(override_source.getItemTextureOverrides());
}
m_nodedef->setNodeRegistrationStatus(true);
// Perform pending node name resolutions
m_nodedef->runNodeResolveCallbacks();
// unmap node names in cross-references
m_nodedef->resolveCrossrefs();
// init the recipe hashes to speed up crafting
m_craftdef->initHashes(this);
// Initialize Environment
m_startup_server_map = nullptr; // Ownership moved to ServerEnvironment
m_env = new ServerEnvironment(servermap, m_script, this,
m_path_world, m_metrics_backend.get());
m_env->init();
m_inventory_mgr->setEnv(m_env);
m_clients.setEnv(m_env);
if (!servermap->settings_mgr.makeMapgenParams())
FATAL_ERROR("Couldn't create any mapgen type");
// Initialize mapgens
m_emerge->initMapgens(servermap->getMapgenParams());
if (g_settings->getBool("enable_rollback_recording")) {
// Create rollback manager
m_rollback = new RollbackManager(m_path_world, this);
}
// Give environment reference to scripting api
m_script->initializeEnvironment(m_env);
// Do this after regular script init is done
m_script->initAsync();
// Register us to receive map edit events
servermap->addEventReceiver(this);
m_env->loadMeta();
// Those settings can be overwritten in world.mt, they are
// intended to be cached after environment loading.
m_liquid_transform_every = g_settings->getFloat("liquid_update");
m_max_chatmessage_length = g_settings->getU16("chat_message_max_size");
m_csm_restriction_flags = g_settings->getU64("csm_restriction_flags");
m_csm_restriction_noderange = g_settings->getU32("csm_restriction_noderange");
}
void Server::start()
{
init();
infostream << "Starting server on " << m_bind_addr.serializeString()
<< "..." << std::endl;
// Stop thread if already running
m_thread->stop();
// Initialize connection
m_con->SetTimeoutMs(30);
m_con->Serve(m_bind_addr);
// Start thread
m_thread->start();
// ASCII art for the win!
const char *art[] = {
" __. __. __. ",
" _____ |__| ____ _____ / |_ _____ _____ / |_ ",
" / \\| |/ \\ / __ \\ _\\/ __ \\/ __> _\\",
"| Y Y \\ | | \\ ___/| | | ___/\\___ \\| | ",
"|__|_| / |___| /\\______> | \\______>_____/| | ",
" \\/ \\/ \\/ \\/ \\/ "
};
if (!m_admin_chat) {
// we're not printing to rawstream to avoid it showing up in the logs.
// however it would then mess up the ncurses terminal (m_admin_chat),
// so we skip it in that case.
for (auto line : art)
std::cerr << line << std::endl;
}
actionstream << "World at [" << m_path_world << "]" << std::endl;
actionstream << "Server for gameid=\"" << m_gamespec.id
<< "\" listening on ";
m_bind_addr.print(actionstream);
actionstream << "." << std::endl;
}
void Server::stop()
{
infostream<<"Server: Stopping and waiting threads"<<std::endl;
// Stop threads (set run=false first so both start stopping)
m_thread->stop();
m_thread->wait();
infostream<<"Server: Threads stopped"<<std::endl;
}
void Server::step(float dtime)
{
// Limit a bit
if (dtime > 2.0)
dtime = 2.0;
{
MutexAutoLock lock(m_step_dtime_mutex);
m_step_dtime += dtime;
}
// Throw if fatal error occurred in thread
std::string async_err = m_async_fatal_error.get();
if (!async_err.empty()) {
if (!m_simple_singleplayer_mode) {
m_env->kickAllPlayers(SERVER_ACCESSDENIED_CRASH,
g_settings->get("kick_msg_crash"),
g_settings->getBool("ask_reconnect_on_crash"));
}
throw ServerError("AsyncErr: " + async_err);
}
}
void Server::AsyncRunStep(bool initial_step)
{
float dtime;
{
MutexAutoLock lock1(m_step_dtime_mutex);
dtime = m_step_dtime;
}
{
// Send blocks to clients
SendBlocks(dtime);
}
if((dtime < 0.001) && !initial_step)
return;
ScopeProfiler sp(g_profiler, "Server::AsyncRunStep()", SPT_AVG);
{
MutexAutoLock lock1(m_step_dtime_mutex);
m_step_dtime -= dtime;
}
/*
Update uptime
*/
m_uptime_counter->increment(dtime);
handlePeerChanges();
/*
Update time of day and overall game time
*/
m_env->setTimeOfDaySpeed(g_settings->getFloat("time_speed"));
/*
Send to clients at constant intervals
*/
m_time_of_day_send_timer -= dtime;
if (m_time_of_day_send_timer < 0.0) {
m_time_of_day_send_timer = g_settings->getFloat("time_send_interval");
u16 time = m_env->getTimeOfDay();
float time_speed = g_settings->getFloat("time_speed");
SendTimeOfDay(PEER_ID_INEXISTENT, time, time_speed);
m_timeofday_gauge->set(time);
}
{
MutexAutoLock lock(m_env_mutex);
// Figure out and report maximum lag to environment
float max_lag = m_env->getMaxLagEstimate();
max_lag *= 0.9998; // Decrease slowly (about half per 5 minutes)
if(dtime > max_lag){
if(dtime > 0.1 && dtime > max_lag * 2.0)
infostream<<"Server: Maximum lag peaked to "<<dtime
<<" s"<<std::endl;
max_lag = dtime;
}
m_env->reportMaxLagEstimate(max_lag);
// Step environment
m_env->step(dtime);
}
static const float map_timer_and_unload_dtime = 2.92;
if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime))
{
MutexAutoLock lock(m_env_mutex);
// Run Map's timers and unload unused data
ScopeProfiler sp(g_profiler, "Server: map timer and unload");
m_env->getMap().timerUpdate(map_timer_and_unload_dtime,
std::max(g_settings->getFloat("server_unload_unused_data_timeout"), 0.0f),
-1);
}
/*
Note: Orphan MapBlock ptrs become dangling after this call.
*/
m_env->getServerMap().step();
/*
Listen to the admin chat, if available
*/
if (m_admin_chat) {
if (!m_admin_chat->command_queue.empty()) {
MutexAutoLock lock(m_env_mutex);
while (!m_admin_chat->command_queue.empty()) {
ChatEvent *evt = m_admin_chat->command_queue.pop_frontNoEx();
handleChatInterfaceEvent(evt);
delete evt;
}
}
m_admin_chat->outgoing_queue.push_back(
new ChatEventTimeInfo(m_env->getGameTime(), m_env->getTimeOfDay()));
}
/*
Do background stuff
*/
/* Transform liquids */
m_liquid_transform_timer += dtime;
if(m_liquid_transform_timer >= m_liquid_transform_every)
{
m_liquid_transform_timer -= m_liquid_transform_every;
MutexAutoLock lock(m_env_mutex);
ScopeProfiler sp(g_profiler, "Server: liquid transform");
std::map<v3s16, MapBlock*> modified_blocks;
m_env->getServerMap().transformLiquids(modified_blocks, m_env);
if (!modified_blocks.empty()) {
MapEditEvent event;
event.type = MEET_OTHER;
event.setModifiedBlocks(modified_blocks);
m_env->getMap().dispatchEvent(event);
}
}
m_clients.step(dtime);
// increase/decrease lag gauge gradually
if (m_lag_gauge->get() > dtime) {
m_lag_gauge->decrement(dtime/100);
} else {
m_lag_gauge->increment(dtime/100);
}
{
float &counter = m_step_pending_dyn_media_timer;
counter += dtime;
if (counter >= 5.0f) {
stepPendingDynMediaCallbacks(counter);
counter = 0;
}
}
#if USE_CURL
// send masterserver announce
{
float &counter = m_masterserver_timer;
if (!isSingleplayer() && (!counter || counter >= 300.0) &&
g_settings->getBool("server_announce")) {
ServerList::sendAnnounce(counter ? ServerList::AA_UPDATE :
ServerList::AA_START,
m_bind_addr.getPort(),
m_clients.getPlayerNames(),
m_uptime_counter->get(),
m_env->getGameTime(),
m_lag_gauge->get(),
m_gamespec.id,
Mapgen::getMapgenName(m_emerge->mgparams->mgtype),
m_modmgr->getMods(),
m_dedicated);
counter = 0.01;
}
counter += dtime;
}
#endif
/*
Check added and deleted active objects
*/
{
//infostream<<"Server: Checking added and deleted active objects"<<std::endl;
MutexAutoLock envlock(m_env_mutex);
{
ClientInterface::AutoLock clientlock(m_clients);
const RemoteClientMap &clients = m_clients.getClientList();
ScopeProfiler sp(g_profiler, "Server: update objects within range");
m_player_gauge->set(clients.size());
for (const auto &client_it : clients) {
RemoteClient *client = client_it.second;
if (client->getState() < CS_DefinitionsSent)
continue;
// This can happen if the client times out somehow
if (!m_env->getPlayer(client->peer_id))
continue;
PlayerSAO *playersao = getPlayerSAO(client->peer_id);
if (!playersao)
continue;
SendActiveObjectRemoveAdd(client, playersao);
}
}
// Write changes to the mod storage
m_mod_storage_save_timer -= dtime;
if (m_mod_storage_save_timer <= 0.0f) {
m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
m_mod_storage_database->endSave();
m_mod_storage_database->beginSave();
}
}
/*
Send object messages
*/
{
MutexAutoLock envlock(m_env_mutex);
ScopeProfiler sp(g_profiler, "Server: send SAO messages");
// Key = object id
// Value = data sent by object
std::unordered_map<u16, std::vector<ActiveObjectMessage>*> buffered_messages;
// Get active object messages from environment
ActiveObjectMessage aom(0);
u32 count_reliable = 0, count_unreliable = 0;
for(;;) {
if (!m_env->getActiveObjectMessage(&aom))
break;
if (aom.reliable)
count_reliable++;
else
count_unreliable++;
std::vector<ActiveObjectMessage>* message_list = nullptr;
auto n = buffered_messages.find(aom.id);
if (n == buffered_messages.end()) {
message_list = new std::vector<ActiveObjectMessage>;
buffered_messages[aom.id] = message_list;
} else {
message_list = n->second;
}
message_list->push_back(std::move(aom));
}
m_aom_buffer_counter[0]->increment(count_reliable);
m_aom_buffer_counter[1]->increment(count_unreliable);
{
ClientInterface::AutoLock clientlock(m_clients);
const RemoteClientMap &clients = m_clients.getClientList();
// Route data to every client
std::string reliable_data, unreliable_data;
for (const auto &client_it : clients) {
reliable_data.clear();
unreliable_data.clear();
RemoteClient *client = client_it.second;
PlayerSAO *player = getPlayerSAO(client->peer_id);
// Go through all objects in message buffer
for (const auto &buffered_message : buffered_messages) {
// If object does not exist or is not known by client, skip it
u16 id = buffered_message.first;
ServerActiveObject *sao = m_env->getActiveObject(id);
if (!sao || client->m_known_objects.find(id) == client->m_known_objects.end())
continue;
// Get message list of object
std::vector<ActiveObjectMessage>* list = buffered_message.second;
// Go through every message
for (const ActiveObjectMessage &aom : *list) {
// Send position updates to players who do not see the attachment
if (aom.datastring[0] == AO_CMD_UPDATE_POSITION) {
if (sao->getId() == player->getId())
continue;
// Do not send position updates for attached players
// as long the parent is known to the client
ServerActiveObject *parent = sao->getParent();
if (parent && client->m_known_objects.find(parent->getId()) !=
client->m_known_objects.end())
continue;
}
// Add full new data to appropriate buffer
std::string &buffer = aom.reliable ? reliable_data : unreliable_data;
char idbuf[2];
writeU16((u8*) idbuf, aom.id);
// u16 id
// std::string data
buffer.append(idbuf, sizeof(idbuf));
buffer.append(serializeString16(aom.datastring));
}
}
/*
reliable_data and unreliable_data are now ready.
Send them.
*/
if (!reliable_data.empty()) {
SendActiveObjectMessages(client->peer_id, reliable_data);
}
if (!unreliable_data.empty()) {
SendActiveObjectMessages(client->peer_id, unreliable_data, false);
}
}
}
// Clear buffered_messages
for (auto &buffered_message : buffered_messages) {
delete buffered_message.second;
}
}
/*
Send queued-for-sending map edit events.
*/
{
// We will be accessing the environment
MutexAutoLock lock(m_env_mutex);
// Single change sending is disabled if queue size is big
bool disable_single_change_sending = false;
if(m_unsent_map_edit_queue.size() >= 4)
disable_single_change_sending = true;
const auto event_count = m_unsent_map_edit_queue.size();
m_map_edit_event_counter->increment(event_count);
// We'll log the amount of each
Profiler prof;
std::unordered_set<v3s16> node_meta_updates;
while (!m_unsent_map_edit_queue.empty()) {
MapEditEvent* event = m_unsent_map_edit_queue.front();
m_unsent_map_edit_queue.pop();
// Players far away from the change are stored here.
// Instead of sending the changes, MapBlocks are set not sent
// for them.
std::unordered_set<u16> far_players;
switch (event->type) {
case MEET_ADDNODE:
case MEET_SWAPNODE:
prof.add("MEET_ADDNODE", 1);
sendAddNode(event->p, event->n, &far_players,
disable_single_change_sending ? 5 : 30,
event->type == MEET_ADDNODE);
break;
case MEET_REMOVENODE:
prof.add("MEET_REMOVENODE", 1);
sendRemoveNode(event->p, &far_players,
disable_single_change_sending ? 5 : 30);
break;
case MEET_BLOCK_NODE_METADATA_CHANGED: {
prof.add("MEET_BLOCK_NODE_METADATA_CHANGED", 1);
if (!event->is_private_change) {
node_meta_updates.emplace(event->p);
}
if (MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(
getNodeBlockPos(event->p))) {
block->raiseModified(MOD_STATE_WRITE_NEEDED,
MOD_REASON_REPORT_META_CHANGE);
}
break;
}
case MEET_OTHER:
prof.add("MEET_OTHER", 1);
for (const v3s16 &modified_block : event->modified_blocks) {
m_clients.markBlockposAsNotSent(modified_block);
}
break;
default:
prof.add("unknown", 1);
warningstream << "Server: Unknown MapEditEvent "
<< ((u32)event->type) << std::endl;
break;
}
/*
Set blocks not sent to far players
*/
if (!far_players.empty()) {
// Convert list format to that wanted by SetBlocksNotSent
std::map<v3s16, MapBlock*> modified_blocks2;
for (const v3s16 &modified_block : event->modified_blocks) {
modified_blocks2[modified_block] =
m_env->getMap().getBlockNoCreateNoEx(modified_block);
}
// Set blocks not sent
for (const u16 far_player : far_players) {
if (RemoteClient *client = getClient(far_player))
client->SetBlocksNotSent(modified_blocks2);
}
}
delete event;
}
if (event_count >= 5) {
infostream << "Server: MapEditEvents:" << std::endl;
prof.print(infostream);
} else if (event_count != 0) {
verbosestream << "Server: MapEditEvents:" << std::endl;
prof.print(verbosestream);
}