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 = std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE);
945 v3s32 position(pf.X, pf.Y, pf.Z);
946 v3s32 speed(sf.X, sf.Y, sf.Z);
950 [0] v3s32 position*100
952 [12+12] s32 pitch*100
953 [12+12+4] s32 yaw*100
954 [12+12+4+4] u32 keyPressed
955 [12+12+4+4+4] u8 fov*80
956 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
958 *pkt << position << speed << pitch << yaw << keyPressed;
959 *pkt << fov << wanted_range;
962 void Client::interact(u8 action, const PointedThing& pointed)
964 if(m_state != LC_Ready) {
965 errorstream << "Client::interact() "
966 "Canceled (not connected)"
971 LocalPlayer *myplayer = m_env.getLocalPlayer();
972 if (myplayer == NULL)
979 [5] u32 length of the next item (plen)
980 [9] serialized PointedThing
981 [9 + plen] player position information
983 0: start digging (from undersurface) or use
984 1: stop digging (all parameters ignored)
986 3: place block or item (to abovesurface)
988 5: perform secondary action of item
991 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
994 pkt << (u16)getPlayerItem();
996 std::ostringstream tmp_os(std::ios::binary);
997 pointed.serialize(tmp_os);
999 pkt.putLongString(tmp_os.str());
1001 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
1006 void Client::deleteAuthData()
1011 switch (m_chosen_auth_mech) {
1012 case AUTH_MECHANISM_FIRST_SRP:
1014 case AUTH_MECHANISM_SRP:
1015 case AUTH_MECHANISM_LEGACY_PASSWORD:
1016 srp_user_delete((SRPUser *) m_auth_data);
1019 case AUTH_MECHANISM_NONE:
1022 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
1026 AuthMechanism Client::choseAuthMech(const u32 mechs)
1028 if (mechs & AUTH_MECHANISM_SRP)
1029 return AUTH_MECHANISM_SRP;
1031 if (mechs & AUTH_MECHANISM_FIRST_SRP)
1032 return AUTH_MECHANISM_FIRST_SRP;
1034 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
1035 return AUTH_MECHANISM_LEGACY_PASSWORD;
1037 return AUTH_MECHANISM_NONE;
1040 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
1042 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
1043 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
1045 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1046 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1048 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
1049 pkt.putRawString(playerName,PLAYERNAME_SIZE);
1050 pkt.putRawString(playerPassword, PASSWORD_SIZE);
1051 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1056 void Client::sendInit(const std::string &playerName)
1058 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1060 // we don't support network compression yet
1061 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1063 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1064 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1066 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1067 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1073 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1075 m_chosen_auth_mech = chosen_auth_mechanism;
1077 switch (chosen_auth_mechanism) {
1078 case AUTH_MECHANISM_FIRST_SRP: {
1079 // send srp verifier to server
1080 std::string verifier;
1082 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1085 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1086 resp_pkt << salt << verifier << (u8)((m_password == "") ? 1 : 0);
1091 case AUTH_MECHANISM_SRP:
1092 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1095 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1096 m_password = translate_password(getPlayerName(), m_password);
1100 std::string playername_u = lowercase(getPlayerName());
1101 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1102 getPlayerName().c_str(), playername_u.c_str(),
1103 (const unsigned char *) m_password.c_str(),
1104 m_password.length(), NULL, NULL);
1107 SRP_Result res = srp_user_start_authentication(
1108 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1109 (unsigned char **) &bytes_A, &len_A);
1110 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1112 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1113 resp_pkt << std::string(bytes_A, len_A) << based_on;
1117 case AUTH_MECHANISM_NONE:
1118 break; // not handled in this method
1122 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1124 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1126 pkt << (u8) blocks.size();
1129 for(std::vector<v3s16>::iterator
1131 j != blocks.end(); ++j) {
1139 void Client::sendGotBlocks(v3s16 block)
1141 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1142 pkt << (u8) 1 << block;
1146 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1148 size_t server_ids = soundList.size();
1149 assert(server_ids <= 0xFFFF);
1151 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1153 pkt << (u16) (server_ids & 0xFFFF);
1155 for(std::vector<s32>::iterator i = soundList.begin();
1156 i != soundList.end(); ++i)
1162 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1163 const StringMap &fields)
1165 size_t fields_size = fields.size();
1167 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1169 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1171 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1173 StringMap::const_iterator it;
1174 for (it = fields.begin(); it != fields.end(); ++it) {
1175 const std::string &name = it->first;
1176 const std::string &value = it->second;
1178 pkt.putLongString(value);
1184 void Client::sendInventoryFields(const std::string &formname,
1185 const StringMap &fields)
1187 size_t fields_size = fields.size();
1188 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1190 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1191 pkt << formname << (u16) (fields_size & 0xFFFF);
1193 StringMap::const_iterator it;
1194 for (it = fields.begin(); it != fields.end(); ++it) {
1195 const std::string &name = it->first;
1196 const std::string &value = it->second;
1198 pkt.putLongString(value);
1204 void Client::sendInventoryAction(InventoryAction *a)
1206 std::ostringstream os(std::ios_base::binary);
1211 std::string s = os.str();
1213 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1214 pkt.putRawString(s.c_str(),s.size());
1219 void Client::sendChatMessage(const std::wstring &message)
1221 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1228 void Client::sendChangePassword(const std::string &oldpassword,
1229 const std::string &newpassword)
1231 LocalPlayer *player = m_env.getLocalPlayer();
1235 std::string playername = player->getName();
1236 if (m_proto_ver >= 25) {
1237 // get into sudo mode and then send new password to server
1238 m_password = oldpassword;
1239 m_new_password = newpassword;
1240 startAuth(choseAuthMech(m_sudo_auth_methods));
1242 std::string oldpwd = translate_password(playername, oldpassword);
1243 std::string newpwd = translate_password(playername, newpassword);
1245 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1247 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1248 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1251 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1252 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1259 void Client::sendDamage(u8 damage)
1261 DSTACK(FUNCTION_NAME);
1263 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1268 void Client::sendBreath(u16 breath)
1270 DSTACK(FUNCTION_NAME);
1272 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1277 void Client::sendRespawn()
1279 DSTACK(FUNCTION_NAME);
1281 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1285 void Client::sendReady()
1287 DSTACK(FUNCTION_NAME);
1289 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1290 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1292 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1293 << (u8) 0 << (u16) strlen(g_version_hash);
1295 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1299 void Client::sendPlayerPos()
1301 LocalPlayer *myplayer = m_env.getLocalPlayer();
1302 if(myplayer == NULL)
1305 ClientMap &map = m_env.getClientMap();
1307 u8 camera_fov = map.getCameraFov();
1308 u8 wanted_range = map.getControl().wanted_range;
1310 // Save bandwidth by only updating position when something changed
1311 if(myplayer->last_position == myplayer->getPosition() &&
1312 myplayer->last_speed == myplayer->getSpeed() &&
1313 myplayer->last_pitch == myplayer->getPitch() &&
1314 myplayer->last_yaw == myplayer->getYaw() &&
1315 myplayer->last_keyPressed == myplayer->keyPressed &&
1316 myplayer->last_camera_fov == camera_fov &&
1317 myplayer->last_wanted_range == wanted_range)
1320 myplayer->last_position = myplayer->getPosition();
1321 myplayer->last_speed = myplayer->getSpeed();
1322 myplayer->last_pitch = myplayer->getPitch();
1323 myplayer->last_yaw = myplayer->getYaw();
1324 myplayer->last_keyPressed = myplayer->keyPressed;
1325 myplayer->last_camera_fov = camera_fov;
1326 myplayer->last_wanted_range = wanted_range;
1328 //infostream << "Sending Player Position information" << std::endl;
1332 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1333 our_peer_id = m_con.GetPeerID();
1336 // Set peer id if not set already
1337 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1338 myplayer->peer_id = our_peer_id;
1340 assert(myplayer->peer_id == our_peer_id);
1342 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1344 writePlayerPos(myplayer, &map, &pkt);
1349 void Client::sendPlayerItem(u16 item)
1351 LocalPlayer *myplayer = m_env.getLocalPlayer();
1352 if(myplayer == NULL)
1355 u16 our_peer_id = m_con.GetPeerID();
1357 // Set peer id if not set already
1358 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1359 myplayer->peer_id = our_peer_id;
1360 assert(myplayer->peer_id == our_peer_id);
1362 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1369 void Client::removeNode(v3s16 p)
1371 std::map<v3s16, MapBlock*> modified_blocks;
1374 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1376 catch(InvalidPositionException &e) {
1379 for(std::map<v3s16, MapBlock *>::iterator
1380 i = modified_blocks.begin();
1381 i != modified_blocks.end(); ++i) {
1382 addUpdateMeshTaskWithEdge(i->first, false, true);
1386 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1388 //TimeTaker timer1("Client::addNode()");
1390 std::map<v3s16, MapBlock*> modified_blocks;
1393 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1394 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1396 catch(InvalidPositionException &e) {
1399 for(std::map<v3s16, MapBlock *>::iterator
1400 i = modified_blocks.begin();
1401 i != modified_blocks.end(); ++i) {
1402 addUpdateMeshTaskWithEdge(i->first, false, true);
1406 void Client::setPlayerControl(PlayerControl &control)
1408 LocalPlayer *player = m_env.getLocalPlayer();
1409 assert(player != NULL);
1410 player->control = control;
1413 void Client::selectPlayerItem(u16 item)
1415 m_playeritem = item;
1416 m_inventory_updated = true;
1417 sendPlayerItem(item);
1420 // Returns true if the inventory of the local player has been
1421 // updated from the server. If it is true, it is set to false.
1422 bool Client::getLocalInventoryUpdated()
1424 bool updated = m_inventory_updated;
1425 m_inventory_updated = false;
1429 // Copies the inventory of the local player to parameter
1430 void Client::getLocalInventory(Inventory &dst)
1432 LocalPlayer *player = m_env.getLocalPlayer();
1433 assert(player != NULL);
1434 dst = player->inventory;
1437 Inventory* Client::getInventory(const InventoryLocation &loc)
1440 case InventoryLocation::UNDEFINED:
1443 case InventoryLocation::CURRENT_PLAYER:
1445 LocalPlayer *player = m_env.getLocalPlayer();
1446 assert(player != NULL);
1447 return &player->inventory;
1450 case InventoryLocation::PLAYER:
1452 // Check if we are working with local player inventory
1453 LocalPlayer *player = m_env.getLocalPlayer();
1454 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1456 return &player->inventory;
1459 case InventoryLocation::NODEMETA:
1461 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1464 return meta->getInventory();
1467 case InventoryLocation::DETACHED:
1469 if (m_detached_inventories.count(loc.name) == 0)
1471 return m_detached_inventories[loc.name];
1475 FATAL_ERROR("Invalid inventory location type.");
1481 void Client::inventoryAction(InventoryAction *a)
1484 Send it to the server
1486 sendInventoryAction(a);
1489 Predict some local inventory changes
1491 a->clientApply(this, this);
1497 ClientActiveObject * Client::getSelectedActiveObject(
1499 v3f from_pos_f_on_map,
1500 core::line3d<f32> shootline_on_map
1503 std::vector<DistanceSortedActiveObject> objects;
1505 m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1508 // After this, the closest object is the first in the array.
1509 std::sort(objects.begin(), objects.end());
1511 for(unsigned int i=0; i<objects.size(); i++)
1513 ClientActiveObject *obj = objects[i].obj;
1515 aabb3f *selection_box = obj->getSelectionBox();
1516 if(selection_box == NULL)
1519 v3f pos = obj->getPosition();
1521 aabb3f offsetted_box(
1522 selection_box->MinEdge + pos,
1523 selection_box->MaxEdge + pos
1526 if(offsetted_box.intersectsWithLine(shootline_on_map))
1535 float Client::getAnimationTime()
1537 return m_animation_time;
1540 int Client::getCrackLevel()
1542 return m_crack_level;
1545 void Client::setCrack(int level, v3s16 pos)
1547 int old_crack_level = m_crack_level;
1548 v3s16 old_crack_pos = m_crack_pos;
1550 m_crack_level = level;
1553 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1556 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1558 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1561 addUpdateMeshTaskForNode(pos, false, true);
1567 LocalPlayer *player = m_env.getLocalPlayer();
1568 assert(player != NULL);
1572 bool Client::getChatMessage(std::wstring &message)
1574 if(m_chat_queue.size() == 0)
1576 message = m_chat_queue.front();
1581 void Client::typeChatMessage(const std::wstring &message)
1583 // Discard empty line
1588 sendChatMessage(message);
1591 if (message[0] == L'/')
1593 m_chat_queue.push((std::wstring)L"issued command: " + message);
1597 LocalPlayer *player = m_env.getLocalPlayer();
1598 assert(player != NULL);
1599 std::wstring name = narrow_to_wide(player->getName());
1600 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1604 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1606 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1611 Create a task to update the mesh of the block
1614 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders,
1615 m_cache_use_tangent_vertices);
1618 //TimeTaker timer("data fill");
1620 // Debug: 1-6ms, avg=2ms
1622 data->setCrack(m_crack_level, m_crack_pos);
1623 data->setSmoothLighting(m_cache_smooth_lighting);
1626 // Add task to queue
1627 m_mesh_update_thread.enqueueUpdate(p, data, ack_to_server, urgent);
1630 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1633 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1635 catch(InvalidPositionException &e){}
1638 for (int i=0;i<6;i++)
1641 v3s16 p = blockpos + g_6dirs[i];
1642 addUpdateMeshTask(p, false, urgent);
1644 catch(InvalidPositionException &e){}
1648 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1652 infostream<<"Client::addUpdateMeshTaskForNode(): "
1653 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1657 v3s16 blockpos = getNodeBlockPos(nodepos);
1658 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1661 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1663 catch(InvalidPositionException &e) {}
1666 if(nodepos.X == blockpos_relative.X){
1668 v3s16 p = blockpos + v3s16(-1,0,0);
1669 addUpdateMeshTask(p, false, urgent);
1671 catch(InvalidPositionException &e){}
1674 if(nodepos.Y == blockpos_relative.Y){
1676 v3s16 p = blockpos + v3s16(0,-1,0);
1677 addUpdateMeshTask(p, false, urgent);
1679 catch(InvalidPositionException &e){}
1682 if(nodepos.Z == blockpos_relative.Z){
1684 v3s16 p = blockpos + v3s16(0,0,-1);
1685 addUpdateMeshTask(p, false, urgent);
1687 catch(InvalidPositionException &e){}
1691 ClientEvent Client::getClientEvent()
1694 if (m_client_event_queue.empty()) {
1695 event.type = CE_NONE;
1698 event = m_client_event_queue.front();
1699 m_client_event_queue.pop();
1704 float Client::mediaReceiveProgress()
1706 if (m_media_downloader)
1707 return m_media_downloader->getProgress();
1709 return 1.0; // downloader only exists when not yet done
1712 typedef struct TextureUpdateArgs {
1713 IrrlichtDevice *device;
1714 gui::IGUIEnvironment *guienv;
1717 const wchar_t* text_base;
1718 } TextureUpdateArgs;
1720 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1722 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1723 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1725 // update the loading menu -- if neccessary
1726 bool do_draw = false;
1727 u32 time_ms = targs->last_time_ms;
1728 if (cur_percent != targs->last_percent) {
1729 targs->last_percent = cur_percent;
1730 time_ms = getTimeMs();
1731 // only draw when the user will notice something:
1732 do_draw = (time_ms - targs->last_time_ms > 100);
1736 targs->last_time_ms = time_ms;
1737 std::basic_stringstream<wchar_t> strm;
1738 strm << targs->text_base << " " << targs->last_percent << "%...";
1739 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1740 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1744 void Client::afterContentReceived(IrrlichtDevice *device)
1746 infostream<<"Client::afterContentReceived() started"<<std::endl;
1747 assert(m_itemdef_received); // pre-condition
1748 assert(m_nodedef_received); // pre-condition
1749 assert(mediaReceived()); // pre-condition
1751 const wchar_t* text = wgettext("Loading textures...");
1753 // Clear cached pre-scaled 2D GUI images, as this cache
1754 // might have images with the same name but different
1755 // content from previous sessions.
1756 guiScalingCacheClear(device->getVideoDriver());
1758 // Rebuild inherited images and recreate textures
1759 infostream<<"- Rebuilding images and textures"<<std::endl;
1760 draw_load_screen(text,device, guienv, 0, 70);
1761 m_tsrc->rebuildImagesAndTextures();
1765 infostream<<"- Rebuilding shaders"<<std::endl;
1766 text = wgettext("Rebuilding shaders...");
1767 draw_load_screen(text, device, guienv, 0, 71);
1768 m_shsrc->rebuildShaders();
1771 // Update node aliases
1772 infostream<<"- Updating node aliases"<<std::endl;
1773 text = wgettext("Initializing nodes...");
1774 draw_load_screen(text, device, guienv, 0, 72);
1775 m_nodedef->updateAliases(m_itemdef);
1776 std::string texture_path = g_settings->get("texture_path");
1777 if (texture_path != "" && fs::IsDir(texture_path))
1778 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1779 m_nodedef->setNodeRegistrationStatus(true);
1780 m_nodedef->runNodeResolveCallbacks();
1783 // Update node textures and assign shaders to each tile
1784 infostream<<"- Updating node textures"<<std::endl;
1785 TextureUpdateArgs tu_args;
1786 tu_args.device = device;
1787 tu_args.guienv = guienv;
1788 tu_args.last_time_ms = getTimeMs();
1789 tu_args.last_percent = 0;
1790 tu_args.text_base = wgettext("Initializing nodes");
1791 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1792 delete[] tu_args.text_base;
1794 // Start mesh update thread after setting up content definitions
1795 infostream<<"- Starting mesh update thread"<<std::endl;
1796 m_mesh_update_thread.start();
1800 text = wgettext("Done!");
1801 draw_load_screen(text, device, guienv, 0, 100);
1802 infostream<<"Client::afterContentReceived() done"<<std::endl;
1806 float Client::getRTT(void)
1808 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1811 float Client::getCurRate(void)
1813 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1814 m_con.getLocalStat(con::CUR_DL_RATE));
1817 float Client::getAvgRate(void)
1819 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1820 m_con.getLocalStat(con::AVG_DL_RATE));
1823 void Client::makeScreenshot(IrrlichtDevice *device)
1825 irr::video::IVideoDriver *driver = device->getVideoDriver();
1826 irr::video::IImage* const raw_image = driver->createScreenShot();
1831 time_t t = time(NULL);
1832 struct tm *tm = localtime(&t);
1834 char timetstamp_c[64];
1835 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1837 std::string filename_base = g_settings->get("screenshot_path")
1839 + std::string("screenshot_")
1840 + std::string(timetstamp_c);
1841 std::string filename_ext = "." + g_settings->get("screenshot_format");
1842 std::string filename;
1844 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1845 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1847 // Try to find a unique filename
1848 unsigned serial = 0;
1850 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1851 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1852 std::ifstream tmp(filename.c_str());
1854 break; // File did not apparently exist, we'll go with it
1858 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1859 infostream << "Could not find suitable filename for screenshot" << std::endl;
1861 irr::video::IImage* const image =
1862 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1865 raw_image->copyTo(image);
1867 std::ostringstream sstr;
1868 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1869 sstr << "Saved screenshot to '" << filename << "'";
1871 sstr << "Failed to save screenshot '" << filename << "'";
1873 m_chat_queue.push(narrow_to_wide(sstr.str()));
1874 infostream << sstr.str() << std::endl;
1882 // IGameDef interface
1884 IItemDefManager* Client::getItemDefManager()
1888 INodeDefManager* Client::getNodeDefManager()
1892 ICraftDefManager* Client::getCraftDefManager()
1895 //return m_craftdef;
1897 ITextureSource* Client::getTextureSource()
1901 IShaderSource* Client::getShaderSource()
1905 scene::ISceneManager* Client::getSceneManager()
1907 return m_device->getSceneManager();
1909 u16 Client::allocateUnknownNodeId(const std::string &name)
1911 errorstream << "Client::allocateUnknownNodeId(): "
1912 << "Client cannot allocate node IDs" << std::endl;
1913 FATAL_ERROR("Client allocated unknown node");
1915 return CONTENT_IGNORE;
1917 ISoundManager* Client::getSoundManager()
1921 MtEventManager* Client::getEventManager()
1926 ParticleManager* Client::getParticleManager()
1928 return &m_particle_manager;
1931 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1933 StringMap::const_iterator it = m_mesh_data.find(filename);
1934 if (it == m_mesh_data.end()) {
1935 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1936 << "\"" << std::endl;
1939 const std::string &data = it->second;
1940 scene::ISceneManager *smgr = m_device->getSceneManager();
1942 // Create the mesh, remove it from cache and return it
1943 // This allows unique vertex colors and other properties for each instance
1944 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1945 io::IFileSystem *irrfs = m_device->getFileSystem();
1946 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1947 *data_rw, data_rw.getSize(), filename.c_str());
1948 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1950 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1952 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1953 // of uniquely named instances and re-use them
1955 smgr->getMeshCache()->removeMesh(mesh);