3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
24 #include <IFileSystem.h>
25 #include "threading/mutex_auto_lock.h"
26 #include "util/auth.h"
27 #include "util/directiontables.h"
28 #include "util/pointedthing.h"
29 #include "util/serialize.h"
30 #include "util/string.h"
33 #include "network/clientopcodes.h"
36 #include "mapblock_mesh.h"
43 #include "nodemetadata.h"
46 #include "clientmap.h"
47 #include "clientmedia.h"
49 #include "IMeshCache.h"
52 #include "drawscene.h"
53 #include "database-sqlite3.h"
54 #include "serialization.h"
55 #include "guiscalingfilter.h"
57 extern gui::IGUIEnvironment* guienv;
63 QueuedMeshUpdate::QueuedMeshUpdate():
66 ack_block_to_server(false)
70 QueuedMeshUpdate::~QueuedMeshUpdate()
80 MeshUpdateQueue::MeshUpdateQueue()
84 MeshUpdateQueue::~MeshUpdateQueue()
86 MutexAutoLock lock(m_mutex);
88 for(std::vector<QueuedMeshUpdate*>::iterator
90 i != m_queue.end(); ++i)
92 QueuedMeshUpdate *q = *i;
98 peer_id=0 adds with nobody to send to
100 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
102 DSTACK(FUNCTION_NAME);
104 assert(data); // pre-condition
106 MutexAutoLock lock(m_mutex);
112 Find if block is already in queue.
113 If it is, update the data and quit.
115 for(std::vector<QueuedMeshUpdate*>::iterator
117 i != m_queue.end(); ++i)
119 QueuedMeshUpdate *q = *i;
125 if(ack_block_to_server)
126 q->ack_block_to_server = true;
134 QueuedMeshUpdate *q = new QueuedMeshUpdate;
137 q->ack_block_to_server = ack_block_to_server;
138 m_queue.push_back(q);
141 // Returned pointer must be deleted
142 // Returns NULL if queue is empty
143 QueuedMeshUpdate *MeshUpdateQueue::pop()
145 MutexAutoLock lock(m_mutex);
147 bool must_be_urgent = !m_urgents.empty();
148 for(std::vector<QueuedMeshUpdate*>::iterator
150 i != m_queue.end(); ++i)
152 QueuedMeshUpdate *q = *i;
153 if(must_be_urgent && m_urgents.count(q->p) == 0)
156 m_urgents.erase(q->p);
166 void MeshUpdateThread::enqueueUpdate(v3s16 p, MeshMakeData *data,
167 bool ack_block_to_server, bool urgent)
169 m_queue_in.addBlock(p, data, ack_block_to_server, urgent);
173 void MeshUpdateThread::doUpdate()
176 while ((q = m_queue_in.pop())) {
178 ScopeProfiler sp(g_profiler, "Client: Mesh making");
180 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
185 r.ack_block_to_server = q->ack_block_to_server;
187 m_queue_out.push_back(r);
198 IrrlichtDevice *device,
199 const char *playername,
200 std::string password,
201 MapDrawControl &control,
202 IWritableTextureSource *tsrc,
203 IWritableShaderSource *shsrc,
204 IWritableItemDefManager *itemdef,
205 IWritableNodeDefManager *nodedef,
206 ISoundManager *sound,
207 MtEventManager *event,
210 m_packetcounter_timer(0.0),
211 m_connection_reinit_timer(0.1),
212 m_avg_rtt_timer(0.0),
213 m_playerpos_send_timer(0.0),
214 m_ignore_damage_timer(0.0),
221 m_mesh_update_thread(),
223 new ClientMap(this, this, control,
224 device->getSceneManager()->getRootSceneNode(),
225 device->getSceneManager(), 666),
226 device->getSceneManager(),
229 m_particle_manager(&m_env),
230 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
233 m_minimap_disabled_by_server(false),
234 m_server_ser_ver(SER_FMT_VER_INVALID),
237 m_inventory_updated(false),
238 m_inventory_from_server(NULL),
239 m_inventory_from_server_age(0.0),
244 m_password(password),
245 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
247 m_access_denied(false),
248 m_access_denied_reconnect(false),
249 m_itemdef_received(false),
250 m_nodedef_received(false),
251 m_media_downloader(new ClientMediaDownloader()),
252 m_time_of_day_set(false),
253 m_last_time_of_day_f(-1),
254 m_time_of_day_update_timer(0),
255 m_recommended_send_interval(0.1),
256 m_removed_sounds_check_timer(0),
261 m_env.setLocalPlayer(new LocalPlayer(this, playername));
263 m_mapper = new Mapper(device, this);
264 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
266 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
267 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
268 m_cache_use_tangent_vertices = m_cache_enable_shaders && (
269 g_settings->getBool("enable_bumpmapping") ||
270 g_settings->getBool("enable_parallax_occlusion"));
275 //request all client managed threads to stop
276 m_mesh_update_thread.stop();
277 // Save local server map
279 infostream << "Local map saving ended." << std::endl;
280 m_localdb->endSave();
284 bool Client::isShutdown()
287 if (!m_mesh_update_thread.isRunning()) return true;
296 m_mesh_update_thread.stop();
297 m_mesh_update_thread.wait();
298 while (!m_mesh_update_thread.m_queue_out.empty()) {
299 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
304 delete m_inventory_from_server;
306 // Delete detached inventories
307 for (UNORDERED_MAP<std::string, Inventory*>::iterator
308 i = m_detached_inventories.begin();
309 i != m_detached_inventories.end(); ++i) {
313 // cleanup 3d model meshes on client shutdown
314 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
315 scene::IAnimatedMesh *mesh =
316 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
319 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
325 void Client::connect(Address address,
326 const std::string &address_name,
327 bool is_local_server)
329 DSTACK(FUNCTION_NAME);
331 initLocalMapSaving(address, address_name, is_local_server);
333 m_con.SetTimeoutMs(0);
334 m_con.Connect(address);
337 void Client::step(float dtime)
339 DSTACK(FUNCTION_NAME);
345 if(m_ignore_damage_timer > dtime)
346 m_ignore_damage_timer -= dtime;
348 m_ignore_damage_timer = 0.0;
350 m_animation_time += dtime;
351 if(m_animation_time > 60.0)
352 m_animation_time -= 60.0;
354 m_time_of_day_update_timer += dtime;
362 float &counter = m_packetcounter_timer;
368 infostream << "Client packetcounter (" << m_packetcounter_timer
370 m_packetcounter.print(infostream);
371 m_packetcounter.clear();
375 // UGLY hack to fix 2 second startup delay caused by non existent
376 // server client startup synchronization in local server or singleplayer mode
377 static bool initial_step = true;
379 initial_step = false;
381 else if(m_state == LC_Created) {
382 float &counter = m_connection_reinit_timer;
387 LocalPlayer *myplayer = m_env.getLocalPlayer();
388 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
390 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
391 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
393 if (proto_version_min < 25) {
394 // Send TOSERVER_INIT_LEGACY
395 // [0] u16 TOSERVER_INIT_LEGACY
396 // [2] u8 SER_FMT_VER_HIGHEST_READ
397 // [3] u8[20] player_name
398 // [23] u8[28] password (new in some version)
399 // [51] u16 minimum supported network protocol version (added sometime)
400 // [53] u16 maximum supported network protocol version (added later than the previous one)
402 char pName[PLAYERNAME_SIZE];
403 char pPassword[PASSWORD_SIZE];
404 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
405 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
407 std::string hashed_password = translate_password(myplayer->getName(), m_password);
408 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
409 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
411 sendLegacyInit(pName, pPassword);
413 if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
414 sendInit(myplayer->getName());
417 // Not connected, return
422 Do stuff if connected
426 Run Map's timers and unload unused data
428 const float map_timer_and_unload_dtime = 5.25;
429 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
430 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
431 std::vector<v3s16> deleted_blocks;
432 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
433 g_settings->getFloat("client_unload_unused_data_timeout"),
434 g_settings->getS32("client_mapblock_limit"),
439 NOTE: This loop is intentionally iterated the way it is.
442 std::vector<v3s16>::iterator i = deleted_blocks.begin();
443 std::vector<v3s16> sendlist;
445 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
456 sendDeletedBlocks(sendlist);
458 if(i == deleted_blocks.end())
464 sendlist.push_back(*i);
472 // Control local player (0ms)
473 LocalPlayer *player = m_env.getLocalPlayer();
474 assert(player != NULL);
475 player->applyControl(dtime);
484 ClientEnvEvent event = m_env.getClientEvent();
485 if(event.type == CEE_NONE) {
488 else if(event.type == CEE_PLAYER_DAMAGE) {
489 if(m_ignore_damage_timer <= 0) {
490 u8 damage = event.player_damage.amount;
492 if(event.player_damage.send_to_server)
495 // Add to ClientEvent queue
497 event.type = CE_PLAYER_DAMAGE;
498 event.player_damage.amount = damage;
499 m_client_event_queue.push(event);
502 else if(event.type == CEE_PLAYER_BREATH) {
503 u16 breath = event.player_breath.amount;
511 float &counter = m_avg_rtt_timer;
515 // connectedAndInitialized() is true, peer exists.
516 float avg_rtt = getRTT();
517 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
521 Send player position to server
524 float &counter = m_playerpos_send_timer;
526 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
534 Replace updated meshes
537 int num_processed_meshes = 0;
538 while (!m_mesh_update_thread.m_queue_out.empty())
540 num_processed_meshes++;
542 MinimapMapblock *minimap_mapblock = NULL;
543 bool do_mapper_update = true;
545 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
546 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
548 // Delete the old mesh
549 if (block->mesh != NULL) {
555 minimap_mapblock = r.mesh->moveMinimapMapblock();
556 if (minimap_mapblock == NULL)
557 do_mapper_update = false;
560 if (r.mesh && r.mesh->getMesh()->getMeshBufferCount() == 0) {
563 // Replace with the new mesh
564 block->mesh = r.mesh;
570 if (do_mapper_update)
571 m_mapper->addBlock(r.p, minimap_mapblock);
573 if (r.ack_block_to_server) {
583 if (num_processed_meshes > 0)
584 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
590 if (m_media_downloader && m_media_downloader->isStarted()) {
591 m_media_downloader->step(this);
592 if (m_media_downloader->isDone()) {
594 delete m_media_downloader;
595 m_media_downloader = NULL;
600 If the server didn't update the inventory in a while, revert
601 the local inventory (so the player notices the lag problem
602 and knows something is wrong).
604 if(m_inventory_from_server)
606 float interval = 10.0;
607 float count_before = floor(m_inventory_from_server_age / interval);
609 m_inventory_from_server_age += dtime;
611 float count_after = floor(m_inventory_from_server_age / interval);
613 if(count_after != count_before)
615 // Do this every <interval> seconds after TOCLIENT_INVENTORY
616 // Reset the locally changed inventory to the authoritative inventory
617 LocalPlayer *player = m_env.getLocalPlayer();
618 player->inventory = *m_inventory_from_server;
619 m_inventory_updated = true;
624 Update positions of sounds attached to objects
627 for(UNORDERED_MAP<int, u16>::iterator i = m_sounds_to_objects.begin();
628 i != m_sounds_to_objects.end(); ++i) {
629 int client_id = i->first;
630 u16 object_id = i->second;
631 ClientActiveObject *cao = m_env.getActiveObject(object_id);
634 v3f pos = cao->getPosition();
635 m_sound->updateSoundPosition(client_id, pos);
640 Handle removed remotely initiated sounds
642 m_removed_sounds_check_timer += dtime;
643 if(m_removed_sounds_check_timer >= 2.32) {
644 m_removed_sounds_check_timer = 0;
645 // Find removed sounds and clear references to them
646 std::vector<s32> removed_server_ids;
647 for(UNORDERED_MAP<s32, int>::iterator i = m_sounds_server_to_client.begin();
648 i != m_sounds_server_to_client.end();) {
649 s32 server_id = i->first;
650 int client_id = i->second;
652 if(!m_sound->soundExists(client_id)) {
653 m_sounds_server_to_client.erase(server_id);
654 m_sounds_client_to_server.erase(client_id);
655 m_sounds_to_objects.erase(client_id);
656 removed_server_ids.push_back(server_id);
661 if(!removed_server_ids.empty()) {
662 sendRemovedSounds(removed_server_ids);
667 if (m_localdb && m_localdb_save_interval.step(dtime,
668 m_cache_save_interval)) {
669 m_localdb->endSave();
670 m_localdb->beginSave();
674 bool Client::loadMedia(const std::string &data, const std::string &filename)
676 // Silly irrlicht's const-incorrectness
677 Buffer<char> data_rw(data.c_str(), data.size());
681 const char *image_ext[] = {
682 ".png", ".jpg", ".bmp", ".tga",
683 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
686 name = removeStringEnd(filename, image_ext);
689 verbosestream<<"Client: Attempting to load image "
690 <<"file \""<<filename<<"\""<<std::endl;
692 io::IFileSystem *irrfs = m_device->getFileSystem();
693 video::IVideoDriver *vdrv = m_device->getVideoDriver();
695 // Create an irrlicht memory file
696 io::IReadFile *rfile = irrfs->createMemoryReadFile(
697 *data_rw, data_rw.getSize(), "_tempreadfile");
699 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
702 video::IImage *img = vdrv->createImageFromFile(rfile);
704 errorstream<<"Client: Cannot create image from data of "
705 <<"file \""<<filename<<"\""<<std::endl;
710 m_tsrc->insertSourceImage(filename, img);
717 const char *sound_ext[] = {
718 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
719 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
722 name = removeStringEnd(filename, sound_ext);
725 verbosestream<<"Client: Attempting to load sound "
726 <<"file \""<<filename<<"\""<<std::endl;
727 m_sound->loadSoundData(name, data);
731 const char *model_ext[] = {
732 ".x", ".b3d", ".md2", ".obj",
735 name = removeStringEnd(filename, model_ext);
738 verbosestream<<"Client: Storing model into memory: "
739 <<"\""<<filename<<"\""<<std::endl;
740 if(m_mesh_data.count(filename))
741 errorstream<<"Multiple models with name \""<<filename.c_str()
742 <<"\" found; replacing previous model"<<std::endl;
743 m_mesh_data[filename] = data;
747 errorstream<<"Client: Don't know how to load file \""
748 <<filename<<"\""<<std::endl;
752 // Virtual methods from con::PeerHandler
753 void Client::peerAdded(con::Peer *peer)
755 infostream << "Client::peerAdded(): peer->id="
756 << peer->id << std::endl;
758 void Client::deletingPeer(con::Peer *peer, bool timeout)
760 infostream << "Client::deletingPeer(): "
761 "Server Peer is getting deleted "
762 << "(timeout=" << timeout << ")" << std::endl;
765 m_access_denied = true;
766 m_access_denied_reason = gettext("Connection timed out.");
772 u16 number of files requested
778 void Client::request_media(const std::vector<std::string> &file_requests)
780 std::ostringstream os(std::ios_base::binary);
781 writeU16(os, TOSERVER_REQUEST_MEDIA);
782 size_t file_requests_size = file_requests.size();
784 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
786 // Packet dynamicly resized
787 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
789 pkt << (u16) (file_requests_size & 0xFFFF);
791 for(std::vector<std::string>::const_iterator i = file_requests.begin();
792 i != file_requests.end(); ++i) {
798 infostream << "Client: Sending media request list to server ("
799 << file_requests.size() << " files. packet size)" << std::endl;
802 void Client::received_media()
804 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
806 infostream << "Client: Notifying server that we received all media"
810 void Client::initLocalMapSaving(const Address &address,
811 const std::string &hostname,
812 bool is_local_server)
814 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
818 const std::string world_path = porting::path_user
819 + DIR_DELIM + "worlds"
820 + DIR_DELIM + "server_"
821 + hostname + "_" + std::to_string(address.getPort());
823 fs::CreateAllDirs(world_path);
825 m_localdb = new Database_SQLite3(world_path);
826 m_localdb->beginSave();
827 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
830 void Client::ReceiveAll()
832 DSTACK(FUNCTION_NAME);
833 u32 start_ms = porting::getTimeMs();
836 // Limit time even if there would be huge amounts of data to
838 if(porting::getTimeMs() > start_ms + 100)
843 g_profiler->graphAdd("client_received_packets", 1);
845 catch(con::NoIncomingDataException &e) {
848 catch(con::InvalidIncomingDataException &e) {
849 infostream<<"Client::ReceiveAll(): "
850 "InvalidIncomingDataException: what()="
851 <<e.what()<<std::endl;
856 void Client::Receive()
858 DSTACK(FUNCTION_NAME);
864 inline void Client::handleCommand(NetworkPacket* pkt)
866 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
867 (this->*opHandle.handler)(pkt);
871 sender_peer_id given to this shall be quaranteed to be a valid peer
873 void Client::ProcessData(NetworkPacket *pkt)
875 DSTACK(FUNCTION_NAME);
877 ToClientCommand command = (ToClientCommand) pkt->getCommand();
878 u32 sender_peer_id = pkt->getPeerId();
880 //infostream<<"Client: received command="<<command<<std::endl;
881 m_packetcounter.add((u16)command);
884 If this check is removed, be sure to change the queue
885 system to know the ids
887 if(sender_peer_id != PEER_ID_SERVER) {
888 infostream << "Client::ProcessData(): Discarding data not "
889 "coming from server: peer_id=" << sender_peer_id
894 // Command must be handled into ToClientCommandHandler
895 if (command >= TOCLIENT_NUM_MSG_TYPES) {
896 infostream << "Client: Ignoring unknown command "
897 << command << std::endl;
902 * Those packets are handled before m_server_ser_ver is set, it's normal
903 * But we must use the new ToClientConnectionState in the future,
906 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
911 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
912 infostream << "Client: Server serialization"
913 " format invalid or not initialized."
914 " Skipping incoming command=" << command << std::endl;
919 Handle runtime commands
925 void Client::Send(NetworkPacket* pkt)
927 m_con.Send(PEER_ID_SERVER,
928 serverCommandFactoryTable[pkt->getCommand()].channel,
930 serverCommandFactoryTable[pkt->getCommand()].reliable);
933 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
934 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
936 v3f pf = myplayer->getPosition() * 100;
937 v3f sf = myplayer->getSpeed() * 100;
938 s32 pitch = myplayer->getPitch() * 100;
939 s32 yaw = myplayer->getYaw() * 100;
940 u32 keyPressed = myplayer->keyPressed;
941 // scaled by 80, so that pi can fit into a u8
942 u8 fov = clientMap->getCameraFov() * 80;
943 u8 wanted_range = MYMIN(255,
944 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
946 v3s32 position(pf.X, pf.Y, pf.Z);
947 v3s32 speed(sf.X, sf.Y, sf.Z);
951 [0] v3s32 position*100
953 [12+12] s32 pitch*100
954 [12+12+4] s32 yaw*100
955 [12+12+4+4] u32 keyPressed
956 [12+12+4+4+4] u8 fov*80
957 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
959 *pkt << position << speed << pitch << yaw << keyPressed;
960 *pkt << fov << wanted_range;
963 void Client::interact(u8 action, const PointedThing& pointed)
965 if(m_state != LC_Ready) {
966 errorstream << "Client::interact() "
967 "Canceled (not connected)"
972 LocalPlayer *myplayer = m_env.getLocalPlayer();
973 if (myplayer == NULL)
980 [5] u32 length of the next item (plen)
981 [9] serialized PointedThing
982 [9 + plen] player position information
984 0: start digging (from undersurface) or use
985 1: stop digging (all parameters ignored)
987 3: place block or item (to abovesurface)
989 5: perform secondary action of item
992 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
995 pkt << (u16)getPlayerItem();
997 std::ostringstream tmp_os(std::ios::binary);
998 pointed.serialize(tmp_os);
1000 pkt.putLongString(tmp_os.str());
1002 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
1007 void Client::deleteAuthData()
1012 switch (m_chosen_auth_mech) {
1013 case AUTH_MECHANISM_FIRST_SRP:
1015 case AUTH_MECHANISM_SRP:
1016 case AUTH_MECHANISM_LEGACY_PASSWORD:
1017 srp_user_delete((SRPUser *) m_auth_data);
1020 case AUTH_MECHANISM_NONE:
1023 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
1027 AuthMechanism Client::choseAuthMech(const u32 mechs)
1029 if (mechs & AUTH_MECHANISM_SRP)
1030 return AUTH_MECHANISM_SRP;
1032 if (mechs & AUTH_MECHANISM_FIRST_SRP)
1033 return AUTH_MECHANISM_FIRST_SRP;
1035 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
1036 return AUTH_MECHANISM_LEGACY_PASSWORD;
1038 return AUTH_MECHANISM_NONE;
1041 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
1043 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
1044 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
1046 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1047 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1049 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
1050 pkt.putRawString(playerName,PLAYERNAME_SIZE);
1051 pkt.putRawString(playerPassword, PASSWORD_SIZE);
1052 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1057 void Client::sendInit(const std::string &playerName)
1059 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1061 // we don't support network compression yet
1062 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1064 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1065 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1067 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1068 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1074 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1076 m_chosen_auth_mech = chosen_auth_mechanism;
1078 switch (chosen_auth_mechanism) {
1079 case AUTH_MECHANISM_FIRST_SRP: {
1080 // send srp verifier to server
1081 std::string verifier;
1083 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1086 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1087 resp_pkt << salt << verifier << (u8)((m_password == "") ? 1 : 0);
1092 case AUTH_MECHANISM_SRP:
1093 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1096 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1097 m_password = translate_password(getPlayerName(), m_password);
1101 std::string playername_u = lowercase(getPlayerName());
1102 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1103 getPlayerName().c_str(), playername_u.c_str(),
1104 (const unsigned char *) m_password.c_str(),
1105 m_password.length(), NULL, NULL);
1108 SRP_Result res = srp_user_start_authentication(
1109 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1110 (unsigned char **) &bytes_A, &len_A);
1111 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1113 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1114 resp_pkt << std::string(bytes_A, len_A) << based_on;
1118 case AUTH_MECHANISM_NONE:
1119 break; // not handled in this method
1123 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1125 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1127 pkt << (u8) blocks.size();
1130 for(std::vector<v3s16>::iterator
1132 j != blocks.end(); ++j) {
1140 void Client::sendGotBlocks(v3s16 block)
1142 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1143 pkt << (u8) 1 << block;
1147 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1149 size_t server_ids = soundList.size();
1150 assert(server_ids <= 0xFFFF);
1152 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1154 pkt << (u16) (server_ids & 0xFFFF);
1156 for(std::vector<s32>::iterator i = soundList.begin();
1157 i != soundList.end(); ++i)
1163 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1164 const StringMap &fields)
1166 size_t fields_size = fields.size();
1168 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1170 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1172 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1174 StringMap::const_iterator it;
1175 for (it = fields.begin(); it != fields.end(); ++it) {
1176 const std::string &name = it->first;
1177 const std::string &value = it->second;
1179 pkt.putLongString(value);
1185 void Client::sendInventoryFields(const std::string &formname,
1186 const StringMap &fields)
1188 size_t fields_size = fields.size();
1189 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1191 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1192 pkt << formname << (u16) (fields_size & 0xFFFF);
1194 StringMap::const_iterator it;
1195 for (it = fields.begin(); it != fields.end(); ++it) {
1196 const std::string &name = it->first;
1197 const std::string &value = it->second;
1199 pkt.putLongString(value);
1205 void Client::sendInventoryAction(InventoryAction *a)
1207 std::ostringstream os(std::ios_base::binary);
1212 std::string s = os.str();
1214 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1215 pkt.putRawString(s.c_str(),s.size());
1220 void Client::sendChatMessage(const std::wstring &message)
1222 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1229 void Client::sendChangePassword(const std::string &oldpassword,
1230 const std::string &newpassword)
1232 LocalPlayer *player = m_env.getLocalPlayer();
1236 std::string playername = player->getName();
1237 if (m_proto_ver >= 25) {
1238 // get into sudo mode and then send new password to server
1239 m_password = oldpassword;
1240 m_new_password = newpassword;
1241 startAuth(choseAuthMech(m_sudo_auth_methods));
1243 std::string oldpwd = translate_password(playername, oldpassword);
1244 std::string newpwd = translate_password(playername, newpassword);
1246 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1248 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1249 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1252 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1253 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1260 void Client::sendDamage(u8 damage)
1262 DSTACK(FUNCTION_NAME);
1264 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1269 void Client::sendBreath(u16 breath)
1271 DSTACK(FUNCTION_NAME);
1273 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1278 void Client::sendRespawn()
1280 DSTACK(FUNCTION_NAME);
1282 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1286 void Client::sendReady()
1288 DSTACK(FUNCTION_NAME);
1290 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1291 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1293 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1294 << (u8) 0 << (u16) strlen(g_version_hash);
1296 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1300 void Client::sendPlayerPos()
1302 LocalPlayer *myplayer = m_env.getLocalPlayer();
1303 if(myplayer == NULL)
1306 ClientMap &map = m_env.getClientMap();
1308 u8 camera_fov = map.getCameraFov();
1309 u8 wanted_range = map.getControl().wanted_range;
1311 // Save bandwidth by only updating position when something changed
1312 if(myplayer->last_position == myplayer->getPosition() &&
1313 myplayer->last_speed == myplayer->getSpeed() &&
1314 myplayer->last_pitch == myplayer->getPitch() &&
1315 myplayer->last_yaw == myplayer->getYaw() &&
1316 myplayer->last_keyPressed == myplayer->keyPressed &&
1317 myplayer->last_camera_fov == camera_fov &&
1318 myplayer->last_wanted_range == wanted_range)
1321 myplayer->last_position = myplayer->getPosition();
1322 myplayer->last_speed = myplayer->getSpeed();
1323 myplayer->last_pitch = myplayer->getPitch();
1324 myplayer->last_yaw = myplayer->getYaw();
1325 myplayer->last_keyPressed = myplayer->keyPressed;
1326 myplayer->last_camera_fov = camera_fov;
1327 myplayer->last_wanted_range = wanted_range;
1329 //infostream << "Sending Player Position information" << std::endl;
1333 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1334 our_peer_id = m_con.GetPeerID();
1337 // Set peer id if not set already
1338 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1339 myplayer->peer_id = our_peer_id;
1341 assert(myplayer->peer_id == our_peer_id);
1343 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1345 writePlayerPos(myplayer, &map, &pkt);
1350 void Client::sendPlayerItem(u16 item)
1352 LocalPlayer *myplayer = m_env.getLocalPlayer();
1353 if(myplayer == NULL)
1356 u16 our_peer_id = m_con.GetPeerID();
1358 // Set peer id if not set already
1359 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1360 myplayer->peer_id = our_peer_id;
1361 assert(myplayer->peer_id == our_peer_id);
1363 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1370 void Client::removeNode(v3s16 p)
1372 std::map<v3s16, MapBlock*> modified_blocks;
1375 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1377 catch(InvalidPositionException &e) {
1380 for(std::map<v3s16, MapBlock *>::iterator
1381 i = modified_blocks.begin();
1382 i != modified_blocks.end(); ++i) {
1383 addUpdateMeshTaskWithEdge(i->first, false, true);
1387 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1389 //TimeTaker timer1("Client::addNode()");
1391 std::map<v3s16, MapBlock*> modified_blocks;
1394 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1395 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1397 catch(InvalidPositionException &e) {
1400 for(std::map<v3s16, MapBlock *>::iterator
1401 i = modified_blocks.begin();
1402 i != modified_blocks.end(); ++i) {
1403 addUpdateMeshTaskWithEdge(i->first, false, true);
1407 void Client::setPlayerControl(PlayerControl &control)
1409 LocalPlayer *player = m_env.getLocalPlayer();
1410 assert(player != NULL);
1411 player->control = control;
1414 void Client::selectPlayerItem(u16 item)
1416 m_playeritem = item;
1417 m_inventory_updated = true;
1418 sendPlayerItem(item);
1421 // Returns true if the inventory of the local player has been
1422 // updated from the server. If it is true, it is set to false.
1423 bool Client::getLocalInventoryUpdated()
1425 bool updated = m_inventory_updated;
1426 m_inventory_updated = false;
1430 // Copies the inventory of the local player to parameter
1431 void Client::getLocalInventory(Inventory &dst)
1433 LocalPlayer *player = m_env.getLocalPlayer();
1434 assert(player != NULL);
1435 dst = player->inventory;
1438 Inventory* Client::getInventory(const InventoryLocation &loc)
1441 case InventoryLocation::UNDEFINED:
1444 case InventoryLocation::CURRENT_PLAYER:
1446 LocalPlayer *player = m_env.getLocalPlayer();
1447 assert(player != NULL);
1448 return &player->inventory;
1451 case InventoryLocation::PLAYER:
1453 // Check if we are working with local player inventory
1454 LocalPlayer *player = m_env.getLocalPlayer();
1455 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1457 return &player->inventory;
1460 case InventoryLocation::NODEMETA:
1462 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1465 return meta->getInventory();
1468 case InventoryLocation::DETACHED:
1470 if (m_detached_inventories.count(loc.name) == 0)
1472 return m_detached_inventories[loc.name];
1476 FATAL_ERROR("Invalid inventory location type.");
1482 void Client::inventoryAction(InventoryAction *a)
1485 Send it to the server
1487 sendInventoryAction(a);
1490 Predict some local inventory changes
1492 a->clientApply(this, this);
1498 ClientActiveObject * Client::getSelectedActiveObject(
1500 v3f from_pos_f_on_map,
1501 core::line3d<f32> shootline_on_map
1504 std::vector<DistanceSortedActiveObject> objects;
1506 m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1509 // After this, the closest object is the first in the array.
1510 std::sort(objects.begin(), objects.end());
1512 for(unsigned int i=0; i<objects.size(); i++)
1514 ClientActiveObject *obj = objects[i].obj;
1516 aabb3f *selection_box = obj->getSelectionBox();
1517 if(selection_box == NULL)
1520 v3f pos = obj->getPosition();
1522 aabb3f offsetted_box(
1523 selection_box->MinEdge + pos,
1524 selection_box->MaxEdge + pos
1527 if(offsetted_box.intersectsWithLine(shootline_on_map))
1536 float Client::getAnimationTime()
1538 return m_animation_time;
1541 int Client::getCrackLevel()
1543 return m_crack_level;
1546 void Client::setCrack(int level, v3s16 pos)
1548 int old_crack_level = m_crack_level;
1549 v3s16 old_crack_pos = m_crack_pos;
1551 m_crack_level = level;
1554 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1557 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1559 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1562 addUpdateMeshTaskForNode(pos, false, true);
1568 LocalPlayer *player = m_env.getLocalPlayer();
1569 assert(player != NULL);
1573 bool Client::getChatMessage(std::wstring &message)
1575 if(m_chat_queue.size() == 0)
1577 message = m_chat_queue.front();
1582 void Client::typeChatMessage(const std::wstring &message)
1584 // Discard empty line
1589 sendChatMessage(message);
1592 if (message[0] == L'/')
1594 m_chat_queue.push((std::wstring)L"issued command: " + message);
1598 LocalPlayer *player = m_env.getLocalPlayer();
1599 assert(player != NULL);
1600 std::wstring name = narrow_to_wide(player->getName());
1601 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1605 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1607 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1612 Create a task to update the mesh of the block
1615 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders,
1616 m_cache_use_tangent_vertices);
1619 //TimeTaker timer("data fill");
1621 // Debug: 1-6ms, avg=2ms
1623 data->setCrack(m_crack_level, m_crack_pos);
1624 data->setSmoothLighting(m_cache_smooth_lighting);
1627 // Add task to queue
1628 m_mesh_update_thread.enqueueUpdate(p, data, ack_to_server, urgent);
1631 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1634 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1636 catch(InvalidPositionException &e){}
1639 for (int i=0;i<6;i++)
1642 v3s16 p = blockpos + g_6dirs[i];
1643 addUpdateMeshTask(p, false, urgent);
1645 catch(InvalidPositionException &e){}
1649 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1653 infostream<<"Client::addUpdateMeshTaskForNode(): "
1654 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1658 v3s16 blockpos = getNodeBlockPos(nodepos);
1659 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1662 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1664 catch(InvalidPositionException &e) {}
1667 if(nodepos.X == blockpos_relative.X){
1669 v3s16 p = blockpos + v3s16(-1,0,0);
1670 addUpdateMeshTask(p, false, urgent);
1672 catch(InvalidPositionException &e){}
1675 if(nodepos.Y == blockpos_relative.Y){
1677 v3s16 p = blockpos + v3s16(0,-1,0);
1678 addUpdateMeshTask(p, false, urgent);
1680 catch(InvalidPositionException &e){}
1683 if(nodepos.Z == blockpos_relative.Z){
1685 v3s16 p = blockpos + v3s16(0,0,-1);
1686 addUpdateMeshTask(p, false, urgent);
1688 catch(InvalidPositionException &e){}
1692 ClientEvent Client::getClientEvent()
1695 if (m_client_event_queue.empty()) {
1696 event.type = CE_NONE;
1699 event = m_client_event_queue.front();
1700 m_client_event_queue.pop();
1705 float Client::mediaReceiveProgress()
1707 if (m_media_downloader)
1708 return m_media_downloader->getProgress();
1710 return 1.0; // downloader only exists when not yet done
1713 typedef struct TextureUpdateArgs {
1714 IrrlichtDevice *device;
1715 gui::IGUIEnvironment *guienv;
1718 const wchar_t* text_base;
1719 } TextureUpdateArgs;
1721 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1723 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1724 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1726 // update the loading menu -- if neccessary
1727 bool do_draw = false;
1728 u32 time_ms = targs->last_time_ms;
1729 if (cur_percent != targs->last_percent) {
1730 targs->last_percent = cur_percent;
1731 time_ms = getTimeMs();
1732 // only draw when the user will notice something:
1733 do_draw = (time_ms - targs->last_time_ms > 100);
1737 targs->last_time_ms = time_ms;
1738 std::basic_stringstream<wchar_t> strm;
1739 strm << targs->text_base << " " << targs->last_percent << "%...";
1740 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1741 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1745 void Client::afterContentReceived(IrrlichtDevice *device)
1747 infostream<<"Client::afterContentReceived() started"<<std::endl;
1748 assert(m_itemdef_received); // pre-condition
1749 assert(m_nodedef_received); // pre-condition
1750 assert(mediaReceived()); // pre-condition
1752 const wchar_t* text = wgettext("Loading textures...");
1754 // Clear cached pre-scaled 2D GUI images, as this cache
1755 // might have images with the same name but different
1756 // content from previous sessions.
1757 guiScalingCacheClear(device->getVideoDriver());
1759 // Rebuild inherited images and recreate textures
1760 infostream<<"- Rebuilding images and textures"<<std::endl;
1761 draw_load_screen(text,device, guienv, 0, 70);
1762 m_tsrc->rebuildImagesAndTextures();
1766 infostream<<"- Rebuilding shaders"<<std::endl;
1767 text = wgettext("Rebuilding shaders...");
1768 draw_load_screen(text, device, guienv, 0, 71);
1769 m_shsrc->rebuildShaders();
1772 // Update node aliases
1773 infostream<<"- Updating node aliases"<<std::endl;
1774 text = wgettext("Initializing nodes...");
1775 draw_load_screen(text, device, guienv, 0, 72);
1776 m_nodedef->updateAliases(m_itemdef);
1777 std::string texture_path = g_settings->get("texture_path");
1778 if (texture_path != "" && fs::IsDir(texture_path))
1779 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1780 m_nodedef->setNodeRegistrationStatus(true);
1781 m_nodedef->runNodeResolveCallbacks();
1784 // Update node textures and assign shaders to each tile
1785 infostream<<"- Updating node textures"<<std::endl;
1786 TextureUpdateArgs tu_args;
1787 tu_args.device = device;
1788 tu_args.guienv = guienv;
1789 tu_args.last_time_ms = getTimeMs();
1790 tu_args.last_percent = 0;
1791 tu_args.text_base = wgettext("Initializing nodes");
1792 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1793 delete[] tu_args.text_base;
1795 // Start mesh update thread after setting up content definitions
1796 infostream<<"- Starting mesh update thread"<<std::endl;
1797 m_mesh_update_thread.start();
1801 text = wgettext("Done!");
1802 draw_load_screen(text, device, guienv, 0, 100);
1803 infostream<<"Client::afterContentReceived() done"<<std::endl;
1807 float Client::getRTT(void)
1809 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1812 float Client::getCurRate(void)
1814 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1815 m_con.getLocalStat(con::CUR_DL_RATE));
1818 float Client::getAvgRate(void)
1820 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1821 m_con.getLocalStat(con::AVG_DL_RATE));
1824 void Client::makeScreenshot(IrrlichtDevice *device)
1826 irr::video::IVideoDriver *driver = device->getVideoDriver();
1827 irr::video::IImage* const raw_image = driver->createScreenShot();
1832 time_t t = time(NULL);
1833 struct tm *tm = localtime(&t);
1835 char timetstamp_c[64];
1836 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1838 std::string filename_base = g_settings->get("screenshot_path")
1840 + std::string("screenshot_")
1841 + std::string(timetstamp_c);
1842 std::string filename_ext = "." + g_settings->get("screenshot_format");
1843 std::string filename;
1845 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1846 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1848 // Try to find a unique filename
1849 unsigned serial = 0;
1851 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1852 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1853 std::ifstream tmp(filename.c_str());
1855 break; // File did not apparently exist, we'll go with it
1859 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1860 infostream << "Could not find suitable filename for screenshot" << std::endl;
1862 irr::video::IImage* const image =
1863 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1866 raw_image->copyTo(image);
1868 std::ostringstream sstr;
1869 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1870 sstr << "Saved screenshot to '" << filename << "'";
1872 sstr << "Failed to save screenshot '" << filename << "'";
1874 m_chat_queue.push(narrow_to_wide(sstr.str()));
1875 infostream << sstr.str() << std::endl;
1883 // IGameDef interface
1885 IItemDefManager* Client::getItemDefManager()
1889 INodeDefManager* Client::getNodeDefManager()
1893 ICraftDefManager* Client::getCraftDefManager()
1896 //return m_craftdef;
1898 ITextureSource* Client::getTextureSource()
1902 IShaderSource* Client::getShaderSource()
1906 scene::ISceneManager* Client::getSceneManager()
1908 return m_device->getSceneManager();
1910 u16 Client::allocateUnknownNodeId(const std::string &name)
1912 errorstream << "Client::allocateUnknownNodeId(): "
1913 << "Client cannot allocate node IDs" << std::endl;
1914 FATAL_ERROR("Client allocated unknown node");
1916 return CONTENT_IGNORE;
1918 ISoundManager* Client::getSoundManager()
1922 MtEventManager* Client::getEventManager()
1927 ParticleManager* Client::getParticleManager()
1929 return &m_particle_manager;
1932 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1934 StringMap::const_iterator it = m_mesh_data.find(filename);
1935 if (it == m_mesh_data.end()) {
1936 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1937 << "\"" << std::endl;
1940 const std::string &data = it->second;
1941 scene::ISceneManager *smgr = m_device->getSceneManager();
1943 // Create the mesh, remove it from cache and return it
1944 // This allows unique vertex colors and other properties for each instance
1945 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1946 io::IFileSystem *irrfs = m_device->getFileSystem();
1947 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1948 *data_rw, data_rw.getSize(), filename.c_str());
1949 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1951 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1953 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1954 // of uniquely named instances and re-use them
1956 smgr->getMeshCache()->removeMesh(mesh);