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.
23 #include <IFileSystem.h>
24 #include "jthread/jmutexautolock.h"
25 #include "util/directiontables.h"
26 #include "util/pointedthing.h"
27 #include "util/serialize.h"
28 #include "util/string.h"
30 #include "network/clientopcodes.h"
34 #include "mapblock_mesh.h"
40 #include "nodemetadata.h"
43 #include "clientmap.h"
44 #include "clientmedia.h"
46 #include "IMeshCache.h"
49 #include "drawscene.h"
50 #include "database-sqlite3.h"
51 #include "serialization.h"
53 extern gui::IGUIEnvironment* guienv;
59 QueuedMeshUpdate::QueuedMeshUpdate():
62 ack_block_to_server(false)
66 QueuedMeshUpdate::~QueuedMeshUpdate()
76 MeshUpdateQueue::MeshUpdateQueue()
80 MeshUpdateQueue::~MeshUpdateQueue()
82 JMutexAutoLock lock(m_mutex);
84 for(std::vector<QueuedMeshUpdate*>::iterator
86 i != m_queue.end(); i++)
88 QueuedMeshUpdate *q = *i;
94 peer_id=0 adds with nobody to send to
96 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
98 DSTACK(__FUNCTION_NAME);
100 assert(data); // pre-condition
102 JMutexAutoLock lock(m_mutex);
108 Find if block is already in queue.
109 If it is, update the data and quit.
111 for(std::vector<QueuedMeshUpdate*>::iterator
113 i != m_queue.end(); i++)
115 QueuedMeshUpdate *q = *i;
121 if(ack_block_to_server)
122 q->ack_block_to_server = true;
130 QueuedMeshUpdate *q = new QueuedMeshUpdate;
133 q->ack_block_to_server = ack_block_to_server;
134 m_queue.push_back(q);
137 // Returned pointer must be deleted
138 // Returns NULL if queue is empty
139 QueuedMeshUpdate * MeshUpdateQueue::pop()
141 JMutexAutoLock lock(m_mutex);
143 bool must_be_urgent = !m_urgents.empty();
144 for(std::vector<QueuedMeshUpdate*>::iterator
146 i != m_queue.end(); i++)
148 QueuedMeshUpdate *q = *i;
149 if(must_be_urgent && m_urgents.count(q->p) == 0)
152 m_urgents.erase(q->p);
162 void * MeshUpdateThread::Thread()
166 log_register_thread("MeshUpdateThread");
168 DSTACK(__FUNCTION_NAME);
170 BEGIN_DEBUG_EXCEPTION_HANDLER
172 porting::setThreadName("MeshUpdateThread");
174 while(!StopRequested())
176 QueuedMeshUpdate *q = m_queue_in.pop();
183 ScopeProfiler sp(g_profiler, "Client: Mesh making");
185 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
186 if(mesh_new->getMesh()->getMeshBufferCount() == 0)
195 r.ack_block_to_server = q->ack_block_to_server;
197 m_queue_out.push_back(r);
202 END_DEBUG_EXCEPTION_HANDLER(errorstream)
212 IrrlichtDevice *device,
213 const char *playername,
214 std::string password,
215 MapDrawControl &control,
216 IWritableTextureSource *tsrc,
217 IWritableShaderSource *shsrc,
218 IWritableItemDefManager *itemdef,
219 IWritableNodeDefManager *nodedef,
220 ISoundManager *sound,
221 MtEventManager *event,
224 m_packetcounter_timer(0.0),
225 m_connection_reinit_timer(0.1),
226 m_avg_rtt_timer(0.0),
227 m_playerpos_send_timer(0.0),
228 m_ignore_damage_timer(0.0),
235 m_mesh_update_thread(this),
237 new ClientMap(this, this, control,
238 device->getSceneManager()->getRootSceneNode(),
239 device->getSceneManager(), 666),
240 device->getSceneManager(),
243 m_particle_manager(&m_env),
244 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
246 m_server_ser_ver(SER_FMT_VER_INVALID),
248 m_inventory_updated(false),
249 m_inventory_from_server(NULL),
250 m_inventory_from_server_age(0.0),
251 m_show_highlighted(false),
255 m_highlighted_pos(0,0,0),
257 m_password(password),
258 m_access_denied(false),
259 m_itemdef_received(false),
260 m_nodedef_received(false),
261 m_media_downloader(new ClientMediaDownloader()),
262 m_time_of_day_set(false),
263 m_last_time_of_day_f(-1),
264 m_time_of_day_update_timer(0),
265 m_recommended_send_interval(0.1),
266 m_removed_sounds_check_timer(0),
271 m_env.addPlayer(new LocalPlayer(this, playername));
273 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
275 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
276 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
281 //request all client managed threads to stop
282 m_mesh_update_thread.Stop();
283 // Save local server map
285 infostream << "Local map saving ended." << std::endl;
286 m_localdb->endSave();
290 bool Client::isShutdown()
293 if (!m_mesh_update_thread.IsRunning()) return true;
302 m_mesh_update_thread.Stop();
303 m_mesh_update_thread.Wait();
304 while(!m_mesh_update_thread.m_queue_out.empty()) {
305 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
310 delete m_inventory_from_server;
312 // Delete detached inventories
313 for(std::map<std::string, Inventory*>::iterator
314 i = m_detached_inventories.begin();
315 i != m_detached_inventories.end(); i++){
319 // cleanup 3d model meshes on client shutdown
320 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
321 scene::IAnimatedMesh * mesh =
322 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
325 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
329 void Client::connect(Address address,
330 const std::string &address_name,
331 bool is_local_server)
333 DSTACK(__FUNCTION_NAME);
335 initLocalMapSaving(address, address_name, is_local_server);
337 m_con.SetTimeoutMs(0);
338 m_con.Connect(address);
341 void Client::step(float dtime)
343 DSTACK(__FUNCTION_NAME);
349 if(m_ignore_damage_timer > dtime)
350 m_ignore_damage_timer -= dtime;
352 m_ignore_damage_timer = 0.0;
354 m_animation_time += dtime;
355 if(m_animation_time > 60.0)
356 m_animation_time -= 60.0;
358 m_time_of_day_update_timer += dtime;
366 float &counter = m_packetcounter_timer;
372 infostream << "Client packetcounter (" << m_packetcounter_timer
374 m_packetcounter.print(infostream);
375 m_packetcounter.clear();
379 // UGLY hack to fix 2 second startup delay caused by non existent
380 // server client startup synchronization in local server or singleplayer mode
381 static bool initial_step = true;
383 initial_step = false;
385 else if(m_state == LC_Created) {
386 float &counter = m_connection_reinit_timer;
391 Player *myplayer = m_env.getLocalPlayer();
392 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
394 // Send TOSERVER_INIT
395 // [0] u16 TOSERVER_INIT
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 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
408 snprintf(pPassword, PASSWORD_SIZE, "%s", m_password.c_str());
410 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
411 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
413 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
414 pkt.putRawString(pName,PLAYERNAME_SIZE);
415 pkt.putRawString(pPassword, PASSWORD_SIZE);
416 pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
421 // Not connected, return
426 Do stuff if connected
430 Run Map's timers and unload unused data
432 const float map_timer_and_unload_dtime = 5.25;
433 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
434 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
435 std::vector<v3s16> deleted_blocks;
436 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
437 g_settings->getFloat("client_unload_unused_data_timeout"),
442 NOTE: This loop is intentionally iterated the way it is.
445 std::vector<v3s16>::iterator i = deleted_blocks.begin();
446 std::vector<v3s16> sendlist;
448 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
458 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * sendlist.size());
460 pkt << (u8) sendlist.size();
463 for(std::vector<v3s16>::iterator
464 j = sendlist.begin();
465 j != sendlist.end(); ++j) {
472 if(i == deleted_blocks.end())
478 sendlist.push_back(*i);
486 // Control local player (0ms)
487 LocalPlayer *player = m_env.getLocalPlayer();
488 assert(player != NULL);
489 player->applyControl(dtime);
498 ClientEnvEvent event = m_env.getClientEvent();
499 if(event.type == CEE_NONE) {
502 else if(event.type == CEE_PLAYER_DAMAGE) {
503 if(m_ignore_damage_timer <= 0) {
504 u8 damage = event.player_damage.amount;
506 if(event.player_damage.send_to_server)
509 // Add to ClientEvent queue
511 event.type = CE_PLAYER_DAMAGE;
512 event.player_damage.amount = damage;
513 m_client_event_queue.push(event);
516 else if(event.type == CEE_PLAYER_BREATH) {
517 u16 breath = event.player_breath.amount;
525 float &counter = m_avg_rtt_timer;
529 // connectedAndInitialized() is true, peer exists.
530 float avg_rtt = getRTT();
531 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
535 Send player position to server
538 float &counter = m_playerpos_send_timer;
540 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
548 Replace updated meshes
551 int num_processed_meshes = 0;
552 while(!m_mesh_update_thread.m_queue_out.empty())
554 num_processed_meshes++;
555 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
556 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
558 // Delete the old mesh
559 if(block->mesh != NULL)
561 // TODO: Remove hardware buffers of meshbuffers of block->mesh
566 // Replace with the new mesh
567 block->mesh = r.mesh;
572 if(r.ack_block_to_server) {
578 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
579 pkt << (u8) 1 << r.p;
584 if(num_processed_meshes > 0)
585 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
591 if (m_media_downloader && m_media_downloader->isStarted()) {
592 m_media_downloader->step(this);
593 if (m_media_downloader->isDone()) {
595 delete m_media_downloader;
596 m_media_downloader = NULL;
601 If the server didn't update the inventory in a while, revert
602 the local inventory (so the player notices the lag problem
603 and knows something is wrong).
605 if(m_inventory_from_server)
607 float interval = 10.0;
608 float count_before = floor(m_inventory_from_server_age / interval);
610 m_inventory_from_server_age += dtime;
612 float count_after = floor(m_inventory_from_server_age / interval);
614 if(count_after != count_before)
616 // Do this every <interval> seconds after TOCLIENT_INVENTORY
617 // Reset the locally changed inventory to the authoritative inventory
618 Player *player = m_env.getLocalPlayer();
619 player->inventory = *m_inventory_from_server;
620 m_inventory_updated = true;
625 Update positions of sounds attached to objects
628 for(std::map<int, u16>::iterator
629 i = m_sounds_to_objects.begin();
630 i != m_sounds_to_objects.end(); i++)
632 int client_id = i->first;
633 u16 object_id = i->second;
634 ClientActiveObject *cao = m_env.getActiveObject(object_id);
637 v3f pos = cao->getPosition();
638 m_sound->updateSoundPosition(client_id, pos);
643 Handle removed remotely initiated sounds
645 m_removed_sounds_check_timer += dtime;
646 if(m_removed_sounds_check_timer >= 2.32) {
647 m_removed_sounds_check_timer = 0;
648 // Find removed sounds and clear references to them
649 std::set<s32> removed_server_ids;
650 for(std::map<s32, int>::iterator
651 i = m_sounds_server_to_client.begin();
652 i != m_sounds_server_to_client.end();) {
653 s32 server_id = i->first;
654 int client_id = i->second;
656 if(!m_sound->soundExists(client_id)) {
657 m_sounds_server_to_client.erase(server_id);
658 m_sounds_client_to_server.erase(client_id);
659 m_sounds_to_objects.erase(client_id);
660 removed_server_ids.insert(server_id);
665 if(!removed_server_ids.empty()) {
666 size_t server_ids = removed_server_ids.size();
667 assert(server_ids <= 0xFFFF);
669 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
671 pkt << (u16) (server_ids & 0xFFFF);
673 for(std::set<s32>::iterator i = removed_server_ids.begin();
674 i != removed_server_ids.end(); i++)
682 if (m_localdb && m_localdb_save_interval.step(dtime,
683 m_cache_save_interval)) {
684 m_localdb->endSave();
685 m_localdb->beginSave();
689 bool Client::loadMedia(const std::string &data, const std::string &filename)
691 // Silly irrlicht's const-incorrectness
692 Buffer<char> data_rw(data.c_str(), data.size());
696 const char *image_ext[] = {
697 ".png", ".jpg", ".bmp", ".tga",
698 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
701 name = removeStringEnd(filename, image_ext);
704 verbosestream<<"Client: Attempting to load image "
705 <<"file \""<<filename<<"\""<<std::endl;
707 io::IFileSystem *irrfs = m_device->getFileSystem();
708 video::IVideoDriver *vdrv = m_device->getVideoDriver();
710 // Create an irrlicht memory file
711 io::IReadFile *rfile = irrfs->createMemoryReadFile(
712 *data_rw, data_rw.getSize(), "_tempreadfile");
714 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
717 video::IImage *img = vdrv->createImageFromFile(rfile);
719 errorstream<<"Client: Cannot create image from data of "
720 <<"file \""<<filename<<"\""<<std::endl;
725 m_tsrc->insertSourceImage(filename, img);
732 const char *sound_ext[] = {
733 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
734 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
737 name = removeStringEnd(filename, sound_ext);
740 verbosestream<<"Client: Attempting to load sound "
741 <<"file \""<<filename<<"\""<<std::endl;
742 m_sound->loadSoundData(name, data);
746 const char *model_ext[] = {
747 ".x", ".b3d", ".md2", ".obj",
750 name = removeStringEnd(filename, model_ext);
753 verbosestream<<"Client: Storing model into memory: "
754 <<"\""<<filename<<"\""<<std::endl;
755 if(m_mesh_data.count(filename))
756 errorstream<<"Multiple models with name \""<<filename.c_str()
757 <<"\" found; replacing previous model"<<std::endl;
758 m_mesh_data[filename] = data;
762 errorstream<<"Client: Don't know how to load file \""
763 <<filename<<"\""<<std::endl;
767 // Virtual methods from con::PeerHandler
768 void Client::peerAdded(con::Peer *peer)
770 infostream<<"Client::peerAdded(): peer->id="
771 <<peer->id<<std::endl;
773 void Client::deletingPeer(con::Peer *peer, bool timeout)
775 infostream<<"Client::deletingPeer(): "
776 "Server Peer is getting deleted "
777 <<"(timeout="<<timeout<<")"<<std::endl;
782 u16 number of files requested
788 void Client::request_media(const std::vector<std::string> &file_requests)
790 std::ostringstream os(std::ios_base::binary);
791 writeU16(os, TOSERVER_REQUEST_MEDIA);
792 size_t file_requests_size = file_requests.size();
794 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
796 // Packet dynamicly resized
797 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
799 pkt << (u16) (file_requests_size & 0xFFFF);
801 for(std::vector<std::string>::const_iterator i = file_requests.begin();
802 i != file_requests.end(); ++i) {
808 infostream << "Client: Sending media request list to server ("
809 << file_requests.size() << " files. packet size)" << std::endl;
812 void Client::received_media()
814 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
816 infostream << "Client: Notifying server that we received all media"
820 void Client::initLocalMapSaving(const Address &address,
821 const std::string &hostname,
822 bool is_local_server)
824 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
828 const std::string world_path = porting::path_user
829 + DIR_DELIM + "worlds"
830 + DIR_DELIM + "server_"
831 + hostname + "_" + to_string(address.getPort());
833 fs::CreateAllDirs(world_path);
835 m_localdb = new Database_SQLite3(world_path);
836 m_localdb->beginSave();
837 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
840 void Client::ReceiveAll()
842 DSTACK(__FUNCTION_NAME);
843 u32 start_ms = porting::getTimeMs();
846 // Limit time even if there would be huge amounts of data to
848 if(porting::getTimeMs() > start_ms + 100)
853 g_profiler->graphAdd("client_received_packets", 1);
855 catch(con::NoIncomingDataException &e) {
858 catch(con::InvalidIncomingDataException &e) {
859 infostream<<"Client::ReceiveAll(): "
860 "InvalidIncomingDataException: what()="
861 <<e.what()<<std::endl;
866 void Client::Receive()
868 DSTACK(__FUNCTION_NAME);
869 SharedBuffer<u8> data;
871 u32 datasize = m_con.Receive(sender_peer_id, data);
872 ProcessData(*data, datasize, sender_peer_id);
875 inline void Client::handleCommand(NetworkPacket* pkt)
877 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
878 (this->*opHandle.handler)(pkt);
882 sender_peer_id given to this shall be quaranteed to be a valid peer
884 void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
886 DSTACK(__FUNCTION_NAME);
888 // Ignore packets that don't even fit a command
890 m_packetcounter.add(60000);
894 NetworkPacket pkt(data, datasize, sender_peer_id);
896 ToClientCommand command = (ToClientCommand) pkt.getCommand();
898 //infostream<<"Client: received command="<<command<<std::endl;
899 m_packetcounter.add((u16)command);
902 If this check is removed, be sure to change the queue
903 system to know the ids
905 if(sender_peer_id != PEER_ID_SERVER) {
906 infostream << "Client::ProcessData(): Discarding data not "
907 "coming from server: peer_id=" << sender_peer_id
912 // Command must be handled into ToClientCommandHandler
913 if (command >= TOCLIENT_NUM_MSG_TYPES) {
914 infostream << "Client: Ignoring unknown command "
915 << command << std::endl;
919 * Those packets are handled before m_server_ser_ver is set, it's normal
920 * But we must use the new ToClientConnectionState in the future,
923 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
928 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
929 infostream << "Client: Server serialization"
930 " format invalid or not initialized."
931 " Skipping incoming command=" << command << std::endl;
936 Handle runtime commands
942 void Client::Send(NetworkPacket* pkt)
944 m_con.Send(PEER_ID_SERVER,
945 serverCommandFactoryTable[pkt->getCommand()].channel,
947 serverCommandFactoryTable[pkt->getCommand()].reliable);
950 void Client::interact(u8 action, const PointedThing& pointed)
952 if(m_state != LC_Ready) {
953 errorstream << "Client::interact() "
954 "Canceled (not connected)"
963 [5] u32 length of the next item
964 [9] serialized PointedThing
966 0: start digging (from undersurface) or use
967 1: stop digging (all parameters ignored)
969 3: place block or item (to abovesurface)
973 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
976 pkt << (u16)getPlayerItem();
978 std::ostringstream tmp_os(std::ios::binary);
979 pointed.serialize(tmp_os);
981 pkt.putLongString(tmp_os.str());
986 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
987 const std::map<std::string, std::string> &fields)
989 size_t fields_size = fields.size();
991 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
993 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
995 pkt << p << formname << (u16) (fields_size & 0xFFFF);
997 for(std::map<std::string, std::string>::const_iterator
998 i = fields.begin(); i != fields.end(); i++) {
999 const std::string &name = i->first;
1000 const std::string &value = i->second;
1002 pkt.putLongString(value);
1008 void Client::sendInventoryFields(const std::string &formname,
1009 const std::map<std::string, std::string> &fields)
1011 size_t fields_size = fields.size();
1012 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1014 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1015 pkt << formname << (u16) (fields_size & 0xFFFF);
1017 for(std::map<std::string, std::string>::const_iterator
1018 i = fields.begin(); i != fields.end(); i++) {
1019 const std::string &name = i->first;
1020 const std::string &value = i->second;
1022 pkt.putLongString(value);
1028 void Client::sendInventoryAction(InventoryAction *a)
1030 std::ostringstream os(std::ios_base::binary);
1035 std::string s = os.str();
1037 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1038 pkt.putRawString(s.c_str(),s.size());
1043 void Client::sendChatMessage(const std::wstring &message)
1045 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1052 void Client::sendChangePassword(const std::wstring &oldpassword,
1053 const std::wstring &newpassword)
1055 Player *player = m_env.getLocalPlayer();
1059 std::string playername = player->getName();
1060 std::string oldpwd = translatePassword(playername, oldpassword);
1061 std::string newpwd = translatePassword(playername, newpassword);
1063 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1065 for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1066 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1069 for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1070 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1077 void Client::sendDamage(u8 damage)
1079 DSTACK(__FUNCTION_NAME);
1081 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1086 void Client::sendBreath(u16 breath)
1088 DSTACK(__FUNCTION_NAME);
1090 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1095 void Client::sendRespawn()
1097 DSTACK(__FUNCTION_NAME);
1099 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1103 void Client::sendReady()
1105 DSTACK(__FUNCTION_NAME);
1107 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1108 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(minetest_version_hash));
1110 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH_ORIG
1111 << (u8) 0 << (u16) strlen(minetest_version_hash);
1113 pkt.putRawString(minetest_version_hash, (u16) strlen(minetest_version_hash));
1117 void Client::sendPlayerPos()
1119 LocalPlayer *myplayer = m_env.getLocalPlayer();
1120 if(myplayer == NULL)
1123 // Save bandwidth by only updating position when something changed
1124 if(myplayer->last_position == myplayer->getPosition() &&
1125 myplayer->last_speed == myplayer->getSpeed() &&
1126 myplayer->last_pitch == myplayer->getPitch() &&
1127 myplayer->last_yaw == myplayer->getYaw() &&
1128 myplayer->last_keyPressed == myplayer->keyPressed)
1131 myplayer->last_position = myplayer->getPosition();
1132 myplayer->last_speed = myplayer->getSpeed();
1133 myplayer->last_pitch = myplayer->getPitch();
1134 myplayer->last_yaw = myplayer->getYaw();
1135 myplayer->last_keyPressed = myplayer->keyPressed;
1139 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1140 our_peer_id = m_con.GetPeerID();
1143 // Set peer id if not set already
1144 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1145 myplayer->peer_id = our_peer_id;
1147 assert(myplayer->peer_id == our_peer_id);
1149 v3f pf = myplayer->getPosition();
1150 v3f sf = myplayer->getSpeed();
1151 s32 pitch = myplayer->getPitch() * 100;
1152 s32 yaw = myplayer->getYaw() * 100;
1153 u32 keyPressed = myplayer->keyPressed;
1155 v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1156 v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1159 [0] v3s32 position*100
1160 [12] v3s32 speed*100
1161 [12+12] s32 pitch*100
1162 [12+12+4] s32 yaw*100
1163 [12+12+4+4] u32 keyPressed
1166 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1168 pkt << position << speed << pitch << yaw << keyPressed;
1173 void Client::sendPlayerItem(u16 item)
1175 Player *myplayer = m_env.getLocalPlayer();
1176 if(myplayer == NULL)
1179 u16 our_peer_id = m_con.GetPeerID();
1181 // Set peer id if not set already
1182 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1183 myplayer->peer_id = our_peer_id;
1184 assert(myplayer->peer_id == our_peer_id);
1186 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1193 void Client::removeNode(v3s16 p)
1195 std::map<v3s16, MapBlock*> modified_blocks;
1198 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1200 catch(InvalidPositionException &e) {
1203 for(std::map<v3s16, MapBlock *>::iterator
1204 i = modified_blocks.begin();
1205 i != modified_blocks.end(); ++i) {
1206 addUpdateMeshTaskWithEdge(i->first, false, true);
1210 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1212 //TimeTaker timer1("Client::addNode()");
1214 std::map<v3s16, MapBlock*> modified_blocks;
1217 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1218 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1220 catch(InvalidPositionException &e) {
1223 for(std::map<v3s16, MapBlock *>::iterator
1224 i = modified_blocks.begin();
1225 i != modified_blocks.end(); ++i) {
1226 addUpdateMeshTaskWithEdge(i->first, false, true);
1230 void Client::setPlayerControl(PlayerControl &control)
1232 LocalPlayer *player = m_env.getLocalPlayer();
1233 assert(player != NULL);
1234 player->control = control;
1237 void Client::selectPlayerItem(u16 item)
1239 m_playeritem = item;
1240 m_inventory_updated = true;
1241 sendPlayerItem(item);
1244 // Returns true if the inventory of the local player has been
1245 // updated from the server. If it is true, it is set to false.
1246 bool Client::getLocalInventoryUpdated()
1248 bool updated = m_inventory_updated;
1249 m_inventory_updated = false;
1253 // Copies the inventory of the local player to parameter
1254 void Client::getLocalInventory(Inventory &dst)
1256 Player *player = m_env.getLocalPlayer();
1257 assert(player != NULL);
1258 dst = player->inventory;
1261 Inventory* Client::getInventory(const InventoryLocation &loc)
1264 case InventoryLocation::UNDEFINED:
1267 case InventoryLocation::CURRENT_PLAYER:
1269 Player *player = m_env.getLocalPlayer();
1270 assert(player != NULL);
1271 return &player->inventory;
1274 case InventoryLocation::PLAYER:
1276 Player *player = m_env.getPlayer(loc.name.c_str());
1279 return &player->inventory;
1282 case InventoryLocation::NODEMETA:
1284 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1287 return meta->getInventory();
1290 case InventoryLocation::DETACHED:
1292 if(m_detached_inventories.count(loc.name) == 0)
1294 return m_detached_inventories[loc.name];
1298 FATAL_ERROR("Invalid inventory location type.");
1304 void Client::inventoryAction(InventoryAction *a)
1307 Send it to the server
1309 sendInventoryAction(a);
1312 Predict some local inventory changes
1314 a->clientApply(this, this);
1320 ClientActiveObject * Client::getSelectedActiveObject(
1322 v3f from_pos_f_on_map,
1323 core::line3d<f32> shootline_on_map
1326 std::vector<DistanceSortedActiveObject> objects;
1328 m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1331 // After this, the closest object is the first in the array.
1332 std::sort(objects.begin(), objects.end());
1334 for(unsigned int i=0; i<objects.size(); i++)
1336 ClientActiveObject *obj = objects[i].obj;
1338 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1339 if(selection_box == NULL)
1342 v3f pos = obj->getPosition();
1344 core::aabbox3d<f32> offsetted_box(
1345 selection_box->MinEdge + pos,
1346 selection_box->MaxEdge + pos
1349 if(offsetted_box.intersectsWithLine(shootline_on_map))
1358 std::list<std::string> Client::getConnectedPlayerNames()
1360 return m_env.getPlayerNames();
1363 float Client::getAnimationTime()
1365 return m_animation_time;
1368 int Client::getCrackLevel()
1370 return m_crack_level;
1373 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1375 m_show_highlighted = show_highlighted;
1376 v3s16 old_highlighted_pos = m_highlighted_pos;
1377 m_highlighted_pos = pos;
1378 addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1379 addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1382 void Client::setCrack(int level, v3s16 pos)
1384 int old_crack_level = m_crack_level;
1385 v3s16 old_crack_pos = m_crack_pos;
1387 m_crack_level = level;
1390 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1393 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1395 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1398 addUpdateMeshTaskForNode(pos, false, true);
1404 Player *player = m_env.getLocalPlayer();
1405 assert(player != NULL);
1409 u16 Client::getBreath()
1411 Player *player = m_env.getLocalPlayer();
1412 assert(player != NULL);
1413 return player->getBreath();
1416 bool Client::getChatMessage(std::wstring &message)
1418 if(m_chat_queue.size() == 0)
1420 message = m_chat_queue.front();
1425 void Client::typeChatMessage(const std::wstring &message)
1427 // Discard empty line
1432 sendChatMessage(message);
1435 if (message[0] == L'/')
1437 m_chat_queue.push((std::wstring)L"issued command: " + message);
1441 LocalPlayer *player = m_env.getLocalPlayer();
1442 assert(player != NULL);
1443 std::wstring name = narrow_to_wide(player->getName());
1444 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1448 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1450 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1455 Create a task to update the mesh of the block
1458 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1461 //TimeTaker timer("data fill");
1463 // Debug: 1-6ms, avg=2ms
1465 data->setCrack(m_crack_level, m_crack_pos);
1466 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1467 data->setSmoothLighting(m_cache_smooth_lighting);
1470 // Add task to queue
1471 m_mesh_update_thread.m_queue_in.addBlock(p, data, ack_to_server, urgent);
1474 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1477 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1479 catch(InvalidPositionException &e){}
1482 for (int i=0;i<6;i++)
1485 v3s16 p = blockpos + g_6dirs[i];
1486 addUpdateMeshTask(p, false, urgent);
1488 catch(InvalidPositionException &e){}
1492 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1496 infostream<<"Client::addUpdateMeshTaskForNode(): "
1497 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1501 v3s16 blockpos = getNodeBlockPos(nodepos);
1502 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1505 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1507 catch(InvalidPositionException &e) {}
1510 if(nodepos.X == blockpos_relative.X){
1512 v3s16 p = blockpos + v3s16(-1,0,0);
1513 addUpdateMeshTask(p, false, urgent);
1515 catch(InvalidPositionException &e){}
1518 if(nodepos.Y == blockpos_relative.Y){
1520 v3s16 p = blockpos + v3s16(0,-1,0);
1521 addUpdateMeshTask(p, false, urgent);
1523 catch(InvalidPositionException &e){}
1526 if(nodepos.Z == blockpos_relative.Z){
1528 v3s16 p = blockpos + v3s16(0,0,-1);
1529 addUpdateMeshTask(p, false, urgent);
1531 catch(InvalidPositionException &e){}
1535 ClientEvent Client::getClientEvent()
1538 if(m_client_event_queue.size() == 0) {
1539 event.type = CE_NONE;
1542 event = m_client_event_queue.front();
1543 m_client_event_queue.pop();
1548 float Client::mediaReceiveProgress()
1550 if (m_media_downloader)
1551 return m_media_downloader->getProgress();
1553 return 1.0; // downloader only exists when not yet done
1556 void Client::afterContentReceived(IrrlichtDevice *device, gui::IGUIFont* font)
1558 infostream<<"Client::afterContentReceived() started"<<std::endl;
1559 assert(m_itemdef_received); // pre-condition
1560 assert(m_nodedef_received); // pre-condition
1561 assert(mediaReceived()); // pre-condition
1563 const wchar_t* text = wgettext("Loading textures...");
1565 // Rebuild inherited images and recreate textures
1566 infostream<<"- Rebuilding images and textures"<<std::endl;
1567 draw_load_screen(text,device, guienv, 0, 70);
1568 m_tsrc->rebuildImagesAndTextures();
1572 infostream<<"- Rebuilding shaders"<<std::endl;
1573 text = wgettext("Rebuilding shaders...");
1574 draw_load_screen(text, device, guienv, 0, 75);
1575 m_shsrc->rebuildShaders();
1578 // Update node aliases
1579 infostream<<"- Updating node aliases"<<std::endl;
1580 text = wgettext("Initializing nodes...");
1581 draw_load_screen(text, device, guienv, 0, 80);
1582 m_nodedef->updateAliases(m_itemdef);
1583 m_nodedef->setNodeRegistrationStatus(true);
1584 m_nodedef->runNodeResolverCallbacks();
1587 // Update node textures and assign shaders to each tile
1588 infostream<<"- Updating node textures"<<std::endl;
1589 m_nodedef->updateTextures(this);
1591 // Preload item textures and meshes if configured to
1592 if(g_settings->getBool("preload_item_visuals"))
1594 verbosestream<<"Updating item textures and meshes"<<std::endl;
1595 text = wgettext("Item textures...");
1596 draw_load_screen(text, device, guienv, 0, 0);
1597 std::set<std::string> names = m_itemdef->getAll();
1598 size_t size = names.size();
1601 for(std::set<std::string>::const_iterator
1602 i = names.begin(); i != names.end(); ++i)
1604 // Asking for these caches the result
1605 m_itemdef->getInventoryTexture(*i, this);
1606 m_itemdef->getWieldMesh(*i, this);
1608 percent = (count * 100 / size * 0.2) + 80;
1609 draw_load_screen(text, device, guienv, 0, percent);
1614 // Start mesh update thread after setting up content definitions
1615 infostream<<"- Starting mesh update thread"<<std::endl;
1616 m_mesh_update_thread.Start();
1620 text = wgettext("Done!");
1621 draw_load_screen(text, device, guienv, 0, 100);
1622 infostream<<"Client::afterContentReceived() done"<<std::endl;
1626 float Client::getRTT(void)
1628 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1631 float Client::getCurRate(void)
1633 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1634 m_con.getLocalStat(con::CUR_DL_RATE));
1637 float Client::getAvgRate(void)
1639 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1640 m_con.getLocalStat(con::AVG_DL_RATE));
1643 void Client::makeScreenshot(IrrlichtDevice *device)
1645 irr::video::IVideoDriver *driver = device->getVideoDriver();
1646 irr::video::IImage* const raw_image = driver->createScreenShot();
1648 irr::video::IImage* const image = driver->createImage(video::ECF_R8G8B8,
1649 raw_image->getDimension());
1652 raw_image->copyTo(image);
1653 irr::c8 filename[256];
1654 snprintf(filename, sizeof(filename),
1655 (std::string("%s") + DIR_DELIM + "screenshot_%u.png").c_str(),
1656 g_settings->get("screenshot_path").c_str(),
1657 device->getTimer()->getRealTime());
1658 std::ostringstream sstr;
1659 if (driver->writeImageToFile(image, filename)) {
1660 sstr << "Saved screenshot to '" << filename << "'";
1662 sstr << "Failed to save screenshot '" << filename << "'";
1664 m_chat_queue.push(narrow_to_wide(sstr.str()));
1665 infostream << sstr.str() << std::endl;
1672 // IGameDef interface
1674 IItemDefManager* Client::getItemDefManager()
1678 INodeDefManager* Client::getNodeDefManager()
1682 ICraftDefManager* Client::getCraftDefManager()
1685 //return m_craftdef;
1687 ITextureSource* Client::getTextureSource()
1691 IShaderSource* Client::getShaderSource()
1695 scene::ISceneManager* Client::getSceneManager()
1697 return m_device->getSceneManager();
1699 u16 Client::allocateUnknownNodeId(const std::string &name)
1701 errorstream << "Client::allocateUnknownNodeId(): "
1702 << "Client cannot allocate node IDs" << std::endl;
1703 FATAL_ERROR("Client allocated unknown node");
1705 return CONTENT_IGNORE;
1707 ISoundManager* Client::getSoundManager()
1711 MtEventManager* Client::getEventManager()
1716 ParticleManager* Client::getParticleManager()
1718 return &m_particle_manager;
1721 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1723 std::map<std::string, std::string>::const_iterator i =
1724 m_mesh_data.find(filename);
1725 if(i == m_mesh_data.end()){
1726 errorstream<<"Client::getMesh(): Mesh not found: \""<<filename<<"\""
1730 const std::string &data = i->second;
1731 scene::ISceneManager *smgr = m_device->getSceneManager();
1733 // Create the mesh, remove it from cache and return it
1734 // This allows unique vertex colors and other properties for each instance
1735 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1736 io::IFileSystem *irrfs = m_device->getFileSystem();
1737 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1738 *data_rw, data_rw.getSize(), filename.c_str());
1739 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1741 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1743 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1744 // of uniquely named instances and re-use them
1746 smgr->getMeshCache()->removeMesh(mesh);