]> git.lizzy.rs Git - dragonfireclient.git/blob - src/client/client.cpp
Be lenient with extra slashes for CSM paths
[dragonfireclient.git] / src / client / client.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include <iostream>
21 #include <algorithm>
22 #include <sstream>
23 #include <cmath>
24 #include <IFileSystem.h>
25 #include "client.h"
26 #include "network/clientopcodes.h"
27 #include "network/connection.h"
28 #include "network/networkpacket.h"
29 #include "threading/mutex_auto_lock.h"
30 #include "client/clientevent.h"
31 #include "client/gameui.h"
32 #include "client/renderingengine.h"
33 #include "client/sound.h"
34 #include "client/tile.h"
35 #include "util/auth.h"
36 #include "util/directiontables.h"
37 #include "util/pointedthing.h"
38 #include "util/serialize.h"
39 #include "util/string.h"
40 #include "util/srp.h"
41 #include "filesys.h"
42 #include "mapblock_mesh.h"
43 #include "mapblock.h"
44 #include "minimap.h"
45 #include "modchannels.h"
46 #include "content/mods.h"
47 #include "profiler.h"
48 #include "shader.h"
49 #include "gettext.h"
50 #include "clientmap.h"
51 #include "clientmedia.h"
52 #include "version.h"
53 #include "database/database-sqlite3.h"
54 #include "serialization.h"
55 #include "guiscalingfilter.h"
56 #include "script/scripting_client.h"
57 #include "game.h"
58 #include "chatmessage.h"
59 #include "translation.h"
60
61 extern gui::IGUIEnvironment* guienv;
62
63 /*
64         Client
65 */
66
67 Client::Client(
68                 const char *playername,
69                 const std::string &password,
70                 const std::string &address_name,
71                 MapDrawControl &control,
72                 IWritableTextureSource *tsrc,
73                 IWritableShaderSource *shsrc,
74                 IWritableItemDefManager *itemdef,
75                 NodeDefManager *nodedef,
76                 ISoundManager *sound,
77                 MtEventManager *event,
78                 bool ipv6,
79                 GameUI *game_ui
80 ):
81         m_tsrc(tsrc),
82         m_shsrc(shsrc),
83         m_itemdef(itemdef),
84         m_nodedef(nodedef),
85         m_sound(sound),
86         m_event(event),
87         m_mesh_update_thread(this),
88         m_env(
89                 new ClientMap(this, control, 666),
90                 tsrc, this
91         ),
92         m_particle_manager(&m_env),
93         m_con(new con::Connection(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this)),
94         m_address_name(address_name),
95         m_server_ser_ver(SER_FMT_VER_INVALID),
96         m_last_chat_message_sent(time(NULL)),
97         m_password(password),
98         m_chosen_auth_mech(AUTH_MECHANISM_NONE),
99         m_media_downloader(new ClientMediaDownloader()),
100         m_state(LC_Created),
101         m_game_ui(game_ui),
102         m_modchannel_mgr(new ModChannelMgr())
103 {
104         // Add local player
105         m_env.setLocalPlayer(new LocalPlayer(this, playername));
106
107         if (g_settings->getBool("enable_minimap")) {
108                 m_minimap = new Minimap(this);
109         }
110         m_cache_save_interval = g_settings->getU16("server_map_save_interval");
111 }
112
113 void Client::loadMods()
114 {
115         // Don't load mods twice.
116         // If client scripting is disabled by the client, don't load builtin or
117         // client-provided mods.
118         if (m_mods_loaded || !g_settings->getBool("enable_client_modding"))
119                 return;
120
121         // If client scripting is disabled by the server, don't load builtin or
122         // client-provided mods.
123         // TODO Delete this code block when server-sent CSM and verifying of builtin are
124         // complete.
125         if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOAD_CLIENT_MODS)) {
126                 warningstream << "Client-provided mod loading is disabled by server." <<
127                         std::endl;
128                 return;
129         }
130
131         m_script = new ClientScripting(this);
132         m_env.setScript(m_script);
133         m_script->setEnv(&m_env);
134
135         // Load builtin
136         scanModIntoMemory(BUILTIN_MOD_NAME, getBuiltinLuaPath());
137         m_script->loadModFromMemory(BUILTIN_MOD_NAME);
138
139         // TODO Uncomment when server-sent CSM and verifying of builtin are complete
140         /*
141         // Don't load client-provided mods if disabled by server
142         if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOAD_CLIENT_MODS)) {
143                 warningstream << "Client-provided mod loading is disabled by server." <<
144                         std::endl;
145                 // If builtin integrity is wrong, disconnect user
146                 if (!checkBuiltinIntegrity()) {
147                         // TODO disconnect user
148                 }
149                 return;
150         }
151         */
152
153         ClientModConfiguration modconf(getClientModsLuaPath());
154         m_mods = modconf.getMods();
155         // complain about mods with unsatisfied dependencies
156         if (!modconf.isConsistent()) {
157                 modconf.printUnsatisfiedModsError();
158                 return;
159         }
160
161         // Print mods
162         infostream << "Client loading mods: ";
163         for (const ModSpec &mod : m_mods)
164                 infostream << mod.name << " ";
165         infostream << std::endl;
166
167         // Load and run "mod" scripts
168         for (const ModSpec &mod : m_mods) {
169                 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
170                         throw ModError("Error loading mod \"" + mod.name +
171                                 "\": Mod name does not follow naming conventions: "
172                                         "Only characters [a-z0-9_] are allowed.");
173                 }
174                 scanModIntoMemory(mod.name, mod.path);
175         }
176
177         // Load and run "mod" scripts
178         for (const ModSpec &mod : m_mods)
179                 m_script->loadModFromMemory(mod.name);
180
181         // Mods are done loading. Unlock callbacks
182         m_mods_loaded = true;
183
184         // Run a callback when mods are loaded
185         m_script->on_mods_loaded();
186         if (m_state == LC_Ready)
187                 m_script->on_client_ready(m_env.getLocalPlayer());
188         if (m_camera)
189                 m_script->on_camera_ready(m_camera);
190 }
191
192 bool Client::checkBuiltinIntegrity()
193 {
194         // TODO
195         return true;
196 }
197
198 void Client::scanModSubfolder(const std::string &mod_name, const std::string &mod_path,
199                         std::string mod_subpath)
200 {
201         std::string full_path = mod_path + DIR_DELIM + mod_subpath;
202         std::vector<fs::DirListNode> mod = fs::GetDirListing(full_path);
203         for (const fs::DirListNode &j : mod) {
204                 if (j.dir) {
205                         scanModSubfolder(mod_name, mod_path, mod_subpath + j.name + DIR_DELIM);
206                         continue;
207                 }
208                 std::replace(mod_subpath.begin(), mod_subpath.end(), DIR_DELIM_CHAR, '/');
209
210                 std::string real_path = full_path + j.name;
211                 std::string vfs_path = mod_name + ":" + mod_subpath + j.name;
212                 infostream << "Client::scanModSubfolder(): Loading \"" << real_path
213                                 << "\" as \"" << vfs_path << "\"." << std::endl;
214
215                 std::ifstream is(real_path, std::ios::binary | std::ios::ate);
216                 if(!is.good()) {
217                         errorstream << "Client::scanModSubfolder(): Can't read file \""
218                                         << real_path << "\"." << std::endl;
219                         continue;
220                 }
221                 auto size = is.tellg();
222                 std::string contents(size, '\0');
223                 is.seekg(0);
224                 is.read(&contents[0], size);
225
226                 infostream << "  size: " << size << " bytes" << std::endl;
227                 m_mod_vfs.emplace(vfs_path, contents);
228         }
229 }
230
231 const std::string &Client::getBuiltinLuaPath()
232 {
233         static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
234         return builtin_dir;
235 }
236
237 const std::string &Client::getClientModsLuaPath()
238 {
239         static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
240         return clientmods_dir;
241 }
242
243 const std::vector<ModSpec>& Client::getMods() const
244 {
245         static std::vector<ModSpec> client_modspec_temp;
246         return client_modspec_temp;
247 }
248
249 const ModSpec* Client::getModSpec(const std::string &modname) const
250 {
251         return NULL;
252 }
253
254 void Client::Stop()
255 {
256         m_shutdown = true;
257         if (m_mods_loaded)
258                 m_script->on_shutdown();
259         //request all client managed threads to stop
260         m_mesh_update_thread.stop();
261         // Save local server map
262         if (m_localdb) {
263                 infostream << "Local map saving ended." << std::endl;
264                 m_localdb->endSave();
265         }
266
267         if (m_mods_loaded)
268                 delete m_script;
269 }
270
271 bool Client::isShutdown()
272 {
273         return m_shutdown || !m_mesh_update_thread.isRunning();
274 }
275
276 Client::~Client()
277 {
278         m_shutdown = true;
279         m_con->Disconnect();
280
281         deleteAuthData();
282
283         m_mesh_update_thread.stop();
284         m_mesh_update_thread.wait();
285         while (!m_mesh_update_thread.m_queue_out.empty()) {
286                 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
287                 delete r.mesh;
288         }
289
290
291         delete m_inventory_from_server;
292
293         // Delete detached inventories
294         for (auto &m_detached_inventorie : m_detached_inventories) {
295                 delete m_detached_inventorie.second;
296         }
297
298         // cleanup 3d model meshes on client shutdown
299         while (RenderingEngine::get_mesh_cache()->getMeshCount() != 0) {
300                 scene::IAnimatedMesh *mesh = RenderingEngine::get_mesh_cache()->getMeshByIndex(0);
301
302                 if (mesh)
303                         RenderingEngine::get_mesh_cache()->removeMesh(mesh);
304         }
305
306         delete m_minimap;
307         delete m_media_downloader;
308 }
309
310 void Client::connect(Address address, bool is_local_server)
311 {
312         initLocalMapSaving(address, m_address_name, is_local_server);
313
314         m_con->SetTimeoutMs(0);
315         m_con->Connect(address);
316 }
317
318 void Client::step(float dtime)
319 {
320         // Limit a bit
321         if (dtime > 2.0)
322                 dtime = 2.0;
323
324         m_animation_time += dtime;
325         if(m_animation_time > 60.0)
326                 m_animation_time -= 60.0;
327
328         m_time_of_day_update_timer += dtime;
329
330         ReceiveAll();
331
332         /*
333                 Packet counter
334         */
335         {
336                 float &counter = m_packetcounter_timer;
337                 counter -= dtime;
338                 if(counter <= 0.0)
339                 {
340                         counter = 20.0;
341
342                         infostream << "Client packetcounter (" << m_packetcounter_timer
343                                         << "):"<<std::endl;
344                         m_packetcounter.print(infostream);
345                         m_packetcounter.clear();
346                 }
347         }
348
349         // UGLY hack to fix 2 second startup delay caused by non existent
350         // server client startup synchronization in local server or singleplayer mode
351         static bool initial_step = true;
352         if (initial_step) {
353                 initial_step = false;
354         }
355         else if(m_state == LC_Created) {
356                 if (m_is_registration_confirmation_state) {
357                         // Waiting confirmation
358                         return;
359                 }
360                 float &counter = m_connection_reinit_timer;
361                 counter -= dtime;
362                 if(counter <= 0.0) {
363                         counter = 2.0;
364
365                         LocalPlayer *myplayer = m_env.getLocalPlayer();
366                         FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
367
368                         sendInit(myplayer->getName());
369                 }
370
371                 // Not connected, return
372                 return;
373         }
374
375         /*
376                 Do stuff if connected
377         */
378
379         /*
380                 Run Map's timers and unload unused data
381         */
382         const float map_timer_and_unload_dtime = 5.25;
383         if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
384                 std::vector<v3s16> deleted_blocks;
385                 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
386                         g_settings->getFloat("client_unload_unused_data_timeout"),
387                         g_settings->getS32("client_mapblock_limit"),
388                         &deleted_blocks);
389
390                 /*
391                         Send info to server
392                         NOTE: This loop is intentionally iterated the way it is.
393                 */
394
395                 std::vector<v3s16>::iterator i = deleted_blocks.begin();
396                 std::vector<v3s16> sendlist;
397                 for(;;) {
398                         if(sendlist.size() == 255 || i == deleted_blocks.end()) {
399                                 if(sendlist.empty())
400                                         break;
401                                 /*
402                                         [0] u16 command
403                                         [2] u8 count
404                                         [3] v3s16 pos_0
405                                         [3+6] v3s16 pos_1
406                                         ...
407                                 */
408
409                                 sendDeletedBlocks(sendlist);
410
411                                 if(i == deleted_blocks.end())
412                                         break;
413
414                                 sendlist.clear();
415                         }
416
417                         sendlist.push_back(*i);
418                         ++i;
419                 }
420         }
421
422         /*
423                 Send pending messages on out chat queue
424         */
425         if (!m_out_chat_queue.empty() && canSendChatMessage()) {
426                 sendChatMessage(m_out_chat_queue.front());
427                 m_out_chat_queue.pop();
428         }
429
430         /*
431                 Handle environment
432         */
433         // Control local player (0ms)
434         LocalPlayer *player = m_env.getLocalPlayer();
435         assert(player);
436         player->applyControl(dtime, &m_env);
437
438         // Step environment
439         m_env.step(dtime);
440         m_sound->step(dtime);
441
442         /*
443                 Get events
444         */
445         while (m_env.hasClientEnvEvents()) {
446                 ClientEnvEvent envEvent = m_env.getClientEnvEvent();
447
448                 if (envEvent.type == CEE_PLAYER_DAMAGE) {
449                         u16 damage = envEvent.player_damage.amount;
450
451                         if (envEvent.player_damage.send_to_server)
452                                 sendDamage(damage);
453
454                         // Add to ClientEvent queue
455                         ClientEvent *event = new ClientEvent();
456                         event->type = CE_PLAYER_DAMAGE;
457                         event->player_damage.amount = damage;
458                         m_client_event_queue.push(event);
459                 }
460         }
461
462         /*
463                 Print some info
464         */
465         float &counter = m_avg_rtt_timer;
466         counter += dtime;
467         if(counter >= 10) {
468                 counter = 0.0;
469                 // connectedAndInitialized() is true, peer exists.
470                 float avg_rtt = getRTT();
471                 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
472         }
473
474         /*
475                 Send player position to server
476         */
477         {
478                 float &counter = m_playerpos_send_timer;
479                 counter += dtime;
480                 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
481                 {
482                         counter = 0.0;
483                         sendPlayerPos();
484                 }
485         }
486
487         /*
488                 Replace updated meshes
489         */
490         {
491                 int num_processed_meshes = 0;
492                 std::vector<v3s16> blocks_to_ack;
493                 while (!m_mesh_update_thread.m_queue_out.empty())
494                 {
495                         num_processed_meshes++;
496
497                         MinimapMapblock *minimap_mapblock = NULL;
498                         bool do_mapper_update = true;
499
500                         MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
501                         MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
502                         if (block) {
503                                 // Delete the old mesh
504                                 delete block->mesh;
505                                 block->mesh = nullptr;
506
507                                 if (r.mesh) {
508                                         minimap_mapblock = r.mesh->moveMinimapMapblock();
509                                         if (minimap_mapblock == NULL)
510                                                 do_mapper_update = false;
511
512                                         bool is_empty = true;
513                                         for (int l = 0; l < MAX_TILE_LAYERS; l++)
514                                                 if (r.mesh->getMesh(l)->getMeshBufferCount() != 0)
515                                                         is_empty = false;
516
517                                         if (is_empty)
518                                                 delete r.mesh;
519                                         else
520                                                 // Replace with the new mesh
521                                                 block->mesh = r.mesh;
522                                 }
523                         } else {
524                                 delete r.mesh;
525                         }
526
527                         if (m_minimap && do_mapper_update)
528                                 m_minimap->addBlock(r.p, minimap_mapblock);
529
530                         if (r.ack_block_to_server) {
531                                 if (blocks_to_ack.size() == 255) {
532                                         sendGotBlocks(blocks_to_ack);
533                                         blocks_to_ack.clear();
534                                 }
535
536                                 blocks_to_ack.emplace_back(r.p);
537                         }
538                 }
539                 if (blocks_to_ack.size() > 0) {
540                                 // Acknowledge block(s)
541                                 sendGotBlocks(blocks_to_ack);
542                 }
543
544                 if (num_processed_meshes > 0)
545                         g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
546         }
547
548         /*
549                 Load fetched media
550         */
551         if (m_media_downloader && m_media_downloader->isStarted()) {
552                 m_media_downloader->step(this);
553                 if (m_media_downloader->isDone()) {
554                         delete m_media_downloader;
555                         m_media_downloader = NULL;
556                 }
557         }
558
559         /*
560                 If the server didn't update the inventory in a while, revert
561                 the local inventory (so the player notices the lag problem
562                 and knows something is wrong).
563         */
564         if (m_inventory_from_server) {
565                 float interval = 10.0f;
566                 float count_before = std::floor(m_inventory_from_server_age / interval);
567
568                 m_inventory_from_server_age += dtime;
569
570                 float count_after = std::floor(m_inventory_from_server_age / interval);
571
572                 if (count_after != count_before) {
573                         // Do this every <interval> seconds after TOCLIENT_INVENTORY
574                         // Reset the locally changed inventory to the authoritative inventory
575                         player->inventory = *m_inventory_from_server;
576                         m_update_wielded_item = true;
577                 }
578         }
579
580         /*
581                 Update positions of sounds attached to objects
582         */
583         {
584                 for (auto &m_sounds_to_object : m_sounds_to_objects) {
585                         int client_id = m_sounds_to_object.first;
586                         u16 object_id = m_sounds_to_object.second;
587                         ClientActiveObject *cao = m_env.getActiveObject(object_id);
588                         if (!cao)
589                                 continue;
590                         m_sound->updateSoundPosition(client_id, cao->getPosition());
591                 }
592         }
593
594         /*
595                 Handle removed remotely initiated sounds
596         */
597         m_removed_sounds_check_timer += dtime;
598         if(m_removed_sounds_check_timer >= 2.32) {
599                 m_removed_sounds_check_timer = 0;
600                 // Find removed sounds and clear references to them
601                 std::vector<s32> removed_server_ids;
602                 for (std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.begin();
603                                 i != m_sounds_server_to_client.end();) {
604                         s32 server_id = i->first;
605                         int client_id = i->second;
606                         ++i;
607                         if(!m_sound->soundExists(client_id)) {
608                                 m_sounds_server_to_client.erase(server_id);
609                                 m_sounds_client_to_server.erase(client_id);
610                                 m_sounds_to_objects.erase(client_id);
611                                 removed_server_ids.push_back(server_id);
612                         }
613                 }
614
615                 // Sync to server
616                 if(!removed_server_ids.empty()) {
617                         sendRemovedSounds(removed_server_ids);
618                 }
619         }
620
621         m_mod_storage_save_timer -= dtime;
622         if (m_mod_storage_save_timer <= 0.0f) {
623                 verbosestream << "Saving registered mod storages." << std::endl;
624                 m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
625                 for (std::unordered_map<std::string, ModMetadata *>::const_iterator
626                                 it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
627                         if (it->second->isModified()) {
628                                 it->second->save(getModStoragePath());
629                         }
630                 }
631         }
632
633         // Write server map
634         if (m_localdb && m_localdb_save_interval.step(dtime,
635                         m_cache_save_interval)) {
636                 m_localdb->endSave();
637                 m_localdb->beginSave();
638         }
639 }
640
641 bool Client::loadMedia(const std::string &data, const std::string &filename)
642 {
643         // Silly irrlicht's const-incorrectness
644         Buffer<char> data_rw(data.c_str(), data.size());
645
646         std::string name;
647
648         const char *image_ext[] = {
649                 ".png", ".jpg", ".bmp", ".tga",
650                 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
651                 NULL
652         };
653         name = removeStringEnd(filename, image_ext);
654         if (!name.empty()) {
655                 verbosestream<<"Client: Attempting to load image "
656                 <<"file \""<<filename<<"\""<<std::endl;
657
658                 io::IFileSystem *irrfs = RenderingEngine::get_filesystem();
659                 video::IVideoDriver *vdrv = RenderingEngine::get_video_driver();
660
661                 // Create an irrlicht memory file
662                 io::IReadFile *rfile = irrfs->createMemoryReadFile(
663                                 *data_rw, data_rw.getSize(), "_tempreadfile");
664
665                 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
666
667                 // Read image
668                 video::IImage *img = vdrv->createImageFromFile(rfile);
669                 if (!img) {
670                         errorstream<<"Client: Cannot create image from data of "
671                                         <<"file \""<<filename<<"\""<<std::endl;
672                         rfile->drop();
673                         return false;
674                 }
675
676                 m_tsrc->insertSourceImage(filename, img);
677                 img->drop();
678                 rfile->drop();
679                 return true;
680         }
681
682         const char *sound_ext[] = {
683                 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
684                 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
685                 ".ogg", NULL
686         };
687         name = removeStringEnd(filename, sound_ext);
688         if (!name.empty()) {
689                 verbosestream<<"Client: Attempting to load sound "
690                 <<"file \""<<filename<<"\""<<std::endl;
691                 m_sound->loadSoundData(name, data);
692                 return true;
693         }
694
695         const char *model_ext[] = {
696                 ".x", ".b3d", ".md2", ".obj",
697                 NULL
698         };
699
700         name = removeStringEnd(filename, model_ext);
701         if (!name.empty()) {
702                 verbosestream<<"Client: Storing model into memory: "
703                                 <<"\""<<filename<<"\""<<std::endl;
704                 if(m_mesh_data.count(filename))
705                         errorstream<<"Multiple models with name \""<<filename.c_str()
706                                         <<"\" found; replacing previous model"<<std::endl;
707                 m_mesh_data[filename] = data;
708                 return true;
709         }
710
711         const char *translate_ext[] = {
712                 ".tr", NULL
713         };
714         name = removeStringEnd(filename, translate_ext);
715         if (!name.empty()) {
716                 verbosestream << "Client: Loading translation: "
717                                 << "\"" << filename << "\"" << std::endl;
718                 g_translations->loadTranslation(data);
719                 return true;
720         }
721
722         errorstream << "Client: Don't know how to load file \""
723                 << filename << "\"" << std::endl;
724         return false;
725 }
726
727 // Virtual methods from con::PeerHandler
728 void Client::peerAdded(con::Peer *peer)
729 {
730         infostream << "Client::peerAdded(): peer->id="
731                         << peer->id << std::endl;
732 }
733 void Client::deletingPeer(con::Peer *peer, bool timeout)
734 {
735         infostream << "Client::deletingPeer(): "
736                         "Server Peer is getting deleted "
737                         << "(timeout=" << timeout << ")" << std::endl;
738
739         if (timeout) {
740                 m_access_denied = true;
741                 m_access_denied_reason = gettext("Connection timed out.");
742         }
743 }
744
745 /*
746         u16 command
747         u16 number of files requested
748         for each file {
749                 u16 length of name
750                 string name
751         }
752 */
753 void Client::request_media(const std::vector<std::string> &file_requests)
754 {
755         std::ostringstream os(std::ios_base::binary);
756         writeU16(os, TOSERVER_REQUEST_MEDIA);
757         size_t file_requests_size = file_requests.size();
758
759         FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
760
761         // Packet dynamicly resized
762         NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
763
764         pkt << (u16) (file_requests_size & 0xFFFF);
765
766         for (const std::string &file_request : file_requests) {
767                 pkt << file_request;
768         }
769
770         Send(&pkt);
771
772         infostream << "Client: Sending media request list to server ("
773                         << file_requests.size() << " files. packet size)" << std::endl;
774 }
775
776 void Client::initLocalMapSaving(const Address &address,
777                 const std::string &hostname,
778                 bool is_local_server)
779 {
780         if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
781                 return;
782         }
783
784         const std::string world_path = porting::path_user
785                 + DIR_DELIM + "worlds"
786                 + DIR_DELIM + "server_"
787                 + hostname + "_" + std::to_string(address.getPort());
788
789         fs::CreateAllDirs(world_path);
790
791         m_localdb = new MapDatabaseSQLite3(world_path);
792         m_localdb->beginSave();
793         actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
794 }
795
796 void Client::ReceiveAll()
797 {
798         u64 start_ms = porting::getTimeMs();
799         for(;;)
800         {
801                 // Limit time even if there would be huge amounts of data to
802                 // process
803                 if(porting::getTimeMs() > start_ms + 100)
804                         break;
805
806                 try {
807                         Receive();
808                         g_profiler->graphAdd("client_received_packets", 1);
809                 }
810                 catch(con::NoIncomingDataException &e) {
811                         break;
812                 }
813                 catch(con::InvalidIncomingDataException &e) {
814                         infostream<<"Client::ReceiveAll(): "
815                                         "InvalidIncomingDataException: what()="
816                                         <<e.what()<<std::endl;
817                 }
818         }
819 }
820
821 void Client::Receive()
822 {
823         NetworkPacket pkt;
824         m_con->Receive(&pkt);
825         ProcessData(&pkt);
826 }
827
828 inline void Client::handleCommand(NetworkPacket* pkt)
829 {
830         const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
831         (this->*opHandle.handler)(pkt);
832 }
833
834 /*
835         sender_peer_id given to this shall be quaranteed to be a valid peer
836 */
837 void Client::ProcessData(NetworkPacket *pkt)
838 {
839         ToClientCommand command = (ToClientCommand) pkt->getCommand();
840         u32 sender_peer_id = pkt->getPeerId();
841
842         //infostream<<"Client: received command="<<command<<std::endl;
843         m_packetcounter.add((u16)command);
844
845         /*
846                 If this check is removed, be sure to change the queue
847                 system to know the ids
848         */
849         if(sender_peer_id != PEER_ID_SERVER) {
850                 infostream << "Client::ProcessData(): Discarding data not "
851                         "coming from server: peer_id=" << sender_peer_id
852                         << std::endl;
853                 return;
854         }
855
856         // Command must be handled into ToClientCommandHandler
857         if (command >= TOCLIENT_NUM_MSG_TYPES) {
858                 infostream << "Client: Ignoring unknown command "
859                         << command << std::endl;
860                 return;
861         }
862
863         /*
864          * Those packets are handled before m_server_ser_ver is set, it's normal
865          * But we must use the new ToClientConnectionState in the future,
866          * as a byte mask
867          */
868         if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
869                 handleCommand(pkt);
870                 return;
871         }
872
873         if(m_server_ser_ver == SER_FMT_VER_INVALID) {
874                 infostream << "Client: Server serialization"
875                                 " format invalid or not initialized."
876                                 " Skipping incoming command=" << command << std::endl;
877                 return;
878         }
879
880         /*
881           Handle runtime commands
882         */
883
884         handleCommand(pkt);
885 }
886
887 void Client::Send(NetworkPacket* pkt)
888 {
889         m_con->Send(PEER_ID_SERVER,
890                 serverCommandFactoryTable[pkt->getCommand()].channel,
891                 pkt,
892                 serverCommandFactoryTable[pkt->getCommand()].reliable);
893 }
894
895 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
896 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
897 {
898         v3f pf           = myplayer->getPosition() * 100;
899         v3f sf           = myplayer->getSpeed() * 100;
900         s32 pitch        = myplayer->getPitch() * 100;
901         s32 yaw          = myplayer->getYaw() * 100;
902         u32 keyPressed   = myplayer->keyPressed;
903         // scaled by 80, so that pi can fit into a u8
904         u8 fov           = clientMap->getCameraFov() * 80;
905         u8 wanted_range  = MYMIN(255,
906                         std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
907
908         v3s32 position(pf.X, pf.Y, pf.Z);
909         v3s32 speed(sf.X, sf.Y, sf.Z);
910
911         /*
912                 Format:
913                 [0] v3s32 position*100
914                 [12] v3s32 speed*100
915                 [12+12] s32 pitch*100
916                 [12+12+4] s32 yaw*100
917                 [12+12+4+4] u32 keyPressed
918                 [12+12+4+4+4] u8 fov*80
919                 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
920         */
921         *pkt << position << speed << pitch << yaw << keyPressed;
922         *pkt << fov << wanted_range;
923 }
924
925 void Client::interact(InteractAction action, const PointedThing& pointed)
926 {
927         if(m_state != LC_Ready) {
928                 errorstream << "Client::interact() "
929                                 "Canceled (not connected)"
930                                 << std::endl;
931                 return;
932         }
933
934         LocalPlayer *myplayer = m_env.getLocalPlayer();
935         if (myplayer == NULL)
936                 return;
937
938         /*
939                 [0] u16 command
940                 [2] u8 action
941                 [3] u16 item
942                 [5] u32 length of the next item (plen)
943                 [9] serialized PointedThing
944                 [9 + plen] player position information
945         */
946
947         NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
948
949         pkt << (u8)action;
950         pkt << myplayer->getWieldIndex();
951
952         std::ostringstream tmp_os(std::ios::binary);
953         pointed.serialize(tmp_os);
954
955         pkt.putLongString(tmp_os.str());
956
957         writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
958
959         Send(&pkt);
960 }
961
962 void Client::deleteAuthData()
963 {
964         if (!m_auth_data)
965                 return;
966
967         switch (m_chosen_auth_mech) {
968                 case AUTH_MECHANISM_FIRST_SRP:
969                         break;
970                 case AUTH_MECHANISM_SRP:
971                 case AUTH_MECHANISM_LEGACY_PASSWORD:
972                         srp_user_delete((SRPUser *) m_auth_data);
973                         m_auth_data = NULL;
974                         break;
975                 case AUTH_MECHANISM_NONE:
976                         break;
977         }
978         m_chosen_auth_mech = AUTH_MECHANISM_NONE;
979 }
980
981
982 AuthMechanism Client::choseAuthMech(const u32 mechs)
983 {
984         if (mechs & AUTH_MECHANISM_SRP)
985                 return AUTH_MECHANISM_SRP;
986
987         if (mechs & AUTH_MECHANISM_FIRST_SRP)
988                 return AUTH_MECHANISM_FIRST_SRP;
989
990         if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
991                 return AUTH_MECHANISM_LEGACY_PASSWORD;
992
993         return AUTH_MECHANISM_NONE;
994 }
995
996 void Client::sendInit(const std::string &playerName)
997 {
998         NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
999
1000         // we don't support network compression yet
1001         u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1002
1003         pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1004         pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1005         pkt << playerName;
1006
1007         Send(&pkt);
1008 }
1009
1010 void Client::promptConfirmRegistration(AuthMechanism chosen_auth_mechanism)
1011 {
1012         m_chosen_auth_mech = chosen_auth_mechanism;
1013         m_is_registration_confirmation_state = true;
1014 }
1015
1016 void Client::confirmRegistration()
1017 {
1018         m_is_registration_confirmation_state = false;
1019         startAuth(m_chosen_auth_mech);
1020 }
1021
1022 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1023 {
1024         m_chosen_auth_mech = chosen_auth_mechanism;
1025
1026         switch (chosen_auth_mechanism) {
1027                 case AUTH_MECHANISM_FIRST_SRP: {
1028                         // send srp verifier to server
1029                         std::string verifier;
1030                         std::string salt;
1031                         generate_srp_verifier_and_salt(getPlayerName(), m_password,
1032                                 &verifier, &salt);
1033
1034                         NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1035                         resp_pkt << salt << verifier << (u8)((m_password.empty()) ? 1 : 0);
1036
1037                         Send(&resp_pkt);
1038                         break;
1039                 }
1040                 case AUTH_MECHANISM_SRP:
1041                 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1042                         u8 based_on = 1;
1043
1044                         if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1045                                 m_password = translate_password(getPlayerName(), m_password);
1046                                 based_on = 0;
1047                         }
1048
1049                         std::string playername_u = lowercase(getPlayerName());
1050                         m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1051                                 getPlayerName().c_str(), playername_u.c_str(),
1052                                 (const unsigned char *) m_password.c_str(),
1053                                 m_password.length(), NULL, NULL);
1054                         char *bytes_A = 0;
1055                         size_t len_A = 0;
1056                         SRP_Result res = srp_user_start_authentication(
1057                                 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1058                                 (unsigned char **) &bytes_A, &len_A);
1059                         FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1060
1061                         NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1062                         resp_pkt << std::string(bytes_A, len_A) << based_on;
1063                         Send(&resp_pkt);
1064                         break;
1065                 }
1066                 case AUTH_MECHANISM_NONE:
1067                         break; // not handled in this method
1068         }
1069 }
1070
1071 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1072 {
1073         NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1074
1075         pkt << (u8) blocks.size();
1076
1077         for (const v3s16 &block : blocks) {
1078                 pkt << block;
1079         }
1080
1081         Send(&pkt);
1082 }
1083
1084 void Client::sendGotBlocks(const std::vector<v3s16> &blocks)
1085 {
1086         NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6 * blocks.size());
1087         pkt << (u8) blocks.size();
1088         for (const v3s16 &block : blocks)
1089                 pkt << block;
1090
1091         Send(&pkt);
1092 }
1093
1094 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1095 {
1096         size_t server_ids = soundList.size();
1097         assert(server_ids <= 0xFFFF);
1098
1099         NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1100
1101         pkt << (u16) (server_ids & 0xFFFF);
1102
1103         for (int sound_id : soundList)
1104                 pkt << sound_id;
1105
1106         Send(&pkt);
1107 }
1108
1109 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1110                 const StringMap &fields)
1111 {
1112         size_t fields_size = fields.size();
1113
1114         FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1115
1116         NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1117
1118         pkt << p << formname << (u16) (fields_size & 0xFFFF);
1119
1120         StringMap::const_iterator it;
1121         for (it = fields.begin(); it != fields.end(); ++it) {
1122                 const std::string &name = it->first;
1123                 const std::string &value = it->second;
1124                 pkt << name;
1125                 pkt.putLongString(value);
1126         }
1127
1128         Send(&pkt);
1129 }
1130
1131 void Client::sendInventoryFields(const std::string &formname,
1132                 const StringMap &fields)
1133 {
1134         size_t fields_size = fields.size();
1135         FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1136
1137         NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1138         pkt << formname << (u16) (fields_size & 0xFFFF);
1139
1140         StringMap::const_iterator it;
1141         for (it = fields.begin(); it != fields.end(); ++it) {
1142                 const std::string &name  = it->first;
1143                 const std::string &value = it->second;
1144                 pkt << name;
1145                 pkt.putLongString(value);
1146         }
1147
1148         Send(&pkt);
1149 }
1150
1151 void Client::sendInventoryAction(InventoryAction *a)
1152 {
1153         std::ostringstream os(std::ios_base::binary);
1154
1155         a->serialize(os);
1156
1157         // Make data buffer
1158         std::string s = os.str();
1159
1160         NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1161         pkt.putRawString(s.c_str(),s.size());
1162
1163         Send(&pkt);
1164 }
1165
1166 bool Client::canSendChatMessage() const
1167 {
1168         u32 now = time(NULL);
1169         float time_passed = now - m_last_chat_message_sent;
1170
1171         float virt_chat_message_allowance = m_chat_message_allowance + time_passed *
1172                         (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1173
1174         if (virt_chat_message_allowance < 1.0f)
1175                 return false;
1176
1177         return true;
1178 }
1179
1180 void Client::sendChatMessage(const std::wstring &message)
1181 {
1182         const s16 max_queue_size = g_settings->getS16("max_out_chat_queue_size");
1183         if (canSendChatMessage()) {
1184                 u32 now = time(NULL);
1185                 float time_passed = now - m_last_chat_message_sent;
1186                 m_last_chat_message_sent = time(NULL);
1187
1188                 m_chat_message_allowance += time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1189                 if (m_chat_message_allowance > CLIENT_CHAT_MESSAGE_LIMIT_PER_10S)
1190                         m_chat_message_allowance = CLIENT_CHAT_MESSAGE_LIMIT_PER_10S;
1191
1192                 m_chat_message_allowance -= 1.0f;
1193
1194                 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1195
1196                 pkt << message;
1197
1198                 Send(&pkt);
1199         } else if (m_out_chat_queue.size() < (u16) max_queue_size || max_queue_size == -1) {
1200                 m_out_chat_queue.push(message);
1201         } else {
1202                 infostream << "Could not queue chat message because maximum out chat queue size ("
1203                                 << max_queue_size << ") is reached." << std::endl;
1204         }
1205 }
1206
1207 void Client::clearOutChatQueue()
1208 {
1209         m_out_chat_queue = std::queue<std::wstring>();
1210 }
1211
1212 void Client::sendChangePassword(const std::string &oldpassword,
1213         const std::string &newpassword)
1214 {
1215         LocalPlayer *player = m_env.getLocalPlayer();
1216         if (player == NULL)
1217                 return;
1218
1219         // get into sudo mode and then send new password to server
1220         m_password = oldpassword;
1221         m_new_password = newpassword;
1222         startAuth(choseAuthMech(m_sudo_auth_methods));
1223 }
1224
1225
1226 void Client::sendDamage(u16 damage)
1227 {
1228         NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u16));
1229         pkt << damage;
1230         Send(&pkt);
1231 }
1232
1233 void Client::sendRespawn()
1234 {
1235         NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1236         Send(&pkt);
1237 }
1238
1239 void Client::sendReady()
1240 {
1241         NetworkPacket pkt(TOSERVER_CLIENT_READY,
1242                         1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash) + 2);
1243
1244         pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1245                 << (u8) 0 << (u16) strlen(g_version_hash);
1246
1247         pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1248         pkt << (u16)FORMSPEC_API_VERSION;
1249         Send(&pkt);
1250 }
1251
1252 void Client::sendPlayerPos()
1253 {
1254         LocalPlayer *player = m_env.getLocalPlayer();
1255         if (!player)
1256                 return;
1257
1258         ClientMap &map = m_env.getClientMap();
1259         u8 camera_fov   = map.getCameraFov();
1260         u8 wanted_range = map.getControl().wanted_range;
1261
1262         // Save bandwidth by only updating position when
1263         // player is not dead and something changed
1264
1265         // FIXME: This part causes breakages in mods like 3d_armor, and has been commented for now
1266         // if (m_activeobjects_received && player->isDead())
1267         //      return;
1268
1269         if (
1270                         player->last_position     == player->getPosition() &&
1271                         player->last_speed        == player->getSpeed()    &&
1272                         player->last_pitch        == player->getPitch()    &&
1273                         player->last_yaw          == player->getYaw()      &&
1274                         player->last_keyPressed   == player->keyPressed    &&
1275                         player->last_camera_fov   == camera_fov              &&
1276                         player->last_wanted_range == wanted_range)
1277                 return;
1278
1279         player->last_position     = player->getPosition();
1280         player->last_speed        = player->getSpeed();
1281         player->last_pitch        = player->getPitch();
1282         player->last_yaw          = player->getYaw();
1283         player->last_keyPressed   = player->keyPressed;
1284         player->last_camera_fov   = camera_fov;
1285         player->last_wanted_range = wanted_range;
1286
1287         NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1288
1289         writePlayerPos(player, &map, &pkt);
1290
1291         Send(&pkt);
1292 }
1293
1294 void Client::removeNode(v3s16 p)
1295 {
1296         std::map<v3s16, MapBlock*> modified_blocks;
1297
1298         try {
1299                 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1300         }
1301         catch(InvalidPositionException &e) {
1302         }
1303
1304         for (const auto &modified_block : modified_blocks) {
1305                 addUpdateMeshTaskWithEdge(modified_block.first, false, true);
1306         }
1307 }
1308
1309 /**
1310  * Helper function for Client Side Modding
1311  * CSM restrictions are applied there, this should not be used for core engine
1312  * @param p
1313  * @param is_valid_position
1314  * @return
1315  */
1316 MapNode Client::getNode(v3s16 p, bool *is_valid_position)
1317 {
1318         if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOOKUP_NODES)) {
1319                 v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
1320                 if ((u32) ppos.getDistanceFrom(p) > m_csm_restriction_noderange) {
1321                         *is_valid_position = false;
1322                         return {};
1323                 }
1324         }
1325         return m_env.getMap().getNode(p, is_valid_position);
1326 }
1327
1328 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1329 {
1330         //TimeTaker timer1("Client::addNode()");
1331
1332         std::map<v3s16, MapBlock*> modified_blocks;
1333
1334         try {
1335                 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1336                 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1337         }
1338         catch(InvalidPositionException &e) {
1339         }
1340
1341         for (const auto &modified_block : modified_blocks) {
1342                 addUpdateMeshTaskWithEdge(modified_block.first, false, true);
1343         }
1344 }
1345
1346 void Client::setPlayerControl(PlayerControl &control)
1347 {
1348         LocalPlayer *player = m_env.getLocalPlayer();
1349         assert(player);
1350         player->control = control;
1351 }
1352
1353 void Client::setPlayerItem(u16 item)
1354 {
1355         m_env.getLocalPlayer()->setWieldIndex(item);
1356         m_update_wielded_item = true;
1357
1358         NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1359         pkt << item;
1360         Send(&pkt);
1361 }
1362
1363 // Returns true once after the inventory of the local player
1364 // has been updated from the server.
1365 bool Client::updateWieldedItem()
1366 {
1367         if (!m_update_wielded_item)
1368                 return false;
1369
1370         m_update_wielded_item = false;
1371
1372         LocalPlayer *player = m_env.getLocalPlayer();
1373         assert(player);
1374         if (auto *list = player->inventory.getList("main"))
1375                 list->setModified(false);
1376         if (auto *list = player->inventory.getList("hand"))
1377                 list->setModified(false);
1378
1379         return true;
1380 }
1381
1382 Inventory* Client::getInventory(const InventoryLocation &loc)
1383 {
1384         switch(loc.type){
1385         case InventoryLocation::UNDEFINED:
1386         {}
1387         break;
1388         case InventoryLocation::CURRENT_PLAYER:
1389         {
1390                 LocalPlayer *player = m_env.getLocalPlayer();
1391                 assert(player);
1392                 return &player->inventory;
1393         }
1394         break;
1395         case InventoryLocation::PLAYER:
1396         {
1397                 // Check if we are working with local player inventory
1398                 LocalPlayer *player = m_env.getLocalPlayer();
1399                 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1400                         return NULL;
1401                 return &player->inventory;
1402         }
1403         break;
1404         case InventoryLocation::NODEMETA:
1405         {
1406                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1407                 if(!meta)
1408                         return NULL;
1409                 return meta->getInventory();
1410         }
1411         break;
1412         case InventoryLocation::DETACHED:
1413         {
1414                 if (m_detached_inventories.count(loc.name) == 0)
1415                         return NULL;
1416                 return m_detached_inventories[loc.name];
1417         }
1418         break;
1419         default:
1420                 FATAL_ERROR("Invalid inventory location type.");
1421                 break;
1422         }
1423         return NULL;
1424 }
1425
1426 void Client::inventoryAction(InventoryAction *a)
1427 {
1428         /*
1429                 Send it to the server
1430         */
1431         sendInventoryAction(a);
1432
1433         /*
1434                 Predict some local inventory changes
1435         */
1436         a->clientApply(this, this);
1437
1438         // Remove it
1439         delete a;
1440 }
1441
1442 float Client::getAnimationTime()
1443 {
1444         return m_animation_time;
1445 }
1446
1447 int Client::getCrackLevel()
1448 {
1449         return m_crack_level;
1450 }
1451
1452 v3s16 Client::getCrackPos()
1453 {
1454         return m_crack_pos;
1455 }
1456
1457 void Client::setCrack(int level, v3s16 pos)
1458 {
1459         int old_crack_level = m_crack_level;
1460         v3s16 old_crack_pos = m_crack_pos;
1461
1462         m_crack_level = level;
1463         m_crack_pos = pos;
1464
1465         if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1466         {
1467                 // remove old crack
1468                 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1469         }
1470         if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1471         {
1472                 // add new crack
1473                 addUpdateMeshTaskForNode(pos, false, true);
1474         }
1475 }
1476
1477 u16 Client::getHP()
1478 {
1479         LocalPlayer *player = m_env.getLocalPlayer();
1480         assert(player);
1481         return player->hp;
1482 }
1483
1484 bool Client::getChatMessage(std::wstring &res)
1485 {
1486         if (m_chat_queue.empty())
1487                 return false;
1488
1489         ChatMessage *chatMessage = m_chat_queue.front();
1490         m_chat_queue.pop();
1491
1492         res = L"";
1493
1494         switch (chatMessage->type) {
1495                 case CHATMESSAGE_TYPE_RAW:
1496                 case CHATMESSAGE_TYPE_ANNOUNCE:
1497                 case CHATMESSAGE_TYPE_SYSTEM:
1498                         res = chatMessage->message;
1499                         break;
1500                 case CHATMESSAGE_TYPE_NORMAL: {
1501                         if (!chatMessage->sender.empty())
1502                                 res = L"<" + chatMessage->sender + L"> " + chatMessage->message;
1503                         else
1504                                 res = chatMessage->message;
1505                         break;
1506                 }
1507                 default:
1508                         break;
1509         }
1510
1511         delete chatMessage;
1512         return true;
1513 }
1514
1515 void Client::typeChatMessage(const std::wstring &message)
1516 {
1517         // Discard empty line
1518         if (message.empty())
1519                 return;
1520
1521         // If message was consumed by script API, don't send it to server
1522         if (m_mods_loaded && m_script->on_sending_message(wide_to_utf8(message)))
1523                 return;
1524
1525         // Send to others
1526         sendChatMessage(message);
1527 }
1528
1529 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1530 {
1531         // Check if the block exists to begin with. In the case when a non-existing
1532         // neighbor is automatically added, it may not. In that case we don't want
1533         // to tell the mesh update thread about it.
1534         MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1535         if (b == NULL)
1536                 return;
1537
1538         m_mesh_update_thread.updateBlock(&m_env.getMap(), p, ack_to_server, urgent);
1539 }
1540
1541 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1542 {
1543         try{
1544                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1545         }
1546         catch(InvalidPositionException &e){}
1547
1548         // Leading edge
1549         for (int i=0;i<6;i++)
1550         {
1551                 try{
1552                         v3s16 p = blockpos + g_6dirs[i];
1553                         addUpdateMeshTask(p, false, urgent);
1554                 }
1555                 catch(InvalidPositionException &e){}
1556         }
1557 }
1558
1559 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1560 {
1561         {
1562                 v3s16 p = nodepos;
1563                 infostream<<"Client::addUpdateMeshTaskForNode(): "
1564                                 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1565                                 <<std::endl;
1566         }
1567
1568         v3s16 blockpos          = getNodeBlockPos(nodepos);
1569         v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1570
1571         try{
1572                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1573         }
1574         catch(InvalidPositionException &e) {}
1575
1576         // Leading edge
1577         if(nodepos.X == blockpos_relative.X){
1578                 try{
1579                         v3s16 p = blockpos + v3s16(-1,0,0);
1580                         addUpdateMeshTask(p, false, urgent);
1581                 }
1582                 catch(InvalidPositionException &e){}
1583         }
1584
1585         if(nodepos.Y == blockpos_relative.Y){
1586                 try{
1587                         v3s16 p = blockpos + v3s16(0,-1,0);
1588                         addUpdateMeshTask(p, false, urgent);
1589                 }
1590                 catch(InvalidPositionException &e){}
1591         }
1592
1593         if(nodepos.Z == blockpos_relative.Z){
1594                 try{
1595                         v3s16 p = blockpos + v3s16(0,0,-1);
1596                         addUpdateMeshTask(p, false, urgent);
1597                 }
1598                 catch(InvalidPositionException &e){}
1599         }
1600 }
1601
1602 ClientEvent *Client::getClientEvent()
1603 {
1604         FATAL_ERROR_IF(m_client_event_queue.empty(),
1605                         "Cannot getClientEvent, queue is empty.");
1606
1607         ClientEvent *event = m_client_event_queue.front();
1608         m_client_event_queue.pop();
1609         return event;
1610 }
1611
1612 bool Client::connectedToServer()
1613 {
1614         return m_con->Connected();
1615 }
1616
1617 const Address Client::getServerAddress()
1618 {
1619         return m_con->GetPeerAddress(PEER_ID_SERVER);
1620 }
1621
1622 float Client::mediaReceiveProgress()
1623 {
1624         if (m_media_downloader)
1625                 return m_media_downloader->getProgress();
1626
1627         return 1.0; // downloader only exists when not yet done
1628 }
1629
1630 typedef struct TextureUpdateArgs {
1631         gui::IGUIEnvironment *guienv;
1632         u64 last_time_ms;
1633         u16 last_percent;
1634         const wchar_t* text_base;
1635         ITextureSource *tsrc;
1636 } TextureUpdateArgs;
1637
1638 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1639 {
1640                 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1641                 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1642
1643                 // update the loading menu -- if neccessary
1644                 bool do_draw = false;
1645                 u64 time_ms = targs->last_time_ms;
1646                 if (cur_percent != targs->last_percent) {
1647                         targs->last_percent = cur_percent;
1648                         time_ms = porting::getTimeMs();
1649                         // only draw when the user will notice something:
1650                         do_draw = (time_ms - targs->last_time_ms > 100);
1651                 }
1652
1653                 if (do_draw) {
1654                         targs->last_time_ms = time_ms;
1655                         std::basic_stringstream<wchar_t> strm;
1656                         strm << targs->text_base << " " << targs->last_percent << "%...";
1657                         RenderingEngine::draw_load_screen(strm.str(), targs->guienv, targs->tsrc, 0,
1658                                 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true);
1659                 }
1660 }
1661
1662 void Client::afterContentReceived()
1663 {
1664         infostream<<"Client::afterContentReceived() started"<<std::endl;
1665         assert(m_itemdef_received); // pre-condition
1666         assert(m_nodedef_received); // pre-condition
1667         assert(mediaReceived()); // pre-condition
1668
1669         const wchar_t* text = wgettext("Loading textures...");
1670
1671         // Clear cached pre-scaled 2D GUI images, as this cache
1672         // might have images with the same name but different
1673         // content from previous sessions.
1674         guiScalingCacheClear();
1675
1676         // Rebuild inherited images and recreate textures
1677         infostream<<"- Rebuilding images and textures"<<std::endl;
1678         RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 70);
1679         m_tsrc->rebuildImagesAndTextures();
1680         delete[] text;
1681
1682         // Rebuild shaders
1683         infostream<<"- Rebuilding shaders"<<std::endl;
1684         text = wgettext("Rebuilding shaders...");
1685         RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 71);
1686         m_shsrc->rebuildShaders();
1687         delete[] text;
1688
1689         // Update node aliases
1690         infostream<<"- Updating node aliases"<<std::endl;
1691         text = wgettext("Initializing nodes...");
1692         RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 72);
1693         m_nodedef->updateAliases(m_itemdef);
1694         for (const auto &path : getTextureDirs())
1695                 m_nodedef->applyTextureOverrides(path + DIR_DELIM + "override.txt");
1696         m_nodedef->setNodeRegistrationStatus(true);
1697         m_nodedef->runNodeResolveCallbacks();
1698         delete[] text;
1699
1700         // Update node textures and assign shaders to each tile
1701         infostream<<"- Updating node textures"<<std::endl;
1702         TextureUpdateArgs tu_args;
1703         tu_args.guienv = guienv;
1704         tu_args.last_time_ms = porting::getTimeMs();
1705         tu_args.last_percent = 0;
1706         tu_args.text_base =  wgettext("Initializing nodes");
1707         tu_args.tsrc = m_tsrc;
1708         m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1709         delete[] tu_args.text_base;
1710
1711         // Start mesh update thread after setting up content definitions
1712         infostream<<"- Starting mesh update thread"<<std::endl;
1713         m_mesh_update_thread.start();
1714
1715         m_state = LC_Ready;
1716         sendReady();
1717
1718         if (m_mods_loaded)
1719                 m_script->on_client_ready(m_env.getLocalPlayer());
1720
1721         text = wgettext("Done!");
1722         RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 100);
1723         infostream<<"Client::afterContentReceived() done"<<std::endl;
1724         delete[] text;
1725 }
1726
1727 float Client::getRTT()
1728 {
1729         return m_con->getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1730 }
1731
1732 float Client::getCurRate()
1733 {
1734         return (m_con->getLocalStat(con::CUR_INC_RATE) +
1735                         m_con->getLocalStat(con::CUR_DL_RATE));
1736 }
1737
1738 void Client::makeScreenshot()
1739 {
1740         irr::video::IVideoDriver *driver = RenderingEngine::get_video_driver();
1741         irr::video::IImage* const raw_image = driver->createScreenShot();
1742
1743         if (!raw_image)
1744                 return;
1745
1746         time_t t = time(NULL);
1747         struct tm *tm = localtime(&t);
1748
1749         char timetstamp_c[64];
1750         strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1751
1752         std::string filename_base = g_settings->get("screenshot_path")
1753                         + DIR_DELIM
1754                         + std::string("screenshot_")
1755                         + std::string(timetstamp_c);
1756         std::string filename_ext = "." + g_settings->get("screenshot_format");
1757         std::string filename;
1758
1759         u32 quality = (u32)g_settings->getS32("screenshot_quality");
1760         quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1761
1762         // Try to find a unique filename
1763         unsigned serial = 0;
1764
1765         while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1766                 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1767                 std::ifstream tmp(filename.c_str());
1768                 if (!tmp.good())
1769                         break;  // File did not apparently exist, we'll go with it
1770                 serial++;
1771         }
1772
1773         if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1774                 infostream << "Could not find suitable filename for screenshot" << std::endl;
1775         } else {
1776                 irr::video::IImage* const image =
1777                                 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1778
1779                 if (image) {
1780                         raw_image->copyTo(image);
1781
1782                         std::ostringstream sstr;
1783                         if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1784                                 sstr << "Saved screenshot to '" << filename << "'";
1785                         } else {
1786                                 sstr << "Failed to save screenshot '" << filename << "'";
1787                         }
1788                         pushToChatQueue(new ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1789                                         narrow_to_wide(sstr.str())));
1790                         infostream << sstr.str() << std::endl;
1791                         image->drop();
1792                 }
1793         }
1794
1795         raw_image->drop();
1796 }
1797
1798 bool Client::shouldShowMinimap() const
1799 {
1800         return !m_minimap_disabled_by_server;
1801 }
1802
1803 void Client::pushToEventQueue(ClientEvent *event)
1804 {
1805         m_client_event_queue.push(event);
1806 }
1807
1808 void Client::showMinimap(const bool show)
1809 {
1810         m_game_ui->showMinimap(show);
1811 }
1812
1813 // IGameDef interface
1814 // Under envlock
1815 IItemDefManager* Client::getItemDefManager()
1816 {
1817         return m_itemdef;
1818 }
1819 const NodeDefManager* Client::getNodeDefManager()
1820 {
1821         return m_nodedef;
1822 }
1823 ICraftDefManager* Client::getCraftDefManager()
1824 {
1825         return NULL;
1826         //return m_craftdef;
1827 }
1828 ITextureSource* Client::getTextureSource()
1829 {
1830         return m_tsrc;
1831 }
1832 IShaderSource* Client::getShaderSource()
1833 {
1834         return m_shsrc;
1835 }
1836
1837 u16 Client::allocateUnknownNodeId(const std::string &name)
1838 {
1839         errorstream << "Client::allocateUnknownNodeId(): "
1840                         << "Client cannot allocate node IDs" << std::endl;
1841         FATAL_ERROR("Client allocated unknown node");
1842
1843         return CONTENT_IGNORE;
1844 }
1845 ISoundManager* Client::getSoundManager()
1846 {
1847         return m_sound;
1848 }
1849 MtEventManager* Client::getEventManager()
1850 {
1851         return m_event;
1852 }
1853
1854 ParticleManager* Client::getParticleManager()
1855 {
1856         return &m_particle_manager;
1857 }
1858
1859 scene::IAnimatedMesh* Client::getMesh(const std::string &filename, bool cache)
1860 {
1861         StringMap::const_iterator it = m_mesh_data.find(filename);
1862         if (it == m_mesh_data.end()) {
1863                 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1864                         << "\"" << std::endl;
1865                 return NULL;
1866         }
1867         const std::string &data    = it->second;
1868
1869         // Create the mesh, remove it from cache and return it
1870         // This allows unique vertex colors and other properties for each instance
1871         Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1872         io::IReadFile *rfile   = RenderingEngine::get_filesystem()->createMemoryReadFile(
1873                         *data_rw, data_rw.getSize(), filename.c_str());
1874         FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1875
1876         scene::IAnimatedMesh *mesh = RenderingEngine::get_scene_manager()->getMesh(rfile);
1877         rfile->drop();
1878         mesh->grab();
1879         if (!cache)
1880                 RenderingEngine::get_mesh_cache()->removeMesh(mesh);
1881         return mesh;
1882 }
1883
1884 const std::string* Client::getModFile(std::string filename)
1885 {
1886         // strip dir delimiter from beginning of path
1887         auto pos = filename.find_first_of(':');
1888         if (pos == std::string::npos)
1889                 return nullptr;
1890         pos++;
1891         auto pos2 = filename.find_first_not_of("/", pos);
1892         if (pos2 > pos)
1893                 filename.erase(pos, pos2 - pos);
1894
1895         StringMap::const_iterator it = m_mod_vfs.find(filename);
1896         if (it == m_mod_vfs.end())
1897                 return nullptr;
1898         return &it->second;
1899 }
1900
1901 bool Client::registerModStorage(ModMetadata *storage)
1902 {
1903         if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
1904                 errorstream << "Unable to register same mod storage twice. Storage name: "
1905                                 << storage->getModName() << std::endl;
1906                 return false;
1907         }
1908
1909         m_mod_storages[storage->getModName()] = storage;
1910         return true;
1911 }
1912
1913 void Client::unregisterModStorage(const std::string &name)
1914 {
1915         std::unordered_map<std::string, ModMetadata *>::const_iterator it =
1916                 m_mod_storages.find(name);
1917         if (it != m_mod_storages.end()) {
1918                 // Save unconditionaly on unregistration
1919                 it->second->save(getModStoragePath());
1920                 m_mod_storages.erase(name);
1921         }
1922 }
1923
1924 std::string Client::getModStoragePath() const
1925 {
1926         return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";
1927 }
1928
1929 /*
1930  * Mod channels
1931  */
1932
1933 bool Client::joinModChannel(const std::string &channel)
1934 {
1935         if (m_modchannel_mgr->channelRegistered(channel))
1936                 return false;
1937
1938         NetworkPacket pkt(TOSERVER_MODCHANNEL_JOIN, 2 + channel.size());
1939         pkt << channel;
1940         Send(&pkt);
1941
1942         m_modchannel_mgr->joinChannel(channel, 0);
1943         return true;
1944 }
1945
1946 bool Client::leaveModChannel(const std::string &channel)
1947 {
1948         if (!m_modchannel_mgr->channelRegistered(channel))
1949                 return false;
1950
1951         NetworkPacket pkt(TOSERVER_MODCHANNEL_LEAVE, 2 + channel.size());
1952         pkt << channel;
1953         Send(&pkt);
1954
1955         m_modchannel_mgr->leaveChannel(channel, 0);
1956         return true;
1957 }
1958
1959 bool Client::sendModChannelMessage(const std::string &channel, const std::string &message)
1960 {
1961         if (!m_modchannel_mgr->canWriteOnChannel(channel))
1962                 return false;
1963
1964         if (message.size() > STRING_MAX_LEN) {
1965                 warningstream << "ModChannel message too long, dropping before sending "
1966                                 << " (" << message.size() << " > " << STRING_MAX_LEN << ", channel: "
1967                                 << channel << ")" << std::endl;
1968                 return false;
1969         }
1970
1971         // @TODO: do some client rate limiting
1972         NetworkPacket pkt(TOSERVER_MODCHANNEL_MSG, 2 + channel.size() + 2 + message.size());
1973         pkt << channel << message;
1974         Send(&pkt);
1975         return true;
1976 }
1977
1978 ModChannel* Client::getModChannel(const std::string &channel)
1979 {
1980         return m_modchannel_mgr->getModChannel(channel);
1981 }