]> git.lizzy.rs Git - dragonfireclient.git/blobdiff - src/client.cpp
Wieldmesh: don't force anisotropic filtering on, instead disable mipmaps
[dragonfireclient.git] / src / client.cpp
index 4d6c0cb9907337c6dc56d95e4935d64636640fa4..074ac9ba60c9b342b061a2a5cb4c2717be84c5d8 100644 (file)
@@ -17,13 +17,19 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
 
-#include "client.h"
 #include <iostream>
 #include <algorithm>
-#include "clientserver.h"
+#include <sstream>
+#include <IFileSystem.h>
 #include "jthread/jmutexautolock.h"
+#include "util/directiontables.h"
+#include "util/pointedthing.h"
+#include "util/serialize.h"
+#include "util/string.h"
+#include "strfnd.h"
+#include "client.h"
+#include "clientserver.h"
 #include "main.h"
-#include <sstream>
 #include "filesys.h"
 #include "porting.h"
 #include "mapsector.h"
@@ -37,19 +43,21 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "nodedef.h"
 #include "itemdef.h"
 #include "shader.h"
-#include <IFileSystem.h>
 #include "base64.h"
 #include "clientmap.h"
 #include "clientmedia.h"
 #include "sound.h"
-#include "util/string.h"
 #include "IMeshCache.h"
 #include "serialization.h"
-#include "util/serialize.h"
 #include "config.h"
-#include "util/directiontables.h"
-#include "util/pointedthing.h"
 #include "version.h"
+#include "drawscene.h"
+#include "subgame.h"
+#include "server.h"
+#include "database.h"
+#include "database-sqlite3.h"
+
+extern gui::IGUIEnvironment* guienv;
 
 /*
        QueuedMeshUpdate
@@ -168,6 +176,8 @@ void * MeshUpdateThread::Thread()
        
        BEGIN_DEBUG_EXCEPTION_HANDLER
 
+       porting::setThreadName("MeshUpdateThread");
+
        while(!StopRequested())
        {
                QueuedMeshUpdate *q = m_queue_in.pop();
@@ -209,6 +219,7 @@ Client::Client(
                IrrlichtDevice *device,
                const char *playername,
                std::string password,
+               bool is_simple_singleplayer_game,
                MapDrawControl &control,
                IWritableTextureSource *tsrc,
                IWritableShaderSource *shsrc,
@@ -218,6 +229,11 @@ Client::Client(
                MtEventManager *event,
                bool ipv6
 ):
+       m_packetcounter_timer(0.0),
+       m_connection_reinit_timer(0.1),
+       m_avg_rtt_timer(0.0),
+       m_playerpos_send_timer(0.0),
+       m_ignore_damage_timer(0.0),
        m_tsrc(tsrc),
        m_shsrc(shsrc),
        m_itemdef(itemdef),
@@ -239,6 +255,7 @@ Client::Client(
        m_inventory_updated(false),
        m_inventory_from_server(NULL),
        m_inventory_from_server_age(0.0),
+       m_show_hud(true),
        m_animation_time(0),
        m_crack_level(-1),
        m_crack_pos(0,0,0),
@@ -252,31 +269,55 @@ Client::Client(
        m_last_time_of_day_f(-1),
        m_time_of_day_update_timer(0),
        m_recommended_send_interval(0.1),
-       m_removed_sounds_check_timer(0)
+       m_removed_sounds_check_timer(0),
+       m_state(LC_Created)
 {
-       m_packetcounter_timer = 0.0;
-       //m_delete_unused_sectors_timer = 0.0;
-       m_connection_reinit_timer = 0.0;
-       m_avg_rtt_timer = 0.0;
-       m_playerpos_send_timer = 0.0;
-       m_ignore_damage_timer = 0.0;
-
        /*
                Add local player
        */
        {
-               Player *player = new LocalPlayer(this);
-
-               player->updateName(playername);
+               Player *player = new LocalPlayer(this, playername);
 
                m_env.addPlayer(player);
        }
+
+       if (g_settings->getBool("enable_local_map_saving")
+                       && !is_simple_singleplayer_game) {
+               const std::string world_path = porting::path_user + DIR_DELIM + "worlds"
+                               + DIR_DELIM + "server_" + g_settings->get("address")
+                               + "_" + g_settings->get("remote_port");
+
+               SubgameSpec gamespec;
+               if (!getWorldExists(world_path)) {
+                       gamespec = findSubgame(g_settings->get("default_game"));
+                       if (!gamespec.isValid())
+                               gamespec = findSubgame("minimal");
+               } else {
+                       std::string world_gameid = getWorldGameId(world_path, false);
+                       gamespec = findWorldSubgame(world_path);
+               }
+               if (!gamespec.isValid()) {
+                       errorstream << "Couldn't find subgame for local map saving." << std::endl;
+                       return;
+               }
+
+               localserver = new Server(world_path, gamespec, false, false);
+               localdb = new Database_SQLite3(&(ServerMap&)localserver->getMap(), world_path);
+               localdb->beginSave();
+               actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
+       } else {
+               localdb = NULL;
+       }
 }
 
 void Client::Stop()
 {
        //request all client managed threads to stop
        m_mesh_update_thread.Stop();
+       if (localdb != NULL) {
+               actionstream << "Local map saving ended" << std::endl;
+               localdb->endSave();
+       }
 }
 
 bool Client::isShutdown()
@@ -325,25 +366,14 @@ void Client::connect(Address address)
        m_con.Connect(address);
 }
 
-bool Client::connectedAndInitialized()
-{
-       if(m_con.Connected() == false)
-               return false;
-       
-       if(m_server_ser_ver == SER_FMT_VER_INVALID)
-               return false;
-       
-       return true;
-}
-
 void Client::step(float dtime)
 {
        DSTACK(__FUNCTION_NAME);
-       
+
        // Limit a bit
        if(dtime > 2.0)
                dtime = 2.0;
-       
+
        if(m_ignore_damage_timer > dtime)
                m_ignore_damage_timer -= dtime;
        else
@@ -367,14 +397,12 @@ void Client::step(float dtime)
                {
                        counter = 20.0;
                        
-                       infostream<<"Client packetcounter (20s):"<<std::endl;
+                       infostream << "Client packetcounter (" << m_packetcounter_timer
+                                       << "):"<<std::endl;
                        m_packetcounter.print(infostream);
                        m_packetcounter.clear();
                }
        }
-       
-       // Get connection status
-       bool connected = connectedAndInitialized();
 
 #if 0
        {
@@ -466,8 +494,13 @@ void Client::step(float dtime)
                }
        }
 #endif
-
-       if(connected == false)
+       // UGLY hack to fix 2 second startup delay caused by non existent
+       // server client startup synchronization in local server or singleplayer mode
+       static bool initial_step = true;
+       if (initial_step) {
+               initial_step = false;
+       }
+       else if(m_state == LC_Created)
        {
                float &counter = m_connection_reinit_timer;
                counter -= dtime;
@@ -479,7 +512,6 @@ void Client::step(float dtime)
                        
                        Player *myplayer = m_env.getLocalPlayer();
                        assert(myplayer != NULL);
-       
                        // Send TOSERVER_INIT
                        // [0] u16 TOSERVER_INIT
                        // [2] u8 SER_FMT_VER_HIGHEST_READ
@@ -632,7 +664,7 @@ void Client::step(float dtime)
                {
                        counter = 0.0;
                        // connectedAndInitialized() is true, peer exists.
-                       float avg_rtt = m_con.GetPeerAvgRTT(PEER_ID_SERVER);
+                       float avg_rtt = getRTT();
                        infostream<<"Client: avg_rtt="<<avg_rtt<<std::endl;
                }
        }
@@ -643,7 +675,7 @@ void Client::step(float dtime)
        {
                float &counter = m_playerpos_send_timer;
                counter += dtime;
-               if(counter >= m_recommended_send_interval)
+               if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
                {
                        counter = 0.0;
                        sendPlayerPos();
@@ -1051,6 +1083,8 @@ void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
                // Send as reliable
                m_con.Send(PEER_ID_SERVER, 1, reply, true);
 
+               m_state = LC_Init;
+
                return;
        }
 
@@ -1159,6 +1193,10 @@ void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
                        sector->insertBlock(block);
                }
 
+               if (localdb != NULL) {
+                       ((ServerMap&) localserver->getMap()).saveBlock(block, localdb);
+               }
+
                /*
                        Add it to mesh update queue and set it to be acknowledged after update.
                */
@@ -1222,7 +1260,7 @@ void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
                m_time_of_day_set = true;
 
                u32 dr = m_env.getDayNightRatio();
-               verbosestream<<"Client: time_of_day="<<time_of_day
+               infostream<<"Client: time_of_day="<<time_of_day
                                <<" time_speed="<<time_speed
                                <<" dr="<<dr<<std::endl;
        }
@@ -1792,9 +1830,13 @@ void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
                v2f align        = readV2F1000(is);
                v2f offset       = readV2F1000(is);
                v3f world_pos;
+               v2s32 size;
                try{
                        world_pos    = readV3F1000(is);
                }catch(SerializationError &e) {};
+               try{
+                       size = readV2S32(is);
+               } catch(SerializationError &e) {};
 
                ClientEvent event;
                event.type             = CE_HUDADD;
@@ -1810,6 +1852,7 @@ void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
                event.hudadd.align     = new v2f(align);
                event.hudadd.offset    = new v2f(offset);
                event.hudadd.world_pos = new v3f(world_pos);
+               event.hudadd.size      = new v2s32(size);
                m_client_event_queue.push_back(event);
        }
        else if(command == TOCLIENT_HUDRM)
@@ -1830,6 +1873,7 @@ void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
                v2f v2fdata;
                v3f v3fdata;
                u32 intdata = 0;
+               v2s32 v2s32data;
                
                std::string datastring((char *)&data[2], datasize - 2);
                std::istringstream is(datastring, std::ios_base::binary);
@@ -1844,6 +1888,8 @@ void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
                        sdata = deSerializeString(is);
                else if (stat == HUD_STAT_WORLD_POS)
                        v3fdata = readV3F1000(is);
+               else if (stat == HUD_STAT_SIZE )
+                       v2s32data = readV2S32(is);
                else
                        intdata = readU32(is);
                
@@ -1855,6 +1901,7 @@ void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
                event.hudchange.v3fdata = new v3f(v3fdata);
                event.hudchange.sdata   = new std::string(sdata);
                event.hudchange.data    = intdata;
+               event.hudchange.v2s32data = new v2s32(v2s32data);
                m_client_event_queue.push_back(event);
        }
        else if(command == TOCLIENT_HUD_SET_FLAGS)
@@ -1922,6 +1969,31 @@ void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
                event.override_day_night_ratio.ratio_f     = day_night_ratio_f;
                m_client_event_queue.push_back(event);
        }
+       else if(command == TOCLIENT_LOCAL_PLAYER_ANIMATIONS)
+       {
+               std::string datastring((char *)&data[2], datasize - 2);
+               std::istringstream is(datastring, std::ios_base::binary);
+
+               LocalPlayer *player = m_env.getLocalPlayer();
+               assert(player != NULL);
+
+               player->local_animations[0] = readV2S32(is);
+               player->local_animations[1] = readV2S32(is);
+               player->local_animations[2] = readV2S32(is);
+               player->local_animations[3] = readV2S32(is);
+               player->local_animation_speed = readF1000(is);
+       }
+       else if(command == TOCLIENT_EYE_OFFSET)
+       {
+               std::string datastring((char *)&data[2], datasize - 2);
+               std::istringstream is(datastring, std::ios_base::binary);
+
+               LocalPlayer *player = m_env.getLocalPlayer();
+               assert(player != NULL);
+
+               player->eye_offset_first = readV3F1000(is);
+               player->eye_offset_third = readV3F1000(is);
+       }
        else
        {
                infostream<<"Client: Ignoring unknown command "
@@ -1937,7 +2009,7 @@ void Client::Send(u16 channelnum, SharedBuffer<u8> data, bool reliable)
 
 void Client::interact(u8 action, const PointedThing& pointed)
 {
-       if(connectedAndInitialized() == false){
+       if(m_state != LC_Ready){
                infostream<<"Client::interact() "
                                "cancelled (not connected)"
                                <<std::endl;
@@ -2053,8 +2125,10 @@ void Client::sendChatMessage(const std::wstring &message)
        
        // Write length
        size_t messagesize = message.size();
-       assert(messagesize <= 0xFFFF);
-       writeU16(buf, (u16) (messagesize & 0xFF));
+       if (messagesize > 0xFFFF) {
+               messagesize = 0xFFFF;
+       }
+       writeU16(buf, (u16) messagesize);
        os.write((char*)buf, 2);
        
        // Write string
@@ -2072,8 +2146,8 @@ void Client::sendChatMessage(const std::wstring &message)
        Send(0, data, true);
 }
 
-void Client::sendChangePassword(const std::wstring oldpassword,
-               const std::wstring newpassword)
+void Client::sendChangePassword(const std::wstring &oldpassword,
+                                const std::wstring &newpassword)
 {
        Player *player = m_env.getLocalPlayer();
        if(player == NULL)
@@ -2152,6 +2226,27 @@ void Client::sendRespawn()
        Send(0, data, true);
 }
 
+void Client::sendReady()
+{
+       DSTACK(__FUNCTION_NAME);
+       std::ostringstream os(std::ios_base::binary);
+
+       writeU16(os, TOSERVER_CLIENT_READY);
+       writeU8(os,VERSION_MAJOR);
+       writeU8(os,VERSION_MINOR);
+       writeU8(os,VERSION_PATCH_ORIG);
+       writeU8(os,0);
+
+       writeU16(os,strlen(minetest_version_hash));
+       os.write(minetest_version_hash,strlen(minetest_version_hash));
+
+       // Make data buffer
+       std::string s = os.str();
+       SharedBuffer<u8> data((u8*)s.c_str(), s.size());
+       // Send as reliable
+       Send(0, data, true);
+}
+
 void Client::sendPlayerPos()
 {
        LocalPlayer *myplayer = m_env.getLocalPlayer();
@@ -2246,20 +2341,19 @@ void Client::removeNode(v3s16 p)
        {
        }
        
-       // add urgent task to update the modified node
-       addUpdateMeshTaskForNode(p, false, true);
-
        for(std::map<v3s16, MapBlock * >::iterator
                        i = modified_blocks.begin();
                        i != modified_blocks.end(); ++i)
        {
-               addUpdateMeshTaskWithEdge(i->first);
+               addUpdateMeshTask(i->first, false, false);
        }
+       // add urgent task to update the modified node
+       addUpdateMeshTaskForNode(p, false, true);
 }
 
 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
 {
-       TimeTaker timer1("Client::addNode()");
+       //TimeTaker timer1("Client::addNode()");
 
        std::map<v3s16, MapBlock*> modified_blocks;
 
@@ -2275,7 +2369,7 @@ void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
                        i = modified_blocks.begin();
                        i != modified_blocks.end(); ++i)
        {
-               addUpdateMeshTaskWithEdge(i->first);
+               addUpdateMeshTask(i->first, false, false);
        }
 }
        
@@ -2421,6 +2515,15 @@ int Client::getCrackLevel()
        return m_crack_level;
 }
 
+void Client::setHighlighted(v3s16 pos, bool show_hud)
+{
+       m_show_hud = show_hud;
+       v3s16 old_highlighted_pos = m_highlighted_pos;
+       m_highlighted_pos = pos;
+       addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
+       addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
+}
+
 void Client::setCrack(int level, v3s16 pos)
 {
        int old_crack_level = m_crack_level;
@@ -2475,16 +2578,14 @@ void Client::typeChatMessage(const std::wstring &message)
        // Show locally
        if (message[0] == L'/')
        {
-               m_chat_queue.push_back(
-                               (std::wstring)L"issued command: "+message);
+               m_chat_queue.push_back((std::wstring)L"issued command: " + message);
        }
        else
        {
                LocalPlayer *player = m_env.getLocalPlayer();
                assert(player != NULL);
                std::wstring name = narrow_to_wide(player->getName());
-               m_chat_queue.push_back(
-                               (std::wstring)L"<"+name+L"> "+message);
+               m_chat_queue.push_back((std::wstring)L"<" + name + L"> " + message);
        }
 }
 
@@ -2493,22 +2594,23 @@ void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
        MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
        if(b == NULL)
                return;
-       
+
        /*
                Create a task to update the mesh of the block
        */
-       
+
        MeshMakeData *data = new MeshMakeData(this);
-       
+
        {
                //TimeTaker timer("data fill");
                // Release: ~0ms
                // Debug: 1-6ms, avg=2ms
                data->fill(b);
                data->setCrack(m_crack_level, m_crack_pos);
+               data->setHighlighted(m_highlighted_pos, m_show_hud);
                data->setSmoothLighting(g_settings->getBool("smooth_lighting"));
        }
-       
+
        // Add task to queue
        m_mesh_update_thread.m_queue_in.addBlock(p, data, ack_to_server, urgent);
 }
@@ -2596,10 +2698,6 @@ float Client::mediaReceiveProgress()
                return 1.0; // downloader only exists when not yet done
 }
 
-void draw_load_screen(const std::wstring &text,
-               IrrlichtDevice* device, gui::IGUIFont* font,
-               float dtime=0 ,int percent=0, bool clouds=true);
-
 void Client::afterContentReceived(IrrlichtDevice *device, gui::IGUIFont* font)
 {
        infostream<<"Client::afterContentReceived() started"<<std::endl;
@@ -2619,16 +2717,16 @@ void Client::afterContentReceived(IrrlichtDevice *device, gui::IGUIFont* font)
        infostream<<"- Updating node aliases"<<std::endl;
        m_nodedef->updateAliases(m_itemdef);
 
-       // Update node textures
+       // Update node textures and assign shaders to each tile
        infostream<<"- Updating node textures"<<std::endl;
-       m_nodedef->updateTextures(m_tsrc);
+       m_nodedef->updateTextures(this);
 
        // Preload item textures and meshes if configured to
        if(g_settings->getBool("preload_item_visuals"))
        {
                verbosestream<<"Updating item textures and meshes"<<std::endl;
                wchar_t* text = wgettext("Item textures...");
-               draw_load_screen(text,device,font,0,0);
+               draw_load_screen(text, device, guienv, font, 0, 0);
                std::set<std::string> names = m_itemdef->getAll();
                size_t size = names.size();
                size_t count = 0;
@@ -2641,7 +2739,7 @@ void Client::afterContentReceived(IrrlichtDevice *device, gui::IGUIFont* font)
                        count++;
                        percent = count*100/size;
                        if (count%50 == 0) // only update every 50 item
-                               draw_load_screen(text,device,font,0,percent);
+                               draw_load_screen(text, device, guienv, font, 0, percent);
                }
                delete[] text;
        }
@@ -2650,15 +2748,53 @@ void Client::afterContentReceived(IrrlichtDevice *device, gui::IGUIFont* font)
        infostream<<"- Starting mesh update thread"<<std::endl;
        m_mesh_update_thread.Start();
        
+       m_state = LC_Ready;
+       sendReady();
        infostream<<"Client::afterContentReceived() done"<<std::endl;
 }
 
 float Client::getRTT(void)
 {
-       try{
-               return m_con.GetPeerAvgRTT(PEER_ID_SERVER);
-       } catch(con::PeerNotFoundException &e){
-               return 1337;
+       return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
+}
+
+float Client::getCurRate(void)
+{
+       return ( m_con.getLocalStat(con::CUR_INC_RATE) +
+                       m_con.getLocalStat(con::CUR_DL_RATE));
+}
+
+float Client::getAvgRate(void)
+{
+       return ( m_con.getLocalStat(con::AVG_INC_RATE) +
+                       m_con.getLocalStat(con::AVG_DL_RATE));
+}
+
+void Client::makeScreenshot(IrrlichtDevice *device)
+{
+       irr::video::IVideoDriver *driver = device->getVideoDriver();
+       irr::video::IImage* const raw_image = driver->createScreenShot();
+       if (raw_image) {
+               irr::video::IImage* const image = driver->createImage(video::ECF_R8G8B8, 
+                       raw_image->getDimension());
+
+               if (image) {
+                       raw_image->copyTo(image);
+                       irr::c8 filename[256];
+                       snprintf(filename, sizeof(filename), "%s" DIR_DELIM "screenshot_%u.png",
+                                g_settings->get("screenshot_path").c_str(),
+                                device->getTimer()->getRealTime());
+                       std::stringstream sstr;
+                       if (driver->writeImageToFile(image, filename)) {
+                               sstr << "Saved screenshot to '" << filename << "'";
+                       } else {
+                               sstr << "Failed to save screenshot '" << filename << "'";
+                       }
+                       m_chat_queue.push_back(narrow_to_wide(sstr.str()));
+                       infostream << sstr << std::endl;
+                       image->drop();
+               }
+               raw_image->drop();
        }
 }
 
@@ -2685,6 +2821,10 @@ IShaderSource* Client::getShaderSource()
 {
        return m_shsrc;
 }
+scene::ISceneManager* Client::getSceneManager()
+{
+       return m_device->getSceneManager();
+}
 u16 Client::allocateUnknownNodeId(const std::string &name)
 {
        errorstream<<"Client::allocateUnknownNodeId(): "