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);
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 assert(myplayer != NULL);
393 // Send TOSERVER_INIT
394 // [0] u16 TOSERVER_INIT
395 // [2] u8 SER_FMT_VER_HIGHEST_READ
396 // [3] u8[20] player_name
397 // [23] u8[28] password (new in some version)
398 // [51] u16 minimum supported network protocol version (added sometime)
399 // [53] u16 maximum supported network protocol version (added later than the previous one)
401 char pName[PLAYERNAME_SIZE];
402 char pPassword[PASSWORD_SIZE];
404 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
405 snprintf(pPassword, PASSWORD_SIZE, "%s", m_password.c_str());
407 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INIT,
408 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
410 *pkt << (u8) SER_FMT_VER_HIGHEST_READ;
411 pkt->putRawString(pName,PLAYERNAME_SIZE);
412 pkt->putRawString(pPassword, PASSWORD_SIZE);
413 *pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
418 // Not connected, return
423 Do stuff if connected
427 Run Map's timers and unload unused data
429 const float map_timer_and_unload_dtime = 5.25;
430 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
431 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
432 std::vector<v3s16> deleted_blocks;
433 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
434 g_settings->getFloat("client_unload_unused_data_timeout"),
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()) {
455 NetworkPacket* pkt = new NetworkPacket(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * sendlist.size());
457 *pkt << (u8) sendlist.size();
460 for(std::vector<v3s16>::iterator
461 j = sendlist.begin();
462 j != sendlist.end(); ++j) {
469 if(i == deleted_blocks.end())
475 sendlist.push_back(*i);
483 // Control local player (0ms)
484 LocalPlayer *player = m_env.getLocalPlayer();
485 assert(player != NULL);
486 player->applyControl(dtime);
495 ClientEnvEvent event = m_env.getClientEvent();
496 if(event.type == CEE_NONE) {
499 else if(event.type == CEE_PLAYER_DAMAGE) {
500 if(m_ignore_damage_timer <= 0) {
501 u8 damage = event.player_damage.amount;
503 if(event.player_damage.send_to_server)
506 // Add to ClientEvent queue
508 event.type = CE_PLAYER_DAMAGE;
509 event.player_damage.amount = damage;
510 m_client_event_queue.push(event);
513 else if(event.type == CEE_PLAYER_BREATH) {
514 u16 breath = event.player_breath.amount;
522 float &counter = m_avg_rtt_timer;
526 // connectedAndInitialized() is true, peer exists.
527 float avg_rtt = getRTT();
528 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
532 Send player position to server
535 float &counter = m_playerpos_send_timer;
537 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
545 Replace updated meshes
548 int num_processed_meshes = 0;
549 while(!m_mesh_update_thread.m_queue_out.empty())
551 num_processed_meshes++;
552 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
553 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
555 // Delete the old mesh
556 if(block->mesh != NULL)
558 // TODO: Remove hardware buffers of meshbuffers of block->mesh
563 // Replace with the new mesh
564 block->mesh = r.mesh;
569 if(r.ack_block_to_server) {
575 NetworkPacket* pkt = new NetworkPacket(TOSERVER_GOTBLOCKS, 1 + 6);
576 *pkt << (u8) 1 << r.p;
581 if(num_processed_meshes > 0)
582 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
588 if (m_media_downloader && m_media_downloader->isStarted()) {
589 m_media_downloader->step(this);
590 if (m_media_downloader->isDone()) {
592 delete m_media_downloader;
593 m_media_downloader = NULL;
598 If the server didn't update the inventory in a while, revert
599 the local inventory (so the player notices the lag problem
600 and knows something is wrong).
602 if(m_inventory_from_server)
604 float interval = 10.0;
605 float count_before = floor(m_inventory_from_server_age / interval);
607 m_inventory_from_server_age += dtime;
609 float count_after = floor(m_inventory_from_server_age / interval);
611 if(count_after != count_before)
613 // Do this every <interval> seconds after TOCLIENT_INVENTORY
614 // Reset the locally changed inventory to the authoritative inventory
615 Player *player = m_env.getLocalPlayer();
616 player->inventory = *m_inventory_from_server;
617 m_inventory_updated = true;
622 Update positions of sounds attached to objects
625 for(std::map<int, u16>::iterator
626 i = m_sounds_to_objects.begin();
627 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::set<s32> removed_server_ids;
647 for(std::map<s32, int>::iterator
648 i = m_sounds_server_to_client.begin();
649 i != m_sounds_server_to_client.end();) {
650 s32 server_id = i->first;
651 int client_id = i->second;
653 if(!m_sound->soundExists(client_id)) {
654 m_sounds_server_to_client.erase(server_id);
655 m_sounds_client_to_server.erase(client_id);
656 m_sounds_to_objects.erase(client_id);
657 removed_server_ids.insert(server_id);
662 if(!removed_server_ids.empty()) {
663 size_t server_ids = removed_server_ids.size();
664 assert(server_ids <= 0xFFFF);
666 NetworkPacket* pkt = new NetworkPacket(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
668 *pkt << (u16) (server_ids & 0xFFFF);
670 for(std::set<s32>::iterator i = removed_server_ids.begin();
671 i != removed_server_ids.end(); i++)
679 if (m_localdb && m_localdb_save_interval.step(dtime,
680 m_cache_save_interval)) {
681 m_localdb->endSave();
682 m_localdb->beginSave();
686 bool Client::loadMedia(const std::string &data, const std::string &filename)
688 // Silly irrlicht's const-incorrectness
689 Buffer<char> data_rw(data.c_str(), data.size());
693 const char *image_ext[] = {
694 ".png", ".jpg", ".bmp", ".tga",
695 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
698 name = removeStringEnd(filename, image_ext);
701 verbosestream<<"Client: Attempting to load image "
702 <<"file \""<<filename<<"\""<<std::endl;
704 io::IFileSystem *irrfs = m_device->getFileSystem();
705 video::IVideoDriver *vdrv = m_device->getVideoDriver();
707 // Create an irrlicht memory file
708 io::IReadFile *rfile = irrfs->createMemoryReadFile(
709 *data_rw, data_rw.getSize(), "_tempreadfile");
712 video::IImage *img = vdrv->createImageFromFile(rfile);
714 errorstream<<"Client: Cannot create image from data of "
715 <<"file \""<<filename<<"\""<<std::endl;
720 m_tsrc->insertSourceImage(filename, img);
727 const char *sound_ext[] = {
728 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
729 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
732 name = removeStringEnd(filename, sound_ext);
735 verbosestream<<"Client: Attempting to load sound "
736 <<"file \""<<filename<<"\""<<std::endl;
737 m_sound->loadSoundData(name, data);
741 const char *model_ext[] = {
742 ".x", ".b3d", ".md2", ".obj",
745 name = removeStringEnd(filename, model_ext);
748 verbosestream<<"Client: Storing model into memory: "
749 <<"\""<<filename<<"\""<<std::endl;
750 if(m_mesh_data.count(filename))
751 errorstream<<"Multiple models with name \""<<filename.c_str()
752 <<"\" found; replacing previous model"<<std::endl;
753 m_mesh_data[filename] = data;
757 errorstream<<"Client: Don't know how to load file \""
758 <<filename<<"\""<<std::endl;
762 // Virtual methods from con::PeerHandler
763 void Client::peerAdded(con::Peer *peer)
765 infostream<<"Client::peerAdded(): peer->id="
766 <<peer->id<<std::endl;
768 void Client::deletingPeer(con::Peer *peer, bool timeout)
770 infostream<<"Client::deletingPeer(): "
771 "Server Peer is getting deleted "
772 <<"(timeout="<<timeout<<")"<<std::endl;
777 u16 number of files requested
783 void Client::request_media(const std::vector<std::string> &file_requests)
785 std::ostringstream os(std::ios_base::binary);
786 writeU16(os, TOSERVER_REQUEST_MEDIA);
787 size_t file_requests_size = file_requests.size();
788 assert(file_requests_size <= 0xFFFF);
790 // Packet dynamicly resized
791 NetworkPacket* pkt = new NetworkPacket(TOSERVER_REQUEST_MEDIA, 2 + 0);
793 *pkt << (u16) (file_requests_size & 0xFFFF);
795 for(std::vector<std::string>::const_iterator i = file_requests.begin();
796 i != file_requests.end(); ++i) {
802 infostream<<"Client: Sending media request list to server ("
803 <<file_requests.size()<<" files. packet size)"<<std::endl;
806 void Client::received_media()
808 NetworkPacket* pkt = new NetworkPacket(TOSERVER_RECEIVED_MEDIA, 0);
810 infostream<<"Client: Notifying server that we received all media"
814 void Client::initLocalMapSaving(const Address &address,
815 const std::string &hostname,
816 bool is_local_server)
818 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
822 const std::string world_path = porting::path_user
823 + DIR_DELIM + "worlds"
824 + DIR_DELIM + "server_"
825 + hostname + "_" + to_string(address.getPort());
827 fs::CreateAllDirs(world_path);
829 m_localdb = new Database_SQLite3(world_path);
830 m_localdb->beginSave();
831 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
834 void Client::ReceiveAll()
836 DSTACK(__FUNCTION_NAME);
837 u32 start_ms = porting::getTimeMs();
840 // Limit time even if there would be huge amounts of data to
842 if(porting::getTimeMs() > start_ms + 100)
847 g_profiler->graphAdd("client_received_packets", 1);
849 catch(con::NoIncomingDataException &e) {
852 catch(con::InvalidIncomingDataException &e) {
853 infostream<<"Client::ReceiveAll(): "
854 "InvalidIncomingDataException: what()="
855 <<e.what()<<std::endl;
860 void Client::Receive()
862 DSTACK(__FUNCTION_NAME);
863 SharedBuffer<u8> data;
865 u32 datasize = m_con.Receive(sender_peer_id, data);
866 ProcessData(*data, datasize, sender_peer_id);
869 inline void Client::handleCommand(NetworkPacket* pkt)
871 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
872 (this->*opHandle.handler)(pkt);
876 sender_peer_id given to this shall be quaranteed to be a valid peer
878 void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
880 DSTACK(__FUNCTION_NAME);
882 // Ignore packets that don't even fit a command
884 m_packetcounter.add(60000);
888 NetworkPacket* pkt = new NetworkPacket(data, datasize, sender_peer_id);
890 ToClientCommand command = (ToClientCommand) pkt->getCommand();
892 //infostream<<"Client: received command="<<command<<std::endl;
893 m_packetcounter.add((u16)command);
896 If this check is removed, be sure to change the queue
897 system to know the ids
899 if(sender_peer_id != PEER_ID_SERVER) {
900 infostream << "Client::ProcessData(): Discarding data not "
901 "coming from server: peer_id=" << sender_peer_id
907 // Command must be handled into ToClientCommandHandler
908 if (command >= TOCLIENT_NUM_MSG_TYPES) {
909 infostream << "Client: Ignoring unknown command "
910 << command << std::endl;
914 * Those packets are handled before m_server_ser_ver is set, it's normal
915 * But we must use the new ToClientConnectionState in the future,
918 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
924 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
925 infostream << "Client: Server serialization"
926 " format invalid or not initialized."
927 " Skipping incoming command=" << command << std::endl;
933 Handle runtime commands
940 void Client::Send(NetworkPacket* pkt)
942 m_con.Send(PEER_ID_SERVER,
943 serverCommandFactoryTable[pkt->getCommand()].channel,
945 serverCommandFactoryTable[pkt->getCommand()].reliable);
949 void Client::interact(u8 action, const PointedThing& pointed)
951 if(m_state != LC_Ready) {
952 errorstream << "Client::interact() "
953 "cancelled (not connected)"
962 [5] u32 length of the next item
963 [9] serialized PointedThing
965 0: start digging (from undersurface) or use
966 1: stop digging (all parameters ignored)
968 3: place block or item (to abovesurface)
972 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INTERACT, 1 + 2 + 0);
975 *pkt << (u16)getPlayerItem();
977 std::ostringstream tmp_os(std::ios::binary);
978 pointed.serialize(tmp_os);
980 pkt->putLongString(tmp_os.str());
985 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
986 const std::map<std::string, std::string> &fields)
988 size_t fields_size = fields.size();
989 assert(fields_size <= 0xFFFF);
991 NetworkPacket* pkt = new NetworkPacket(TOSERVER_NODEMETA_FIELDS, 0);
993 *pkt << p << formname << (u16) (fields_size & 0xFFFF);
995 for(std::map<std::string, std::string>::const_iterator
996 i = fields.begin(); i != fields.end(); i++) {
997 const std::string &name = i->first;
998 const std::string &value = i->second;
1000 pkt->putLongString(value);
1006 void Client::sendInventoryFields(const std::string &formname,
1007 const std::map<std::string, std::string> &fields)
1009 size_t fields_size = fields.size();
1010 assert(fields_size <= 0xFFFF);
1012 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INVENTORY_FIELDS, 0);
1013 *pkt << formname << (u16) (fields_size & 0xFFFF);
1015 for(std::map<std::string, std::string>::const_iterator
1016 i = fields.begin(); i != fields.end(); i++) {
1017 const std::string &name = i->first;
1018 const std::string &value = i->second;
1020 pkt->putLongString(value);
1026 void Client::sendInventoryAction(InventoryAction *a)
1028 std::ostringstream os(std::ios_base::binary);
1033 std::string s = os.str();
1035 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INVENTORY_ACTION, s.size());
1036 pkt->putRawString(s.c_str(),s.size());
1041 void Client::sendChatMessage(const std::wstring &message)
1043 NetworkPacket* pkt = new NetworkPacket(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1050 void Client::sendChangePassword(const std::wstring &oldpassword,
1051 const std::wstring &newpassword)
1053 Player *player = m_env.getLocalPlayer();
1057 std::string playername = player->getName();
1058 std::string oldpwd = translatePassword(playername, oldpassword);
1059 std::string newpwd = translatePassword(playername, newpassword);
1061 NetworkPacket* pkt = new NetworkPacket(TOSERVER_PASSWORD, 2 * PASSWORD_SIZE);
1063 for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1064 *pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1067 for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1068 *pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1075 void Client::sendDamage(u8 damage)
1077 DSTACK(__FUNCTION_NAME);
1079 NetworkPacket* pkt = new NetworkPacket(TOSERVER_DAMAGE, sizeof(u8));
1084 void Client::sendBreath(u16 breath)
1086 DSTACK(__FUNCTION_NAME);
1088 NetworkPacket* pkt = new NetworkPacket(TOSERVER_BREATH, sizeof(u16));
1093 void Client::sendRespawn()
1095 DSTACK(__FUNCTION_NAME);
1097 NetworkPacket* pkt = new NetworkPacket(TOSERVER_RESPAWN, 0);
1101 void Client::sendReady()
1103 DSTACK(__FUNCTION_NAME);
1105 NetworkPacket* pkt = new NetworkPacket(TOSERVER_CLIENT_READY,
1106 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(minetest_version_hash));
1108 *pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH_ORIG
1109 << (u8) 0 << (u16) strlen(minetest_version_hash);
1111 pkt->putRawString(minetest_version_hash, (u16) strlen(minetest_version_hash));
1115 void Client::sendPlayerPos()
1117 LocalPlayer *myplayer = m_env.getLocalPlayer();
1118 if(myplayer == NULL)
1121 // Save bandwidth by only updating position when something changed
1122 if(myplayer->last_position == myplayer->getPosition() &&
1123 myplayer->last_speed == myplayer->getSpeed() &&
1124 myplayer->last_pitch == myplayer->getPitch() &&
1125 myplayer->last_yaw == myplayer->getYaw() &&
1126 myplayer->last_keyPressed == myplayer->keyPressed)
1129 myplayer->last_position = myplayer->getPosition();
1130 myplayer->last_speed = myplayer->getSpeed();
1131 myplayer->last_pitch = myplayer->getPitch();
1132 myplayer->last_yaw = myplayer->getYaw();
1133 myplayer->last_keyPressed = myplayer->keyPressed;
1137 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1138 our_peer_id = m_con.GetPeerID();
1141 // Set peer id if not set already
1142 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1143 myplayer->peer_id = our_peer_id;
1144 // Check that an existing peer_id is the same as the connection's
1145 assert(myplayer->peer_id == our_peer_id);
1147 v3f pf = myplayer->getPosition();
1148 v3f sf = myplayer->getSpeed();
1149 s32 pitch = myplayer->getPitch() * 100;
1150 s32 yaw = myplayer->getYaw() * 100;
1151 u32 keyPressed = myplayer->keyPressed;
1153 v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1154 v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1157 [0] v3s32 position*100
1158 [12] v3s32 speed*100
1159 [12+12] s32 pitch*100
1160 [12+12+4] s32 yaw*100
1161 [12+12+4+4] u32 keyPressed
1164 NetworkPacket* pkt = new NetworkPacket(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1166 *pkt << position << speed << pitch << yaw << keyPressed;
1171 void Client::sendPlayerItem(u16 item)
1173 Player *myplayer = m_env.getLocalPlayer();
1174 if(myplayer == NULL)
1177 u16 our_peer_id = m_con.GetPeerID();
1179 // Set peer id if not set already
1180 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1181 myplayer->peer_id = our_peer_id;
1183 // Check that an existing peer_id is the same as the connection's
1184 assert(myplayer->peer_id == our_peer_id);
1186 NetworkPacket* pkt = new NetworkPacket(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];
1303 void Client::inventoryAction(InventoryAction *a)
1306 Send it to the server
1308 sendInventoryAction(a);
1311 Predict some local inventory changes
1313 a->clientApply(this, this);
1319 ClientActiveObject * Client::getSelectedActiveObject(
1321 v3f from_pos_f_on_map,
1322 core::line3d<f32> shootline_on_map
1325 std::vector<DistanceSortedActiveObject> objects;
1327 m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1330 // After this, the closest object is the first in the array.
1331 std::sort(objects.begin(), objects.end());
1333 for(unsigned int i=0; i<objects.size(); i++)
1335 ClientActiveObject *obj = objects[i].obj;
1337 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1338 if(selection_box == NULL)
1341 v3f pos = obj->getPosition();
1343 core::aabbox3d<f32> offsetted_box(
1344 selection_box->MinEdge + pos,
1345 selection_box->MaxEdge + pos
1348 if(offsetted_box.intersectsWithLine(shootline_on_map))
1357 std::list<std::string> Client::getConnectedPlayerNames()
1359 return m_env.getPlayerNames();
1362 float Client::getAnimationTime()
1364 return m_animation_time;
1367 int Client::getCrackLevel()
1369 return m_crack_level;
1372 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1374 m_show_highlighted = show_highlighted;
1375 v3s16 old_highlighted_pos = m_highlighted_pos;
1376 m_highlighted_pos = pos;
1377 addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1378 addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1381 void Client::setCrack(int level, v3s16 pos)
1383 int old_crack_level = m_crack_level;
1384 v3s16 old_crack_pos = m_crack_pos;
1386 m_crack_level = level;
1389 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1392 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1394 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1397 addUpdateMeshTaskForNode(pos, false, true);
1403 Player *player = m_env.getLocalPlayer();
1404 assert(player != NULL);
1408 u16 Client::getBreath()
1410 Player *player = m_env.getLocalPlayer();
1411 assert(player != NULL);
1412 return player->getBreath();
1415 bool Client::getChatMessage(std::wstring &message)
1417 if(m_chat_queue.size() == 0)
1419 message = m_chat_queue.front();
1424 void Client::typeChatMessage(const std::wstring &message)
1426 // Discard empty line
1431 sendChatMessage(message);
1434 if (message[0] == L'/')
1436 m_chat_queue.push((std::wstring)L"issued command: " + message);
1440 LocalPlayer *player = m_env.getLocalPlayer();
1441 assert(player != NULL);
1442 std::wstring name = narrow_to_wide(player->getName());
1443 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1447 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1449 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1454 Create a task to update the mesh of the block
1457 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1460 //TimeTaker timer("data fill");
1462 // Debug: 1-6ms, avg=2ms
1464 data->setCrack(m_crack_level, m_crack_pos);
1465 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1466 data->setSmoothLighting(m_cache_smooth_lighting);
1469 // Add task to queue
1470 m_mesh_update_thread.m_queue_in.addBlock(p, data, ack_to_server, urgent);
1473 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1476 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1478 catch(InvalidPositionException &e){}
1481 for (int i=0;i<6;i++)
1484 v3s16 p = blockpos + g_6dirs[i];
1485 addUpdateMeshTask(p, false, urgent);
1487 catch(InvalidPositionException &e){}
1491 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1495 infostream<<"Client::addUpdateMeshTaskForNode(): "
1496 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1500 v3s16 blockpos = getNodeBlockPos(nodepos);
1501 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1504 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1506 catch(InvalidPositionException &e) {}
1509 if(nodepos.X == blockpos_relative.X){
1511 v3s16 p = blockpos + v3s16(-1,0,0);
1512 addUpdateMeshTask(p, false, urgent);
1514 catch(InvalidPositionException &e){}
1517 if(nodepos.Y == blockpos_relative.Y){
1519 v3s16 p = blockpos + v3s16(0,-1,0);
1520 addUpdateMeshTask(p, false, urgent);
1522 catch(InvalidPositionException &e){}
1525 if(nodepos.Z == blockpos_relative.Z){
1527 v3s16 p = blockpos + v3s16(0,0,-1);
1528 addUpdateMeshTask(p, false, urgent);
1530 catch(InvalidPositionException &e){}
1534 ClientEvent Client::getClientEvent()
1537 if(m_client_event_queue.size() == 0) {
1538 event.type = CE_NONE;
1541 event = m_client_event_queue.front();
1542 m_client_event_queue.pop();
1547 float Client::mediaReceiveProgress()
1549 if (m_media_downloader)
1550 return m_media_downloader->getProgress();
1552 return 1.0; // downloader only exists when not yet done
1555 void Client::afterContentReceived(IrrlichtDevice *device, gui::IGUIFont* font)
1557 infostream<<"Client::afterContentReceived() started"<<std::endl;
1558 assert(m_itemdef_received);
1559 assert(m_nodedef_received);
1560 assert(mediaReceived());
1562 const wchar_t* text = wgettext("Loading textures...");
1564 // Rebuild inherited images and recreate textures
1565 infostream<<"- Rebuilding images and textures"<<std::endl;
1566 draw_load_screen(text,device, guienv, 0, 70);
1567 m_tsrc->rebuildImagesAndTextures();
1571 infostream<<"- Rebuilding shaders"<<std::endl;
1572 text = wgettext("Rebuilding shaders...");
1573 draw_load_screen(text, device, guienv, 0, 75);
1574 m_shsrc->rebuildShaders();
1577 // Update node aliases
1578 infostream<<"- Updating node aliases"<<std::endl;
1579 text = wgettext("Initializing nodes...");
1580 draw_load_screen(text, device, guienv, 0, 80);
1581 m_nodedef->updateAliases(m_itemdef);
1582 m_nodedef->setNodeRegistrationStatus(true);
1583 m_nodedef->runNodeResolverCallbacks();
1586 // Update node textures and assign shaders to each tile
1587 infostream<<"- Updating node textures"<<std::endl;
1588 m_nodedef->updateTextures(this);
1590 // Preload item textures and meshes if configured to
1591 if(g_settings->getBool("preload_item_visuals"))
1593 verbosestream<<"Updating item textures and meshes"<<std::endl;
1594 text = wgettext("Item textures...");
1595 draw_load_screen(text, device, guienv, 0, 0);
1596 std::set<std::string> names = m_itemdef->getAll();
1597 size_t size = names.size();
1600 for(std::set<std::string>::const_iterator
1601 i = names.begin(); i != names.end(); ++i)
1603 // Asking for these caches the result
1604 m_itemdef->getInventoryTexture(*i, this);
1605 m_itemdef->getWieldMesh(*i, this);
1607 percent = (count * 100 / size * 0.2) + 80;
1608 draw_load_screen(text, device, guienv, 0, percent);
1613 // Start mesh update thread after setting up content definitions
1614 infostream<<"- Starting mesh update thread"<<std::endl;
1615 m_mesh_update_thread.Start();
1619 text = wgettext("Done!");
1620 draw_load_screen(text, device, guienv, 0, 100);
1621 infostream<<"Client::afterContentReceived() done"<<std::endl;
1625 float Client::getRTT(void)
1627 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1630 float Client::getCurRate(void)
1632 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1633 m_con.getLocalStat(con::CUR_DL_RATE));
1636 float Client::getAvgRate(void)
1638 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1639 m_con.getLocalStat(con::AVG_DL_RATE));
1642 void Client::makeScreenshot(IrrlichtDevice *device)
1644 irr::video::IVideoDriver *driver = device->getVideoDriver();
1645 irr::video::IImage* const raw_image = driver->createScreenShot();
1647 irr::video::IImage* const image = driver->createImage(video::ECF_R8G8B8,
1648 raw_image->getDimension());
1651 raw_image->copyTo(image);
1652 irr::c8 filename[256];
1653 snprintf(filename, sizeof(filename),
1654 (std::string("%s") + DIR_DELIM + "screenshot_%u.png").c_str(),
1655 g_settings->get("screenshot_path").c_str(),
1656 device->getTimer()->getRealTime());
1657 std::ostringstream sstr;
1658 if (driver->writeImageToFile(image, filename)) {
1659 sstr << "Saved screenshot to '" << filename << "'";
1661 sstr << "Failed to save screenshot '" << filename << "'";
1663 m_chat_queue.push(narrow_to_wide(sstr.str()));
1664 infostream << sstr.str() << std::endl;
1671 // IGameDef interface
1673 IItemDefManager* Client::getItemDefManager()
1677 INodeDefManager* Client::getNodeDefManager()
1681 ICraftDefManager* Client::getCraftDefManager()
1684 //return m_craftdef;
1686 ITextureSource* Client::getTextureSource()
1690 IShaderSource* Client::getShaderSource()
1694 scene::ISceneManager* Client::getSceneManager()
1696 return m_device->getSceneManager();
1698 u16 Client::allocateUnknownNodeId(const std::string &name)
1700 errorstream<<"Client::allocateUnknownNodeId(): "
1701 <<"Client cannot allocate node IDs"<<std::endl;
1703 return CONTENT_IGNORE;
1705 ISoundManager* Client::getSoundManager()
1709 MtEventManager* Client::getEventManager()
1714 ParticleManager* Client::getParticleManager()
1716 return &m_particle_manager;
1719 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1721 std::map<std::string, std::string>::const_iterator i =
1722 m_mesh_data.find(filename);
1723 if(i == m_mesh_data.end()){
1724 errorstream<<"Client::getMesh(): Mesh not found: \""<<filename<<"\""
1728 const std::string &data = i->second;
1729 scene::ISceneManager *smgr = m_device->getSceneManager();
1731 // Create the mesh, remove it from cache and return it
1732 // This allows unique vertex colors and other properties for each instance
1733 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1734 io::IFileSystem *irrfs = m_device->getFileSystem();
1735 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1736 *data_rw, data_rw.getSize(), filename.c_str());
1739 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1741 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1742 // of uniquely named instances and re-use them
1744 smgr->getMeshCache()->removeMesh(mesh);