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"
53 #include "database-sqlite3.h"
55 extern gui::IGUIEnvironment* guienv;
61 QueuedMeshUpdate::QueuedMeshUpdate():
64 ack_block_to_server(false)
68 QueuedMeshUpdate::~QueuedMeshUpdate()
78 MeshUpdateQueue::MeshUpdateQueue()
82 MeshUpdateQueue::~MeshUpdateQueue()
84 JMutexAutoLock lock(m_mutex);
86 for(std::vector<QueuedMeshUpdate*>::iterator
88 i != m_queue.end(); i++)
90 QueuedMeshUpdate *q = *i;
96 peer_id=0 adds with nobody to send to
98 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
100 DSTACK(__FUNCTION_NAME);
104 JMutexAutoLock lock(m_mutex);
110 Find if block is already in queue.
111 If it is, update the data and quit.
113 for(std::vector<QueuedMeshUpdate*>::iterator
115 i != m_queue.end(); i++)
117 QueuedMeshUpdate *q = *i;
123 if(ack_block_to_server)
124 q->ack_block_to_server = true;
132 QueuedMeshUpdate *q = new QueuedMeshUpdate;
135 q->ack_block_to_server = ack_block_to_server;
136 m_queue.push_back(q);
139 // Returned pointer must be deleted
140 // Returns NULL if queue is empty
141 QueuedMeshUpdate * MeshUpdateQueue::pop()
143 JMutexAutoLock lock(m_mutex);
145 bool must_be_urgent = !m_urgents.empty();
146 for(std::vector<QueuedMeshUpdate*>::iterator
148 i != m_queue.end(); i++)
150 QueuedMeshUpdate *q = *i;
151 if(must_be_urgent && m_urgents.count(q->p) == 0)
154 m_urgents.erase(q->p);
164 void * MeshUpdateThread::Thread()
168 log_register_thread("MeshUpdateThread");
170 DSTACK(__FUNCTION_NAME);
172 BEGIN_DEBUG_EXCEPTION_HANDLER
174 porting::setThreadName("MeshUpdateThread");
176 while(!StopRequested())
178 QueuedMeshUpdate *q = m_queue_in.pop();
185 ScopeProfiler sp(g_profiler, "Client: Mesh making");
187 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
188 if(mesh_new->getMesh()->getMeshBufferCount() == 0)
197 r.ack_block_to_server = q->ack_block_to_server;
199 m_queue_out.push_back(r);
204 END_DEBUG_EXCEPTION_HANDLER(errorstream)
214 IrrlichtDevice *device,
215 const char *playername,
216 std::string password,
217 MapDrawControl &control,
218 IWritableTextureSource *tsrc,
219 IWritableShaderSource *shsrc,
220 IWritableItemDefManager *itemdef,
221 IWritableNodeDefManager *nodedef,
222 ISoundManager *sound,
223 MtEventManager *event,
226 m_packetcounter_timer(0.0),
227 m_connection_reinit_timer(0.1),
228 m_avg_rtt_timer(0.0),
229 m_playerpos_send_timer(0.0),
230 m_ignore_damage_timer(0.0),
237 m_mesh_update_thread(this),
239 new ClientMap(this, this, control,
240 device->getSceneManager()->getRootSceneNode(),
241 device->getSceneManager(), 666),
242 device->getSceneManager(),
245 m_particle_manager(&m_env),
246 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
248 m_server_ser_ver(SER_FMT_VER_INVALID),
250 m_inventory_updated(false),
251 m_inventory_from_server(NULL),
252 m_inventory_from_server_age(0.0),
253 m_show_highlighted(false),
257 m_highlighted_pos(0,0,0),
259 m_password(password),
260 m_access_denied(false),
261 m_itemdef_received(false),
262 m_nodedef_received(false),
263 m_media_downloader(new ClientMediaDownloader()),
264 m_time_of_day_set(false),
265 m_last_time_of_day_f(-1),
266 m_time_of_day_update_timer(0),
267 m_recommended_send_interval(0.1),
268 m_removed_sounds_check_timer(0),
275 Player *player = new LocalPlayer(this, playername);
277 m_env.addPlayer(player);
280 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
281 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
286 //request all client managed threads to stop
287 m_mesh_update_thread.Stop();
288 if (localdb != NULL) {
289 actionstream << "Local map saving ended" << std::endl;
295 bool Client::isShutdown()
298 if (!m_mesh_update_thread.IsRunning()) return true;
307 m_mesh_update_thread.Stop();
308 m_mesh_update_thread.Wait();
309 while(!m_mesh_update_thread.m_queue_out.empty()) {
310 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
315 delete m_inventory_from_server;
317 // Delete detached inventories
318 for(std::map<std::string, Inventory*>::iterator
319 i = m_detached_inventories.begin();
320 i != m_detached_inventories.end(); i++){
324 // cleanup 3d model meshes on client shutdown
325 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
326 scene::IAnimatedMesh * mesh =
327 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
330 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
334 void Client::connect(Address address,
335 const std::string &address_name,
336 bool is_local_server)
338 DSTACK(__FUNCTION_NAME);
340 initLocalMapSaving(address, address_name, is_local_server);
342 m_con.SetTimeoutMs(0);
343 m_con.Connect(address);
346 void Client::step(float dtime)
348 DSTACK(__FUNCTION_NAME);
354 if(m_ignore_damage_timer > dtime)
355 m_ignore_damage_timer -= dtime;
357 m_ignore_damage_timer = 0.0;
359 m_animation_time += dtime;
360 if(m_animation_time > 60.0)
361 m_animation_time -= 60.0;
363 m_time_of_day_update_timer += dtime;
371 float &counter = m_packetcounter_timer;
377 infostream << "Client packetcounter (" << m_packetcounter_timer
379 m_packetcounter.print(infostream);
380 m_packetcounter.clear();
384 // UGLY hack to fix 2 second startup delay caused by non existent
385 // server client startup synchronization in local server or singleplayer mode
386 static bool initial_step = true;
388 initial_step = false;
390 else if(m_state == LC_Created) {
391 float &counter = m_connection_reinit_timer;
396 Player *myplayer = m_env.getLocalPlayer();
397 assert(myplayer != NULL);
398 // Send TOSERVER_INIT
399 // [0] u16 TOSERVER_INIT
400 // [2] u8 SER_FMT_VER_HIGHEST_READ
401 // [3] u8[20] player_name
402 // [23] u8[28] password (new in some version)
403 // [51] u16 minimum supported network protocol version (added sometime)
404 // [53] u16 maximum supported network protocol version (added later than the previous one)
406 char pName[PLAYERNAME_SIZE];
407 char pPassword[PASSWORD_SIZE];
409 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
410 snprintf(pPassword, PASSWORD_SIZE, "%s", m_password.c_str());
412 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INIT,
413 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
415 *pkt << (u8) SER_FMT_VER_HIGHEST_READ;
416 pkt->putRawString(pName,PLAYERNAME_SIZE);
417 pkt->putRawString(pPassword, PASSWORD_SIZE);
418 *pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
423 // Not connected, return
428 Do stuff if connected
432 Run Map's timers and unload unused data
434 const float map_timer_and_unload_dtime = 5.25;
435 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
436 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
437 std::list<v3s16> deleted_blocks;
438 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
439 g_settings->getFloat("client_unload_unused_data_timeout"),
444 NOTE: This loop is intentionally iterated the way it is.
447 std::list<v3s16>::iterator i = deleted_blocks.begin();
448 std::list<v3s16> sendlist;
450 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
460 NetworkPacket* pkt = new NetworkPacket(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * sendlist.size());
462 *pkt << (u8) sendlist.size();
465 for(std::list<v3s16>::iterator
466 j = sendlist.begin();
467 j != sendlist.end(); ++j) {
474 if(i == deleted_blocks.end())
480 sendlist.push_back(*i);
488 // Control local player (0ms)
489 LocalPlayer *player = m_env.getLocalPlayer();
490 assert(player != NULL);
491 player->applyControl(dtime);
500 ClientEnvEvent event = m_env.getClientEvent();
501 if(event.type == CEE_NONE) {
504 else if(event.type == CEE_PLAYER_DAMAGE) {
505 if(m_ignore_damage_timer <= 0) {
506 u8 damage = event.player_damage.amount;
508 if(event.player_damage.send_to_server)
511 // Add to ClientEvent queue
513 event.type = CE_PLAYER_DAMAGE;
514 event.player_damage.amount = damage;
515 m_client_event_queue.push_back(event);
518 else if(event.type == CEE_PLAYER_BREATH) {
519 u16 breath = event.player_breath.amount;
527 float &counter = m_avg_rtt_timer;
531 // connectedAndInitialized() is true, peer exists.
532 float avg_rtt = getRTT();
533 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
537 Send player position to server
540 float &counter = m_playerpos_send_timer;
542 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
550 Replace updated meshes
553 int num_processed_meshes = 0;
554 while(!m_mesh_update_thread.m_queue_out.empty())
556 num_processed_meshes++;
557 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
558 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
560 // Delete the old mesh
561 if(block->mesh != NULL)
563 // TODO: Remove hardware buffers of meshbuffers of block->mesh
568 // Replace with the new mesh
569 block->mesh = r.mesh;
574 if(r.ack_block_to_server) {
580 NetworkPacket* pkt = new NetworkPacket(TOSERVER_GOTBLOCKS, 1 + 6);
581 *pkt << (u8) 1 << r.p;
586 if(num_processed_meshes > 0)
587 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
593 if (m_media_downloader && m_media_downloader->isStarted()) {
594 m_media_downloader->step(this);
595 if (m_media_downloader->isDone()) {
597 delete m_media_downloader;
598 m_media_downloader = NULL;
603 If the server didn't update the inventory in a while, revert
604 the local inventory (so the player notices the lag problem
605 and knows something is wrong).
607 if(m_inventory_from_server)
609 float interval = 10.0;
610 float count_before = floor(m_inventory_from_server_age / interval);
612 m_inventory_from_server_age += dtime;
614 float count_after = floor(m_inventory_from_server_age / interval);
616 if(count_after != count_before)
618 // Do this every <interval> seconds after TOCLIENT_INVENTORY
619 // Reset the locally changed inventory to the authoritative inventory
620 Player *player = m_env.getLocalPlayer();
621 player->inventory = *m_inventory_from_server;
622 m_inventory_updated = true;
627 Update positions of sounds attached to objects
630 for(std::map<int, u16>::iterator
631 i = m_sounds_to_objects.begin();
632 i != m_sounds_to_objects.end(); i++)
634 int client_id = i->first;
635 u16 object_id = i->second;
636 ClientActiveObject *cao = m_env.getActiveObject(object_id);
639 v3f pos = cao->getPosition();
640 m_sound->updateSoundPosition(client_id, pos);
645 Handle removed remotely initiated sounds
647 m_removed_sounds_check_timer += dtime;
648 if(m_removed_sounds_check_timer >= 2.32) {
649 m_removed_sounds_check_timer = 0;
650 // Find removed sounds and clear references to them
651 std::set<s32> removed_server_ids;
652 for(std::map<s32, int>::iterator
653 i = m_sounds_server_to_client.begin();
654 i != m_sounds_server_to_client.end();) {
655 s32 server_id = i->first;
656 int client_id = i->second;
658 if(!m_sound->soundExists(client_id)) {
659 m_sounds_server_to_client.erase(server_id);
660 m_sounds_client_to_server.erase(client_id);
661 m_sounds_to_objects.erase(client_id);
662 removed_server_ids.insert(server_id);
667 if(!removed_server_ids.empty()) {
668 size_t server_ids = removed_server_ids.size();
669 assert(server_ids <= 0xFFFF);
671 NetworkPacket* pkt = new NetworkPacket(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
673 *pkt << (u16) (server_ids & 0xFFFF);
675 for(std::set<s32>::iterator i = removed_server_ids.begin();
676 i != removed_server_ids.end(); i++)
684 bool Client::loadMedia(const std::string &data, const std::string &filename)
686 // Silly irrlicht's const-incorrectness
687 Buffer<char> data_rw(data.c_str(), data.size());
691 const char *image_ext[] = {
692 ".png", ".jpg", ".bmp", ".tga",
693 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
696 name = removeStringEnd(filename, image_ext);
699 verbosestream<<"Client: Attempting to load image "
700 <<"file \""<<filename<<"\""<<std::endl;
702 io::IFileSystem *irrfs = m_device->getFileSystem();
703 video::IVideoDriver *vdrv = m_device->getVideoDriver();
705 // Create an irrlicht memory file
706 io::IReadFile *rfile = irrfs->createMemoryReadFile(
707 *data_rw, data_rw.getSize(), "_tempreadfile");
710 video::IImage *img = vdrv->createImageFromFile(rfile);
712 errorstream<<"Client: Cannot create image from data of "
713 <<"file \""<<filename<<"\""<<std::endl;
718 m_tsrc->insertSourceImage(filename, img);
725 const char *sound_ext[] = {
726 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
727 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
730 name = removeStringEnd(filename, sound_ext);
733 verbosestream<<"Client: Attempting to load sound "
734 <<"file \""<<filename<<"\""<<std::endl;
735 m_sound->loadSoundData(name, data);
739 const char *model_ext[] = {
740 ".x", ".b3d", ".md2", ".obj",
743 name = removeStringEnd(filename, model_ext);
746 verbosestream<<"Client: Storing model into memory: "
747 <<"\""<<filename<<"\""<<std::endl;
748 if(m_mesh_data.count(filename))
749 errorstream<<"Multiple models with name \""<<filename.c_str()
750 <<"\" found; replacing previous model"<<std::endl;
751 m_mesh_data[filename] = data;
755 errorstream<<"Client: Don't know how to load file \""
756 <<filename<<"\""<<std::endl;
760 // Virtual methods from con::PeerHandler
761 void Client::peerAdded(con::Peer *peer)
763 infostream<<"Client::peerAdded(): peer->id="
764 <<peer->id<<std::endl;
766 void Client::deletingPeer(con::Peer *peer, bool timeout)
768 infostream<<"Client::deletingPeer(): "
769 "Server Peer is getting deleted "
770 <<"(timeout="<<timeout<<")"<<std::endl;
775 u16 number of files requested
781 void Client::request_media(const std::list<std::string> &file_requests)
783 std::ostringstream os(std::ios_base::binary);
784 writeU16(os, TOSERVER_REQUEST_MEDIA);
785 size_t file_requests_size = file_requests.size();
786 assert(file_requests_size <= 0xFFFF);
788 // Packet dynamicly resized
789 NetworkPacket* pkt = new NetworkPacket(TOSERVER_REQUEST_MEDIA, 2 + 0);
791 *pkt << (u16) (file_requests_size & 0xFFFF);
793 for(std::list<std::string>::const_iterator i = file_requests.begin();
794 i != file_requests.end(); ++i) {
800 infostream<<"Client: Sending media request list to server ("
801 <<file_requests.size()<<" files. packet size)"<<std::endl;
804 void Client::received_media()
806 NetworkPacket* pkt = new NetworkPacket(TOSERVER_RECEIVED_MEDIA, 0);
808 infostream<<"Client: Notifying server that we received all media"
812 void Client::initLocalMapSaving(const Address &address,
813 const std::string &hostname,
814 bool is_local_server)
818 if (!g_settings->getBool("enable_local_map_saving") || is_local_server)
821 const std::string world_path = porting::path_user
822 + DIR_DELIM + "worlds"
823 + DIR_DELIM + "server_"
824 + hostname + "_" + to_string(address.getPort());
826 SubgameSpec gamespec;
828 if (!getWorldExists(world_path)) {
829 gamespec = findSubgame(g_settings->get("default_game"));
830 if (!gamespec.isValid())
831 gamespec = findSubgame("minimal");
833 gamespec = findWorldSubgame(world_path);
836 if (!gamespec.isValid()) {
837 errorstream << "Couldn't find subgame for local map saving." << std::endl;
841 localserver = new Server(world_path, gamespec, false, false);
842 localdb = new Database_SQLite3(&(ServerMap&)localserver->getMap(), world_path);
843 localdb->beginSave();
844 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
847 void Client::ReceiveAll()
849 DSTACK(__FUNCTION_NAME);
850 u32 start_ms = porting::getTimeMs();
853 // Limit time even if there would be huge amounts of data to
855 if(porting::getTimeMs() > start_ms + 100)
860 g_profiler->graphAdd("client_received_packets", 1);
862 catch(con::NoIncomingDataException &e) {
865 catch(con::InvalidIncomingDataException &e) {
866 infostream<<"Client::ReceiveAll(): "
867 "InvalidIncomingDataException: what()="
868 <<e.what()<<std::endl;
873 void Client::Receive()
875 DSTACK(__FUNCTION_NAME);
876 SharedBuffer<u8> data;
878 u32 datasize = m_con.Receive(sender_peer_id, data);
879 ProcessData(*data, datasize, sender_peer_id);
882 inline void Client::handleCommand(NetworkPacket* pkt)
884 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
885 (this->*opHandle.handler)(pkt);
889 sender_peer_id given to this shall be quaranteed to be a valid peer
891 void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
893 DSTACK(__FUNCTION_NAME);
895 // Ignore packets that don't even fit a command
897 m_packetcounter.add(60000);
901 NetworkPacket* pkt = new NetworkPacket(data, datasize, sender_peer_id);
903 ToClientCommand command = (ToClientCommand) pkt->getCommand();
905 //infostream<<"Client: received command="<<command<<std::endl;
906 m_packetcounter.add((u16)command);
909 If this check is removed, be sure to change the queue
910 system to know the ids
912 if(sender_peer_id != PEER_ID_SERVER) {
913 infostream << "Client::ProcessData(): Discarding data not "
914 "coming from server: peer_id=" << sender_peer_id
920 // Command must be handled into ToClientCommandHandler
921 if (command >= TOCLIENT_NUM_MSG_TYPES) {
922 infostream << "Client: Ignoring unknown command "
923 << command << std::endl;
927 * Those packets are handled before m_server_ser_ver is set, it's normal
928 * But we must use the new ToClientConnectionState in the future,
931 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
937 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
938 infostream << "Client: Server serialization"
939 " format invalid or not initialized."
940 " Skipping incoming command=" << command << std::endl;
946 Handle runtime commands
953 void Client::Send(NetworkPacket* pkt)
955 m_con.Send(PEER_ID_SERVER,
956 serverCommandFactoryTable[pkt->getCommand()].channel,
958 serverCommandFactoryTable[pkt->getCommand()].reliable);
961 void Client::interact(u8 action, const PointedThing& pointed)
963 if(m_state != LC_Ready) {
964 errorstream << "Client::interact() "
965 "cancelled (not connected)"
974 [5] u32 length of the next item
975 [9] serialized PointedThing
977 0: start digging (from undersurface) or use
978 1: stop digging (all parameters ignored)
980 3: place block or item (to abovesurface)
984 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INTERACT, 1 + 2 + 0);
987 *pkt << (u16)getPlayerItem();
989 std::ostringstream tmp_os(std::ios::binary);
990 pointed.serialize(tmp_os);
992 pkt->putLongString(tmp_os.str());
997 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
998 const std::map<std::string, std::string> &fields)
1000 size_t fields_size = fields.size();
1001 assert(fields_size <= 0xFFFF);
1003 NetworkPacket* pkt = new NetworkPacket(TOSERVER_NODEMETA_FIELDS, 0);
1005 *pkt << p << formname << (u16) (fields_size & 0xFFFF);
1007 for(std::map<std::string, std::string>::const_iterator
1008 i = fields.begin(); i != fields.end(); i++) {
1009 const std::string &name = i->first;
1010 const std::string &value = i->second;
1012 pkt->putLongString(value);
1018 void Client::sendInventoryFields(const std::string &formname,
1019 const std::map<std::string, std::string> &fields)
1021 size_t fields_size = fields.size();
1022 assert(fields_size <= 0xFFFF);
1024 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INVENTORY_FIELDS, 0);
1025 *pkt << formname << (u16) (fields_size & 0xFFFF);
1027 for(std::map<std::string, std::string>::const_iterator
1028 i = fields.begin(); i != fields.end(); i++) {
1029 const std::string &name = i->first;
1030 const std::string &value = i->second;
1032 pkt->putLongString(value);
1038 void Client::sendInventoryAction(InventoryAction *a)
1040 std::ostringstream os(std::ios_base::binary);
1045 std::string s = os.str();
1047 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INVENTORY_ACTION, s.size());
1048 pkt->putRawString(s.c_str(),s.size());
1053 void Client::sendChatMessage(const std::wstring &message)
1055 NetworkPacket* pkt = new NetworkPacket(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1062 void Client::sendChangePassword(const std::wstring &oldpassword,
1063 const std::wstring &newpassword)
1065 Player *player = m_env.getLocalPlayer();
1069 std::string playername = player->getName();
1070 std::string oldpwd = translatePassword(playername, oldpassword);
1071 std::string newpwd = translatePassword(playername, newpassword);
1073 NetworkPacket* pkt = new NetworkPacket(TOSERVER_PASSWORD, 2 * PASSWORD_SIZE);
1075 for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1076 *pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1079 for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1080 *pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1087 void Client::sendDamage(u8 damage)
1089 DSTACK(__FUNCTION_NAME);
1091 NetworkPacket* pkt = new NetworkPacket(TOSERVER_DAMAGE, sizeof(u8));
1096 void Client::sendBreath(u16 breath)
1098 DSTACK(__FUNCTION_NAME);
1100 NetworkPacket* pkt = new NetworkPacket(TOSERVER_BREATH, sizeof(u16));
1105 void Client::sendRespawn()
1107 DSTACK(__FUNCTION_NAME);
1109 NetworkPacket* pkt = new NetworkPacket(TOSERVER_RESPAWN, 0);
1113 void Client::sendReady()
1115 DSTACK(__FUNCTION_NAME);
1117 NetworkPacket* pkt = new NetworkPacket(TOSERVER_CLIENT_READY,
1118 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(minetest_version_hash));
1120 *pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH_ORIG
1121 << (u8) 0 << (u16) strlen(minetest_version_hash);
1123 pkt->putRawString(minetest_version_hash, (u16) strlen(minetest_version_hash));
1127 void Client::sendPlayerPos()
1129 LocalPlayer *myplayer = m_env.getLocalPlayer();
1130 if(myplayer == NULL)
1133 // Save bandwidth by only updating position when something changed
1134 if(myplayer->last_position == myplayer->getPosition() &&
1135 myplayer->last_speed == myplayer->getSpeed() &&
1136 myplayer->last_pitch == myplayer->getPitch() &&
1137 myplayer->last_yaw == myplayer->getYaw() &&
1138 myplayer->last_keyPressed == myplayer->keyPressed)
1141 myplayer->last_position = myplayer->getPosition();
1142 myplayer->last_speed = myplayer->getSpeed();
1143 myplayer->last_pitch = myplayer->getPitch();
1144 myplayer->last_yaw = myplayer->getYaw();
1145 myplayer->last_keyPressed = myplayer->keyPressed;
1149 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1150 our_peer_id = m_con.GetPeerID();
1153 // Set peer id if not set already
1154 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1155 myplayer->peer_id = our_peer_id;
1156 // Check that an existing peer_id is the same as the connection's
1157 assert(myplayer->peer_id == our_peer_id);
1159 v3f pf = myplayer->getPosition();
1160 v3f sf = myplayer->getSpeed();
1161 s32 pitch = myplayer->getPitch() * 100;
1162 s32 yaw = myplayer->getYaw() * 100;
1163 u32 keyPressed = myplayer->keyPressed;
1165 v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1166 v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1169 [0] v3s32 position*100
1170 [12] v3s32 speed*100
1171 [12+12] s32 pitch*100
1172 [12+12+4] s32 yaw*100
1173 [12+12+4+4] u32 keyPressed
1176 NetworkPacket* pkt = new NetworkPacket(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1178 *pkt << position << speed << pitch << yaw << keyPressed;
1183 void Client::sendPlayerItem(u16 item)
1185 Player *myplayer = m_env.getLocalPlayer();
1186 if(myplayer == NULL)
1189 u16 our_peer_id = m_con.GetPeerID();
1191 // Set peer id if not set already
1192 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1193 myplayer->peer_id = our_peer_id;
1195 // Check that an existing peer_id is the same as the connection's
1196 assert(myplayer->peer_id == our_peer_id);
1198 NetworkPacket* pkt = new NetworkPacket(TOSERVER_PLAYERITEM, 2);
1205 void Client::removeNode(v3s16 p)
1207 std::map<v3s16, MapBlock*> modified_blocks;
1210 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1212 catch(InvalidPositionException &e) {
1215 for(std::map<v3s16, MapBlock *>::iterator
1216 i = modified_blocks.begin();
1217 i != modified_blocks.end(); ++i) {
1218 addUpdateMeshTaskWithEdge(i->first, false, true);
1222 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1224 //TimeTaker timer1("Client::addNode()");
1226 std::map<v3s16, MapBlock*> modified_blocks;
1229 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1230 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1232 catch(InvalidPositionException &e) {
1235 for(std::map<v3s16, MapBlock *>::iterator
1236 i = modified_blocks.begin();
1237 i != modified_blocks.end(); ++i) {
1238 addUpdateMeshTaskWithEdge(i->first, false, true);
1242 void Client::setPlayerControl(PlayerControl &control)
1244 LocalPlayer *player = m_env.getLocalPlayer();
1245 assert(player != NULL);
1246 player->control = control;
1249 void Client::selectPlayerItem(u16 item)
1251 m_playeritem = item;
1252 m_inventory_updated = true;
1253 sendPlayerItem(item);
1256 // Returns true if the inventory of the local player has been
1257 // updated from the server. If it is true, it is set to false.
1258 bool Client::getLocalInventoryUpdated()
1260 bool updated = m_inventory_updated;
1261 m_inventory_updated = false;
1265 // Copies the inventory of the local player to parameter
1266 void Client::getLocalInventory(Inventory &dst)
1268 Player *player = m_env.getLocalPlayer();
1269 assert(player != NULL);
1270 dst = player->inventory;
1273 Inventory* Client::getInventory(const InventoryLocation &loc)
1276 case InventoryLocation::UNDEFINED:
1279 case InventoryLocation::CURRENT_PLAYER:
1281 Player *player = m_env.getLocalPlayer();
1282 assert(player != NULL);
1283 return &player->inventory;
1286 case InventoryLocation::PLAYER:
1288 Player *player = m_env.getPlayer(loc.name.c_str());
1291 return &player->inventory;
1294 case InventoryLocation::NODEMETA:
1296 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1299 return meta->getInventory();
1302 case InventoryLocation::DETACHED:
1304 if(m_detached_inventories.count(loc.name) == 0)
1306 return m_detached_inventories[loc.name];
1315 void Client::inventoryAction(InventoryAction *a)
1318 Send it to the server
1320 sendInventoryAction(a);
1323 Predict some local inventory changes
1325 a->clientApply(this, this);
1331 ClientActiveObject * Client::getSelectedActiveObject(
1333 v3f from_pos_f_on_map,
1334 core::line3d<f32> shootline_on_map
1337 std::vector<DistanceSortedActiveObject> objects;
1339 m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1342 // After this, the closest object is the first in the array.
1343 std::sort(objects.begin(), objects.end());
1345 for(unsigned int i=0; i<objects.size(); i++)
1347 ClientActiveObject *obj = objects[i].obj;
1349 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1350 if(selection_box == NULL)
1353 v3f pos = obj->getPosition();
1355 core::aabbox3d<f32> offsetted_box(
1356 selection_box->MinEdge + pos,
1357 selection_box->MaxEdge + pos
1360 if(offsetted_box.intersectsWithLine(shootline_on_map))
1369 std::list<std::string> Client::getConnectedPlayerNames()
1371 return m_env.getPlayerNames();
1374 float Client::getAnimationTime()
1376 return m_animation_time;
1379 int Client::getCrackLevel()
1381 return m_crack_level;
1384 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1386 m_show_highlighted = show_highlighted;
1387 v3s16 old_highlighted_pos = m_highlighted_pos;
1388 m_highlighted_pos = pos;
1389 addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1390 addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1393 void Client::setCrack(int level, v3s16 pos)
1395 int old_crack_level = m_crack_level;
1396 v3s16 old_crack_pos = m_crack_pos;
1398 m_crack_level = level;
1401 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1404 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1406 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1409 addUpdateMeshTaskForNode(pos, false, true);
1415 Player *player = m_env.getLocalPlayer();
1416 assert(player != NULL);
1420 u16 Client::getBreath()
1422 Player *player = m_env.getLocalPlayer();
1423 assert(player != NULL);
1424 return player->getBreath();
1427 bool Client::getChatMessage(std::wstring &message)
1429 if(m_chat_queue.size() == 0)
1431 message = m_chat_queue.pop_front();
1435 void Client::typeChatMessage(const std::wstring &message)
1437 // Discard empty line
1442 sendChatMessage(message);
1445 if (message[0] == L'/')
1447 m_chat_queue.push_back((std::wstring)L"issued command: " + message);
1451 LocalPlayer *player = m_env.getLocalPlayer();
1452 assert(player != NULL);
1453 std::wstring name = narrow_to_wide(player->getName());
1454 m_chat_queue.push_back((std::wstring)L"<" + name + L"> " + message);
1458 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1460 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1465 Create a task to update the mesh of the block
1468 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1471 //TimeTaker timer("data fill");
1473 // Debug: 1-6ms, avg=2ms
1475 data->setCrack(m_crack_level, m_crack_pos);
1476 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1477 data->setSmoothLighting(m_cache_smooth_lighting);
1480 // Add task to queue
1481 m_mesh_update_thread.m_queue_in.addBlock(p, data, ack_to_server, urgent);
1484 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1487 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1489 catch(InvalidPositionException &e){}
1492 for (int i=0;i<6;i++)
1495 v3s16 p = blockpos + g_6dirs[i];
1496 addUpdateMeshTask(p, false, urgent);
1498 catch(InvalidPositionException &e){}
1502 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1506 infostream<<"Client::addUpdateMeshTaskForNode(): "
1507 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1511 v3s16 blockpos = getNodeBlockPos(nodepos);
1512 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1515 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1517 catch(InvalidPositionException &e) {}
1520 if(nodepos.X == blockpos_relative.X){
1522 v3s16 p = blockpos + v3s16(-1,0,0);
1523 addUpdateMeshTask(p, false, urgent);
1525 catch(InvalidPositionException &e){}
1528 if(nodepos.Y == blockpos_relative.Y){
1530 v3s16 p = blockpos + v3s16(0,-1,0);
1531 addUpdateMeshTask(p, false, urgent);
1533 catch(InvalidPositionException &e){}
1536 if(nodepos.Z == blockpos_relative.Z){
1538 v3s16 p = blockpos + v3s16(0,0,-1);
1539 addUpdateMeshTask(p, false, urgent);
1541 catch(InvalidPositionException &e){}
1545 ClientEvent Client::getClientEvent()
1547 if(m_client_event_queue.size() == 0)
1550 event.type = CE_NONE;
1553 return m_client_event_queue.pop_front();
1556 float Client::mediaReceiveProgress()
1558 if (m_media_downloader)
1559 return m_media_downloader->getProgress();
1561 return 1.0; // downloader only exists when not yet done
1564 void Client::afterContentReceived(IrrlichtDevice *device, gui::IGUIFont* font)
1566 infostream<<"Client::afterContentReceived() started"<<std::endl;
1567 assert(m_itemdef_received);
1568 assert(m_nodedef_received);
1569 assert(mediaReceived());
1571 const wchar_t* text = wgettext("Loading textures...");
1573 // Rebuild inherited images and recreate textures
1574 infostream<<"- Rebuilding images and textures"<<std::endl;
1575 draw_load_screen(text,device, guienv, 0, 70);
1576 m_tsrc->rebuildImagesAndTextures();
1580 infostream<<"- Rebuilding shaders"<<std::endl;
1581 text = wgettext("Rebuilding shaders...");
1582 draw_load_screen(text, device, guienv, 0, 75);
1583 m_shsrc->rebuildShaders();
1586 // Update node aliases
1587 infostream<<"- Updating node aliases"<<std::endl;
1588 text = wgettext("Initializing nodes...");
1589 draw_load_screen(text, device, guienv, 0, 80);
1590 m_nodedef->updateAliases(m_itemdef);
1591 m_nodedef->setNodeRegistrationStatus(true);
1592 m_nodedef->runNodeResolverCallbacks();
1595 // Update node textures and assign shaders to each tile
1596 infostream<<"- Updating node textures"<<std::endl;
1597 m_nodedef->updateTextures(this);
1599 // Preload item textures and meshes if configured to
1600 if(g_settings->getBool("preload_item_visuals"))
1602 verbosestream<<"Updating item textures and meshes"<<std::endl;
1603 text = wgettext("Item textures...");
1604 draw_load_screen(text, device, guienv, 0, 0);
1605 std::set<std::string> names = m_itemdef->getAll();
1606 size_t size = names.size();
1609 for(std::set<std::string>::const_iterator
1610 i = names.begin(); i != names.end(); ++i)
1612 // Asking for these caches the result
1613 m_itemdef->getInventoryTexture(*i, this);
1614 m_itemdef->getWieldMesh(*i, this);
1616 percent = (count * 100 / size * 0.2) + 80;
1617 draw_load_screen(text, device, guienv, 0, percent);
1622 // Start mesh update thread after setting up content definitions
1623 infostream<<"- Starting mesh update thread"<<std::endl;
1624 m_mesh_update_thread.Start();
1628 text = wgettext("Done!");
1629 draw_load_screen(text, device, guienv, 0, 100);
1630 infostream<<"Client::afterContentReceived() done"<<std::endl;
1634 float Client::getRTT(void)
1636 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1639 float Client::getCurRate(void)
1641 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1642 m_con.getLocalStat(con::CUR_DL_RATE));
1645 float Client::getAvgRate(void)
1647 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1648 m_con.getLocalStat(con::AVG_DL_RATE));
1651 void Client::makeScreenshot(IrrlichtDevice *device)
1653 irr::video::IVideoDriver *driver = device->getVideoDriver();
1654 irr::video::IImage* const raw_image = driver->createScreenShot();
1656 irr::video::IImage* const image = driver->createImage(video::ECF_R8G8B8,
1657 raw_image->getDimension());
1660 raw_image->copyTo(image);
1661 irr::c8 filename[256];
1662 snprintf(filename, sizeof(filename), "%s" DIR_DELIM "screenshot_%u.png",
1663 g_settings->get("screenshot_path").c_str(),
1664 device->getTimer()->getRealTime());
1665 std::ostringstream sstr;
1666 if (driver->writeImageToFile(image, filename)) {
1667 sstr << "Saved screenshot to '" << filename << "'";
1669 sstr << "Failed to save screenshot '" << filename << "'";
1671 m_chat_queue.push_back(narrow_to_wide(sstr.str()));
1672 infostream << sstr.str() << std::endl;
1679 // IGameDef interface
1681 IItemDefManager* Client::getItemDefManager()
1685 INodeDefManager* Client::getNodeDefManager()
1689 ICraftDefManager* Client::getCraftDefManager()
1692 //return m_craftdef;
1694 ITextureSource* Client::getTextureSource()
1698 IShaderSource* Client::getShaderSource()
1702 scene::ISceneManager* Client::getSceneManager()
1704 return m_device->getSceneManager();
1706 u16 Client::allocateUnknownNodeId(const std::string &name)
1708 errorstream<<"Client::allocateUnknownNodeId(): "
1709 <<"Client cannot allocate node IDs"<<std::endl;
1711 return CONTENT_IGNORE;
1713 ISoundManager* Client::getSoundManager()
1717 MtEventManager* Client::getEventManager()
1722 ParticleManager* Client::getParticleManager()
1724 return &m_particle_manager;
1727 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1729 std::map<std::string, std::string>::const_iterator i =
1730 m_mesh_data.find(filename);
1731 if(i == m_mesh_data.end()){
1732 errorstream<<"Client::getMesh(): Mesh not found: \""<<filename<<"\""
1736 const std::string &data = i->second;
1737 scene::ISceneManager *smgr = m_device->getSceneManager();
1739 // Create the mesh, remove it from cache and return it
1740 // This allows unique vertex colors and other properties for each instance
1741 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1742 io::IFileSystem *irrfs = m_device->getFileSystem();
1743 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1744 *data_rw, data_rw.getSize(), filename.c_str());
1747 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1749 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1750 // of uniquely named instances and re-use them
1752 smgr->getMeshCache()->removeMesh(mesh);