3 Copyright (C) 2010-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.
21 #include "irrlichttypes_extrabloated.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
27 #include <IMaterialRendererServices.h>
28 #include "IMeshCache.h"
31 #include "guiPasswordChange.h"
32 #include "guiVolumeChange.h"
33 #include "guiFormSpecMenu.h"
35 #include "guiChatConsole.h"
39 #include "particles.h"
44 #include "mainmenumanager.h"
48 // Needed for determining pointing to nodes
50 #include "nodemetadata.h"
51 #include "main.h" // For g_settings
53 #include "tile.h" // For TextureSource
54 #include "shader.h" // For ShaderSource
55 #include "logoutputbuffer.h"
57 #include "quicktune_shortcutter.h"
58 #include "clientmap.h"
63 #include "sound_openal.h"
65 #include "event_manager.h"
68 #include "util/directiontables.h"
69 #include "util/pointedthing.h"
70 #include "drawscene.h"
71 #include "content_cao.h"
73 #ifdef HAVE_TOUCHSCREENGUI
74 #include "touchscreengui.h"
81 struct TextDestNodeMetadata : public TextDest
83 TextDestNodeMetadata(v3s16 p, Client *client)
88 // This is deprecated I guess? -celeron55
89 void gotText(std::wstring text)
91 std::string ntext = wide_to_narrow(text);
92 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
93 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
94 std::map<std::string, std::string> fields;
95 fields["text"] = ntext;
96 m_client->sendNodemetaFields(m_p, "", fields);
98 void gotText(std::map<std::string, std::string> fields)
100 m_client->sendNodemetaFields(m_p, "", fields);
107 struct TextDestPlayerInventory : public TextDest
109 TextDestPlayerInventory(Client *client)
114 TextDestPlayerInventory(Client *client, std::string formname)
117 m_formname = formname;
119 void gotText(std::map<std::string, std::string> fields)
121 m_client->sendInventoryFields(m_formname, fields);
127 struct LocalFormspecHandler : public TextDest
129 LocalFormspecHandler();
130 LocalFormspecHandler(std::string formname) :
133 m_formname = formname;
136 LocalFormspecHandler(std::string formname, Client *client) :
139 m_formname = formname;
142 void gotText(std::wstring message) {
143 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
146 void gotText(std::map<std::string, std::string> fields)
148 if (m_formname == "MT_PAUSE_MENU") {
149 if (fields.find("btn_sound") != fields.end()) {
150 g_gamecallback->changeVolume();
154 if (fields.find("btn_exit_menu") != fields.end()) {
155 g_gamecallback->disconnect();
159 if (fields.find("btn_exit_os") != fields.end()) {
160 g_gamecallback->exitToOS();
164 if (fields.find("btn_change_password") != fields.end()) {
165 g_gamecallback->changePassword();
169 if (fields.find("quit") != fields.end()) {
173 if (fields.find("btn_continue") != fields.end()) {
177 if (m_formname == "MT_CHAT_MENU") {
178 assert(m_client != 0);
179 if ((fields.find("btn_send") != fields.end()) ||
180 (fields.find("quit") != fields.end())) {
181 if (fields.find("f_text") != fields.end()) {
182 m_client->typeChatMessage(narrow_to_wide(fields["f_text"]));
188 if (m_formname == "MT_DEATH_SCREEN") {
189 assert(m_client != 0);
190 if ((fields.find("btn_respawn") != fields.end())) {
191 m_client->sendRespawn();
195 if (fields.find("quit") != fields.end()) {
196 m_client->sendRespawn();
201 // don't show error message for unhandled cursor keys
202 if ( (fields.find("key_up") != fields.end()) ||
203 (fields.find("key_down") != fields.end()) ||
204 (fields.find("key_left") != fields.end()) ||
205 (fields.find("key_right") != fields.end())) {
209 errorstream << "LocalFormspecHandler::gotText unhandled >" << m_formname << "< event" << std::endl;
211 for (std::map<std::string,std::string>::iterator iter = fields.begin();
212 iter != fields.end(); iter++) {
213 errorstream << "\t"<< i << ": " << iter->first << "=" << iter->second << std::endl;
221 /* Form update callback */
223 class NodeMetadataFormSource: public IFormSource
226 NodeMetadataFormSource(ClientMap *map, v3s16 p):
231 std::string getForm()
233 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
236 return meta->getString("formspec");
238 std::string resolveText(std::string str)
240 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
243 return meta->resolveString(str);
250 class PlayerInventoryFormSource: public IFormSource
253 PlayerInventoryFormSource(Client *client):
257 std::string getForm()
259 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
260 return player->inventory_formspec;
267 Check if a node is pointable
269 inline bool isPointableNode(const MapNode& n,
270 Client *client, bool liquids_pointable)
272 const ContentFeatures &features = client->getNodeDefManager()->get(n);
273 return features.pointable ||
274 (liquids_pointable && features.isLiquid());
278 Find what the player is pointing at
280 PointedThing getPointedThing(Client *client, v3f player_position,
281 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
282 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
283 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
287 hilightboxes.clear();
288 selected_object = NULL;
290 INodeDefManager *nodedef = client->getNodeDefManager();
291 ClientMap &map = client->getEnv().getClientMap();
293 f32 mindistance = BS * 1001;
295 // First try to find a pointed at active object
298 selected_object = client->getSelectedActiveObject(d*BS,
299 camera_position, shootline);
301 if(selected_object != NULL)
303 if(selected_object->doShowSelectionBox())
305 aabb3f *selection_box = selected_object->getSelectionBox();
306 // Box should exist because object was
307 // returned in the first place
308 assert(selection_box);
310 v3f pos = selected_object->getPosition();
311 hilightboxes.push_back(aabb3f(
312 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
313 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
316 mindistance = (selected_object->getPosition() - camera_position).getLength();
318 result.type = POINTEDTHING_OBJECT;
319 result.object_id = selected_object->getId();
323 // That didn't work, try to find a pointed at node
326 v3s16 pos_i = floatToInt(player_position, BS);
328 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
332 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
333 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
334 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
335 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
336 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
337 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
339 // Prevent signed number overflow
347 for(s16 y = ystart; y <= yend; y++)
348 for(s16 z = zstart; z <= zend; z++)
349 for(s16 x = xstart; x <= xend; x++)
354 n = map.getNode(v3s16(x,y,z));
356 catch(InvalidPositionException &e)
360 if(!isPointableNode(n, client, liquids_pointable))
363 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
366 v3f npf = intToFloat(np, BS);
368 for(std::vector<aabb3f>::const_iterator
370 i != boxes.end(); i++)
376 for(u16 j=0; j<6; j++)
378 v3s16 facedir = g_6dirs[j];
379 aabb3f facebox = box;
383 facebox.MinEdge.X = facebox.MaxEdge.X-d;
384 else if(facedir.X < 0)
385 facebox.MaxEdge.X = facebox.MinEdge.X+d;
386 else if(facedir.Y > 0)
387 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
388 else if(facedir.Y < 0)
389 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
390 else if(facedir.Z > 0)
391 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
392 else if(facedir.Z < 0)
393 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
395 v3f centerpoint = facebox.getCenter();
396 f32 distance = (centerpoint - camera_position).getLength();
397 if(distance >= mindistance)
399 if(!facebox.intersectsWithLine(shootline))
402 v3s16 np_above = np + facedir;
404 result.type = POINTEDTHING_NODE;
405 result.node_undersurface = np;
406 result.node_abovesurface = np_above;
407 mindistance = distance;
409 hilightboxes.clear();
410 if (!g_settings->getBool("enable_node_highlighting")) {
411 for(std::vector<aabb3f>::const_iterator
413 i2 != boxes.end(); i2++)
416 box.MinEdge += npf + v3f(-d,-d,-d) - intToFloat(camera_offset, BS);
417 box.MaxEdge += npf + v3f(d,d,d) - intToFloat(camera_offset, BS);
418 hilightboxes.push_back(box);
428 /* Profiler display */
430 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
431 gui::IGUIFont *font, u32 text_height, u32 show_profiler,
432 u32 show_profiler_max)
434 if(show_profiler == 0)
436 guitext_profiler->setVisible(false);
441 std::ostringstream os(std::ios_base::binary);
442 g_profiler->printPage(os, show_profiler, show_profiler_max);
443 std::wstring text = narrow_to_wide(os.str());
444 guitext_profiler->setText(text.c_str());
445 guitext_profiler->setVisible(true);
447 s32 w = font->getDimension(text.c_str()).Width;
450 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
451 8+(text_height+5)*2 +
452 font->getDimension(text.c_str()).Height);
453 guitext_profiler->setRelativePosition(rect);
454 guitext_profiler->setVisible(true);
462 Profiler::GraphValues values;
468 Meta(float initial=0, video::SColor color=
469 video::SColor(255,255,255,255)):
475 std::list<Piece> m_log;
483 void put(const Profiler::GraphValues &values)
486 piece.values = values;
487 m_log.push_back(piece);
488 while(m_log.size() > m_log_max_size)
489 m_log.erase(m_log.begin());
492 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
493 gui::IGUIFont* font) const
495 std::map<std::string, Meta> m_meta;
496 for(std::list<Piece>::const_iterator k = m_log.begin();
497 k != m_log.end(); k++)
499 const Piece &piece = *k;
500 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
501 i != piece.values.end(); i++){
502 const std::string &id = i->first;
503 const float &value = i->second;
504 std::map<std::string, Meta>::iterator j =
506 if(j == m_meta.end()){
507 m_meta[id] = Meta(value);
510 if(value < j->second.min)
511 j->second.min = value;
512 if(value > j->second.max)
513 j->second.max = value;
518 static const video::SColor usable_colors[] = {
519 video::SColor(255,255,100,100),
520 video::SColor(255,90,225,90),
521 video::SColor(255,100,100,255),
522 video::SColor(255,255,150,50),
523 video::SColor(255,220,220,100)
525 static const u32 usable_colors_count =
526 sizeof(usable_colors) / sizeof(*usable_colors);
527 u32 next_color_i = 0;
528 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
529 i != m_meta.end(); i++){
530 Meta &meta = i->second;
531 video::SColor color(255,200,200,200);
532 if(next_color_i < usable_colors_count)
533 color = usable_colors[next_color_i++];
538 s32 textx = x_left + m_log_max_size + 15;
539 s32 textx2 = textx + 200 - 15;
543 u32 num_graphs = m_meta.size();
544 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
546 video::SColor bgcolor(120,0,0,0);
547 driver->draw2DRectangle(bgcolor, rect, NULL);
551 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
552 i != m_meta.end(); i++){
553 const std::string &id = i->first;
554 const Meta &meta = i->second;
556 s32 y = y_bottom - meta_i * 50;
557 float show_min = meta.min;
558 float show_max = meta.max;
559 if(show_min >= -0.0001 && show_max >= -0.0001){
560 if(show_min <= show_max * 0.5)
565 snprintf(buf, 10, "%.3g", show_max);
566 font->draw(narrow_to_wide(buf).c_str(),
567 core::rect<s32>(textx, y - graphh,
568 textx2, y - graphh + texth),
570 snprintf(buf, 10, "%.3g", show_min);
571 font->draw(narrow_to_wide(buf).c_str(),
572 core::rect<s32>(textx, y - texth,
575 font->draw(narrow_to_wide(id).c_str(),
576 core::rect<s32>(textx, y - graphh/2 - texth/2,
577 textx2, y - graphh/2 + texth/2),
580 s32 graph1h = graphh;
581 bool relativegraph = (show_min != 0 && show_min != show_max);
582 float lastscaledvalue = 0.0;
583 bool lastscaledvalue_exists = false;
584 for(std::list<Piece>::const_iterator j = m_log.begin();
585 j != m_log.end(); j++)
587 const Piece &piece = *j;
589 bool value_exists = false;
590 Profiler::GraphValues::const_iterator k =
591 piece.values.find(id);
592 if(k != piece.values.end()){
598 lastscaledvalue_exists = false;
601 float scaledvalue = 1.0;
602 if(show_max != show_min)
603 scaledvalue = (value - show_min) / (show_max - show_min);
604 if(scaledvalue == 1.0 && value == 0){
606 lastscaledvalue_exists = false;
610 if(lastscaledvalue_exists){
611 s32 ivalue1 = lastscaledvalue * graph1h;
612 s32 ivalue2 = scaledvalue * graph1h;
613 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
614 v2s32(x, graph1y - ivalue2), meta.color);
616 lastscaledvalue = scaledvalue;
617 lastscaledvalue_exists = true;
619 s32 ivalue = scaledvalue * graph1h;
620 driver->draw2DLine(v2s32(x, graph1y),
621 v2s32(x, graph1y - ivalue), meta.color);
630 class NodeDugEvent: public MtEvent
636 NodeDugEvent(v3s16 p, MapNode n):
640 const char* getType() const
646 ISoundManager *m_sound;
647 INodeDefManager *m_ndef;
649 float m_player_step_timer;
651 SimpleSoundSpec m_player_step_sound;
652 SimpleSoundSpec m_player_leftpunch_sound;
653 SimpleSoundSpec m_player_rightpunch_sound;
655 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
658 m_player_step_timer(0)
662 void playPlayerStep()
664 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
665 m_player_step_timer = 0.03;
666 m_sound->playSound(m_player_step_sound, false);
670 static void viewBobbingStep(MtEvent *e, void *data)
672 SoundMaker *sm = (SoundMaker*)data;
673 sm->playPlayerStep();
676 static void playerRegainGround(MtEvent *e, void *data)
678 SoundMaker *sm = (SoundMaker*)data;
679 sm->playPlayerStep();
682 static void playerJump(MtEvent *e, void *data)
684 //SoundMaker *sm = (SoundMaker*)data;
687 static void cameraPunchLeft(MtEvent *e, void *data)
689 SoundMaker *sm = (SoundMaker*)data;
690 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
693 static void cameraPunchRight(MtEvent *e, void *data)
695 SoundMaker *sm = (SoundMaker*)data;
696 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
699 static void nodeDug(MtEvent *e, void *data)
701 SoundMaker *sm = (SoundMaker*)data;
702 NodeDugEvent *nde = (NodeDugEvent*)e;
703 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
706 static void playerDamage(MtEvent *e, void *data)
708 SoundMaker *sm = (SoundMaker*)data;
709 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
712 static void playerFallingDamage(MtEvent *e, void *data)
714 SoundMaker *sm = (SoundMaker*)data;
715 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
718 void registerReceiver(MtEventManager *mgr)
720 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
721 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
722 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
723 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
724 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
725 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
726 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
727 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
730 void step(float dtime)
732 m_player_step_timer -= dtime;
736 // Locally stored sounds don't need to be preloaded because of this
737 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
739 std::set<std::string> m_fetched;
742 void fetchSounds(const std::string &name,
743 std::set<std::string> &dst_paths,
744 std::set<std::string> &dst_datas)
746 if(m_fetched.count(name))
748 m_fetched.insert(name);
749 std::string base = porting::path_share + DIR_DELIM + "testsounds";
750 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
751 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
752 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
753 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
754 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
755 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
756 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
757 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
758 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
759 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
760 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
764 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
767 bool *m_force_fog_off;
772 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
773 f32 *fog_range, Client *client):
775 m_force_fog_off(force_fog_off),
776 m_fog_range(fog_range),
779 ~GameGlobalShaderConstantSetter() {}
781 virtual void onSetConstants(video::IMaterialRendererServices *services,
788 video::SColor bgcolor = m_sky->getBgColor();
789 video::SColorf bgcolorf(bgcolor);
790 float bgcolorfa[4] = {
796 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
799 float fog_distance = 10000*BS;
800 if(g_settings->getBool("enable_fog") && !*m_force_fog_off)
801 fog_distance = *m_fog_range;
802 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
805 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
806 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
807 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
809 u32 animation_timer = porting::getTimeMs() % 100000;
810 float animation_timer_f = (float)animation_timer / 100000.0;
811 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
812 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
814 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
815 v3f eye_position = player->getEyePosition();
816 services->setPixelShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
817 services->setVertexShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
819 // Uniform sampler layers
823 // before 1.8 there isn't a "integer interface", only float
824 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
825 services->setPixelShaderConstant("baseTexture" , (irr::f32*)&layer0, 1);
826 services->setPixelShaderConstant("normalTexture" , (irr::f32*)&layer1, 1);
827 services->setPixelShaderConstant("useNormalmap" , (irr::f32*)&layer2, 1);
829 services->setPixelShaderConstant("baseTexture" , (irr::s32*)&layer0, 1);
830 services->setPixelShaderConstant("normalTexture" , (irr::s32*)&layer1, 1);
831 services->setPixelShaderConstant("useNormalmap" , (irr::s32*)&layer2, 1);
836 bool nodePlacementPrediction(Client &client,
837 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
839 std::string prediction = playeritem_def.node_placement_prediction;
840 INodeDefManager *nodedef = client.ndef();
841 ClientMap &map = client.getEnv().getClientMap();
843 if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
845 verbosestream<<"Node placement prediction for "
846 <<playeritem_def.name<<" is "
847 <<prediction<<std::endl;
848 v3s16 p = neighbourpos;
849 // Place inside node itself if buildable_to
851 MapNode n_under = map.getNode(nodepos);
852 if(nodedef->get(n_under).buildable_to)
854 else if (!nodedef->get(map.getNode(p)).buildable_to)
856 }catch(InvalidPositionException &e){}
857 // Find id of predicted node
859 bool found = nodedef->getId(prediction, id);
861 errorstream<<"Node placement prediction failed for "
862 <<playeritem_def.name<<" (places "
864 <<") - Name not known"<<std::endl;
867 // Predict param2 for facedir and wallmounted nodes
869 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
870 v3s16 dir = nodepos - neighbourpos;
871 if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
872 param2 = dir.Y < 0 ? 1 : 0;
873 } else if(abs(dir.X) > abs(dir.Z)){
874 param2 = dir.X < 0 ? 3 : 2;
876 param2 = dir.Z < 0 ? 5 : 4;
879 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
880 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
881 if(abs(dir.X) > abs(dir.Z)){
882 param2 = dir.X < 0 ? 3 : 1;
884 param2 = dir.Z < 0 ? 2 : 0;
887 assert(param2 >= 0 && param2 <= 5);
888 //Check attachment if node is in group attached_node
889 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
890 static v3s16 wallmounted_dirs[8] = {
899 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
900 pp = p + wallmounted_dirs[param2];
902 pp = p + v3s16(0,-1,0);
903 if(!nodedef->get(map.getNode(pp)).walkable)
906 // Add node to client map
907 MapNode n(id, 0, param2);
909 LocalPlayer* player = client.getEnv().getLocalPlayer();
911 // Dont place node when player would be inside new node
912 // NOTE: This is to be eventually implemented by a mod as client-side Lua
913 if (!nodedef->get(n).walkable ||
914 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
915 (nodedef->get(n).walkable &&
916 neighbourpos != player->getStandingNodePos() + v3s16(0,1,0) &&
917 neighbourpos != player->getStandingNodePos() + v3s16(0,2,0))) {
919 // This triggers the required mesh update too
920 client.addNode(p, n);
923 }catch(InvalidPositionException &e){
924 errorstream<<"Node placement prediction failed for "
925 <<playeritem_def.name<<" (places "
927 <<") - Position not loaded"<<std::endl;
933 static inline void create_formspec_menu(GUIFormSpecMenu** cur_formspec,
934 InventoryManager *invmgr, IGameDef *gamedef,
935 IWritableTextureSource* tsrc, IrrlichtDevice * device,
936 IFormSource* fs_src, TextDest* txt_dest, Client* client
939 if (*cur_formspec == 0) {
940 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
941 invmgr, gamedef, tsrc, fs_src, txt_dest, cur_formspec, client);
942 (*cur_formspec)->doPause = false;
943 (*cur_formspec)->drop();
946 (*cur_formspec)->setFormSource(fs_src);
947 (*cur_formspec)->setTextDest(txt_dest);
952 #define SIZE_TAG "size[11,5.5]"
954 #define SIZE_TAG "size[11,5.5,true]"
957 static void show_chat_menu(GUIFormSpecMenu** cur_formspec,
958 InventoryManager *invmgr, IGameDef *gamedef,
959 IWritableTextureSource* tsrc, IrrlichtDevice * device,
960 Client* client, std::string text)
962 std::string formspec =
963 FORMSPEC_VERSION_STRING
965 "field[3,2.35;6,0.5;f_text;;" + text + "]"
966 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
970 /* Note: FormspecFormSource and LocalFormspecHandler
971 * are deleted by guiFormSpecMenu */
972 FormspecFormSource* fs_src = new FormspecFormSource(formspec);
973 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
975 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
978 static void show_deathscreen(GUIFormSpecMenu** cur_formspec,
979 InventoryManager *invmgr, IGameDef *gamedef,
980 IWritableTextureSource* tsrc, IrrlichtDevice * device, Client* client)
982 std::string formspec =
983 std::string(FORMSPEC_VERSION_STRING) +
985 "bgcolor[#320000b4;true]"
986 "label[4.85,1.35;You died.]"
987 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
991 /* Note: FormspecFormSource and LocalFormspecHandler
992 * are deleted by guiFormSpecMenu */
993 FormspecFormSource* fs_src = new FormspecFormSource(formspec);
994 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
996 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
999 /******************************************************************************/
1000 static void show_pause_menu(GUIFormSpecMenu** cur_formspec,
1001 InventoryManager *invmgr, IGameDef *gamedef,
1002 IWritableTextureSource* tsrc, IrrlichtDevice * device,
1003 bool singleplayermode)
1006 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1007 "No menu visible:\n"
1008 "- single tap: button activate\n"
1009 "- double tap: place/use\n"
1010 "- slide finger: look around\n"
1011 "Menu/Inventory visible:\n"
1012 "- double tap (outside):\n"
1014 "- touch stack, touch slot:\n"
1016 "- touch&drag, tap 2nd finger\n"
1017 " --> place single item to slot\n"
1020 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1022 "- Space: jump/climb\n"
1023 "- Shift: sneak/go down\n"
1026 "- Mouse: turn/look\n"
1027 "- Mouse left: dig/punch\n"
1028 "- Mouse right: place/use\n"
1029 "- Mouse wheel: select item\n"
1033 float ypos = singleplayermode ? 1.0 : 0.5;
1034 std::ostringstream os;
1036 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1037 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1038 << wide_to_narrow(wstrgettext("Continue")) << "]";
1040 if (!singleplayermode) {
1041 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1042 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1045 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1046 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1047 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1048 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1049 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1050 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1051 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1052 << "textarea[0.4,0.25;3.5,6;;" << "Minetest\n"
1053 << minetest_build_info << "\n"
1054 << "path_user = " << wrap_rows(porting::path_user, 20)
1058 /* Note: FormspecFormSource and LocalFormspecHandler *
1059 * are deleted by guiFormSpecMenu */
1060 FormspecFormSource* fs_src = new FormspecFormSource(os.str());
1061 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1063 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1065 (*cur_formspec)->doPause = true;
1068 /******************************************************************************/
1069 static void updateChat(Client& client, f32 dtime, bool show_debug,
1070 const v2u32& screensize, bool show_chat, u32 show_profiler,
1071 ChatBackend& chat_backend, gui::IGUIStaticText* guitext_chat,
1072 gui::IGUIFont* font)
1074 // Add chat log output for errors to be shown in chat
1075 static LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1077 // Get new messages from error log buffer
1078 while(!chat_log_error_buf.empty()) {
1079 chat_backend.addMessage(L"", narrow_to_wide(chat_log_error_buf.get()));
1082 // Get new messages from client
1083 std::wstring message;
1084 while (client.getChatMessage(message)) {
1085 chat_backend.addUnparsedMessage(message);
1088 // Remove old messages
1089 chat_backend.step(dtime);
1091 // Display all messages in a static text element
1092 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1093 std::wstring recent_chat = chat_backend.getRecentChat();
1095 // TODO replace by fontengine fcts
1096 unsigned int line_height = font->getDimension(L"Ay").Height + font->getKerningHeight();
1098 guitext_chat->setText(recent_chat.c_str());
1100 // Update gui element size and position
1101 s32 chat_y = 5 + line_height;
1103 chat_y += line_height;
1105 core::rect<s32> rect(10, chat_y, font->getDimension(recent_chat.c_str()).Width +10,
1106 chat_y + (recent_chat_count * line_height));
1108 guitext_chat->setRelativePosition(rect);
1109 // Don't show chat if disabled or empty or profiler is enabled
1110 guitext_chat->setVisible(
1111 show_chat && recent_chat_count != 0 && !show_profiler);
1114 /******************************************************************************/
1115 void the_game(bool &kill, bool random_input, InputHandler *input,
1116 IrrlichtDevice *device, gui::IGUIFont* font, std::string map_dir,
1117 std::string playername, std::string password,
1118 std::string address /* If "", local server is used */,
1119 u16 port, std::wstring &error_message, ChatBackend &chat_backend,
1120 const SubgameSpec &gamespec /* Used for local game */,
1121 bool simple_singleplayer_mode)
1123 GUIFormSpecMenu* current_formspec = 0;
1124 video::IVideoDriver* driver = device->getVideoDriver();
1125 scene::ISceneManager* smgr = device->getSceneManager();
1127 // Calculate text height using the font
1128 u32 text_height = font->getDimension(L"Random test string").Height;
1131 Draw "Loading" screen
1135 wchar_t* text = wgettext("Loading...");
1136 draw_load_screen(text, device, guienv, font, 0, 0);
1140 // Create texture source
1141 IWritableTextureSource *tsrc = createTextureSource(device);
1143 // Create shader source
1144 IWritableShaderSource *shsrc = createShaderSource(device);
1146 // These will be filled by data received from the server
1147 // Create item definition manager
1148 IWritableItemDefManager *itemdef = createItemDefManager();
1149 // Create node definition manager
1150 IWritableNodeDefManager *nodedef = createNodeDefManager();
1152 // Sound fetcher (useful when testing)
1153 GameOnDemandSoundFetcher soundfetcher;
1156 ISoundManager *sound = NULL;
1157 bool sound_is_dummy = false;
1159 if(g_settings->getBool("enable_sound")){
1160 infostream<<"Attempting to use OpenAL audio"<<std::endl;
1161 sound = createOpenALSoundManager(&soundfetcher);
1163 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
1165 infostream<<"Sound disabled."<<std::endl;
1169 infostream<<"Using dummy audio."<<std::endl;
1170 sound = &dummySoundManager;
1171 sound_is_dummy = true;
1174 Server *server = NULL;
1178 EventManager eventmgr;
1181 SoundMaker soundmaker(sound, nodedef);
1182 soundmaker.registerReceiver(&eventmgr);
1184 // Create UI for modifying quicktune values
1185 QuicktuneShortcutter quicktune;
1192 wchar_t* text = wgettext("Creating server....");
1193 draw_load_screen(text, device, guienv, font, 0, 25);
1195 infostream<<"Creating server"<<std::endl;
1197 std::string bind_str = g_settings->get("bind_address");
1198 Address bind_addr(0,0,0,0, port);
1200 if (g_settings->getBool("ipv6_server")) {
1201 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1204 bind_addr.Resolve(bind_str.c_str());
1206 } catch (ResolveError &e) {
1207 infostream << "Resolving bind address \"" << bind_str
1208 << "\" failed: " << e.what()
1209 << " -- Listening on all addresses." << std::endl;
1212 if(bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1213 error_message = L"Unable to listen on " +
1214 narrow_to_wide(bind_addr.serializeString()) +
1215 L" because IPv6 is disabled";
1216 errorstream<<wide_to_narrow(error_message)<<std::endl;
1217 // Break out of client scope
1221 server = new Server(map_dir, gamespec,
1222 simple_singleplayer_mode,
1223 bind_addr.isIPv6());
1225 server->start(bind_addr);
1228 do{ // Client scope (breakable do-while(0))
1235 wchar_t* text = wgettext("Creating client...");
1236 draw_load_screen(text, device, guienv, font, 0, 50);
1239 infostream<<"Creating client"<<std::endl;
1241 MapDrawControl draw_control;
1244 wchar_t* text = wgettext("Resolving address...");
1245 draw_load_screen(text, device, guienv, font, 0, 75);
1248 Address connect_address(0,0,0,0, port);
1250 connect_address.Resolve(address.c_str());
1251 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1252 //connect_address.Resolve("localhost");
1253 if (connect_address.isIPv6()) {
1254 IPv6AddressBytes addr_bytes;
1255 addr_bytes.bytes[15] = 1;
1256 connect_address.setAddress(&addr_bytes);
1258 connect_address.setAddress(127,0,0,1);
1262 catch(ResolveError &e) {
1263 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1264 errorstream<<wide_to_narrow(error_message)<<std::endl;
1265 // Break out of client scope
1268 if(connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1269 error_message = L"Unable to connect to " +
1270 narrow_to_wide(connect_address.serializeString()) +
1271 L" because IPv6 is disabled";
1272 errorstream<<wide_to_narrow(error_message)<<std::endl;
1273 // Break out of client scope
1280 Client client(device, playername.c_str(), password, draw_control,
1281 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1282 connect_address.isIPv6());
1284 // Client acts as our GameDef
1285 IGameDef *gamedef = &client;
1288 Attempt to connect to the server
1291 infostream<<"Connecting to server at ";
1292 connect_address.print(&infostream);
1293 infostream<<std::endl;
1294 client.connect(connect_address);
1297 Wait for server to accept connection
1299 bool could_connect = false;
1300 bool connect_aborted = false;
1302 float time_counter = 0.0;
1304 float fps_max = g_settings->getFloat("fps_max");
1305 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1306 u32 lasttime = device->getTimer()->getTime();
1307 while(device->run())
1309 f32 dtime = 0.033; // in seconds
1310 if (cloud_menu_background) {
1311 u32 time = device->getTimer()->getTime();
1313 dtime = (time - lasttime) / 1000.0;
1318 // Update client and server
1321 server->step(dtime);
1324 if(client.getState() == LC_Init) {
1325 could_connect = true;
1329 if(client.accessDenied()) {
1330 error_message = L"Access denied. Reason: "
1331 +client.accessDeniedReason();
1332 errorstream<<wide_to_narrow(error_message)<<std::endl;
1335 if(input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
1336 connect_aborted = true;
1337 infostream<<"Connect aborted [Escape]"<<std::endl;
1343 wchar_t* text = wgettext("Connecting to server...");
1344 draw_load_screen(text, device, guienv, font, dtime, 100);
1348 // On some computers framerate doesn't seem to be
1349 // automatically limited
1350 if (cloud_menu_background) {
1351 // Time of frame without fps limit
1354 // not using getRealTime is necessary for wine
1355 u32 time = device->getTimer()->getTime();
1357 busytime_u32 = time - lasttime;
1360 busytime = busytime_u32 / 1000.0;
1363 u32 frametime_min = 1000./fps_max;
1365 if(busytime_u32 < frametime_min) {
1366 u32 sleeptime = frametime_min - busytime_u32;
1367 device->sleep(sleeptime);
1372 time_counter += dtime;
1375 catch(con::PeerNotFoundException &e)
1379 Handle failure to connect
1381 if(!could_connect) {
1382 if(error_message == L"" && !connect_aborted) {
1383 error_message = L"Connection failed";
1384 errorstream<<wide_to_narrow(error_message)<<std::endl;
1386 // Break out of client scope
1391 Wait until content has been received
1393 bool got_content = false;
1394 bool content_aborted = false;
1396 float time_counter = 0.0;
1398 float fps_max = g_settings->getFloat("fps_max");
1399 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1400 u32 lasttime = device->getTimer()->getTime();
1401 while (device->run()) {
1402 f32 dtime = 0.033; // in seconds
1403 if (cloud_menu_background) {
1404 u32 time = device->getTimer()->getTime();
1406 dtime = (time - lasttime) / 1000.0;
1411 // Update client and server
1414 server->step(dtime);
1417 if (client.mediaReceived() &&
1418 client.itemdefReceived() &&
1419 client.nodedefReceived()) {
1424 if (client.accessDenied()) {
1425 error_message = L"Access denied. Reason: "
1426 +client.accessDeniedReason();
1427 errorstream<<wide_to_narrow(error_message)<<std::endl;
1430 if (client.getState() < LC_Init) {
1431 error_message = L"Client disconnected";
1432 errorstream<<wide_to_narrow(error_message)<<std::endl;
1435 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
1436 content_aborted = true;
1437 infostream<<"Connect aborted [Escape]"<<std::endl;
1443 if (!client.itemdefReceived())
1445 wchar_t* text = wgettext("Item definitions...");
1447 draw_load_screen(text, device, guienv, font, dtime, progress);
1450 else if (!client.nodedefReceived())
1452 wchar_t* text = wgettext("Node definitions...");
1454 draw_load_screen(text, device, guienv, font, dtime, progress);
1460 std::stringstream message;
1461 message.precision(3);
1462 message << gettext("Media...");
1464 if ( ( USE_CURL == 0) ||
1465 (!g_settings->getBool("enable_remote_media_server"))) {
1466 float cur = client.getCurRate();
1467 std::string cur_unit = gettext(" KB/s");
1471 cur_unit = gettext(" MB/s");
1473 message << " ( " << cur << cur_unit << " )";
1475 progress = 50+client.mediaReceiveProgress()*50+0.5;
1476 draw_load_screen(narrow_to_wide(message.str().c_str()), device,
1477 guienv, font, dtime, progress);
1480 // On some computers framerate doesn't seem to be
1481 // automatically limited
1482 if (cloud_menu_background) {
1483 // Time of frame without fps limit
1486 // not using getRealTime is necessary for wine
1487 u32 time = device->getTimer()->getTime();
1489 busytime_u32 = time - lasttime;
1492 busytime = busytime_u32 / 1000.0;
1495 u32 frametime_min = 1000./fps_max;
1497 if(busytime_u32 < frametime_min) {
1498 u32 sleeptime = frametime_min - busytime_u32;
1499 device->sleep(sleeptime);
1504 time_counter += dtime;
1509 if(error_message == L"" && !content_aborted){
1510 error_message = L"Something failed";
1511 errorstream<<wide_to_narrow(error_message)<<std::endl;
1513 // Break out of client scope
1518 After all content has been received:
1519 Update cached textures, meshes and materials
1521 client.afterContentReceived(device,font);
1524 Create the camera node
1526 Camera camera(smgr, draw_control, gamedef);
1527 if (!camera.successfullyCreated(error_message))
1530 f32 camera_yaw = 0; // "right/left"
1531 f32 camera_pitch = 0; // "up/down"
1537 Clouds *clouds = NULL;
1538 if(g_settings->getBool("enable_clouds"))
1540 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1548 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1550 scene::ISceneNode* skybox = NULL;
1553 A copy of the local inventory
1555 Inventory local_inventory(itemdef);
1558 Find out size of crack animation
1560 int crack_animation_length = 5;
1562 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1563 v2u32 size = t->getOriginalSize();
1564 crack_animation_length = size.Y / size.X;
1571 // First line of debug text
1572 gui::IGUIStaticText *guitext = guienv->addStaticText(
1574 core::rect<s32>(0, 0, 0, 0),
1575 false, false, guiroot);
1576 // Second line of debug text
1577 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1579 core::rect<s32>(0, 0, 0, 0),
1580 false, false, guiroot);
1581 // At the middle of the screen
1582 // Object infos are shown in this
1583 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1585 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1586 false, true, guiroot);
1588 // Status text (displays info when showing and hiding GUI stuff, etc.)
1589 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1591 core::rect<s32>(0,0,0,0),
1592 false, false, guiroot);
1593 guitext_status->setVisible(false);
1595 std::wstring statustext;
1596 float statustext_time = 0;
1599 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1601 core::rect<s32>(0,0,0,0),
1602 //false, false); // Disable word wrap as of now
1603 false, true, guiroot);
1604 // Remove stale "recent" chat messages from previous connections
1605 chat_backend.clearRecentChat();
1606 // Chat backend and console
1607 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1609 // Profiler text (size is updated when text is updated)
1610 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1612 core::rect<s32>(0,0,0,0),
1613 false, false, guiroot);
1614 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1615 guitext_profiler->setVisible(false);
1616 guitext_profiler->setWordWrap(true);
1618 #ifdef HAVE_TOUCHSCREENGUI
1619 if (g_touchscreengui)
1620 g_touchscreengui->init(tsrc,porting::getDisplayDensity());
1624 Some statistics are collected in these
1627 u32 beginscenetime = 0;
1628 u32 endscenetime = 0;
1630 float recent_turn_speed = 0.0;
1632 ProfilerGraph graph;
1633 // Initially clear the profiler
1634 Profiler::GraphValues dummyvalues;
1635 g_profiler->graphGet(dummyvalues);
1637 float nodig_delay_timer = 0.0;
1638 float dig_time = 0.0;
1640 PointedThing pointed_old;
1641 bool digging = false;
1642 bool ldown_for_dig = false;
1644 float damage_flash = 0;
1646 float jump_timer = 0;
1647 bool reset_jump_timer = false;
1649 const float object_hit_delay = 0.2;
1650 float object_hit_delay_timer = 0.0;
1651 float time_from_last_punch = 10;
1653 float update_draw_list_timer = 0.0;
1654 v3f update_draw_list_last_cam_dir;
1656 bool invert_mouse = g_settings->getBool("invert_mouse");
1658 bool update_wielded_item_trigger = true;
1660 bool show_hud = true;
1661 bool show_chat = true;
1662 bool force_fog_off = false;
1663 f32 fog_range = 100*BS;
1664 bool disable_camera_update = false;
1665 bool show_debug = g_settings->getBool("show_debug");
1666 bool show_profiler_graph = false;
1667 u32 show_profiler = 0;
1668 u32 show_profiler_max = 3; // Number of pages
1670 float time_of_day = 0;
1671 float time_of_day_smooth = 0;
1673 float repeat_rightclick_timer = 0;
1678 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1679 sky, &force_fog_off, &fog_range, &client));
1685 bool first_loop_after_window_activation = true;
1687 // TODO: Convert the static interval timers to these
1688 // Interval limiter for profiler
1689 IntervalLimiter m_profiler_interval;
1691 // Time is in milliseconds
1692 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1693 // NOTE: So we have to use getTime() and call run()s between them
1694 u32 lasttime = device->getTimer()->getTime();
1696 LocalPlayer* player = client.getEnv().getLocalPlayer();
1697 player->hurt_tilt_timer = 0;
1698 player->hurt_tilt_strength = 0;
1703 Hud hud(driver, smgr, guienv, font, text_height,
1704 gamedef, player, &local_inventory);
1706 core::stringw str = L"Minetest [";
1707 str += driver->getName();
1709 device->setWindowCaption(str.c_str());
1712 std::wstring infotext;
1716 if(device->run() == false || kill == true ||
1717 g_gamecallback->shutdown_requested)
1720 v2u32 screensize = driver->getScreenSize();
1722 // Time of frame without fps limit
1726 // not using getRealTime is necessary for wine
1727 u32 time = device->getTimer()->getTime();
1729 busytime_u32 = time - lasttime;
1732 busytime = busytime_u32 / 1000.0;
1735 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1737 // Necessary for device->getTimer()->getTime()
1745 float fps_max = g_menumgr.pausesGame() ?
1746 g_settings->getFloat("pause_fps_max") :
1747 g_settings->getFloat("fps_max");
1748 u32 frametime_min = 1000./fps_max;
1750 if(busytime_u32 < frametime_min)
1752 u32 sleeptime = frametime_min - busytime_u32;
1753 device->sleep(sleeptime);
1754 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1758 // Necessary for device->getTimer()->getTime()
1762 Time difference calculation
1764 f32 dtime; // in seconds
1766 u32 time = device->getTimer()->getTime();
1768 dtime = (time - lasttime) / 1000.0;
1773 g_profiler->graphAdd("mainloop_dtime", dtime);
1777 if(nodig_delay_timer >= 0)
1778 nodig_delay_timer -= dtime;
1779 if(object_hit_delay_timer >= 0)
1780 object_hit_delay_timer -= dtime;
1781 time_from_last_punch += dtime;
1783 g_profiler->add("Elapsed time", dtime);
1784 g_profiler->avg("FPS", 1./dtime);
1787 Time average and jitter calculation
1790 static f32 dtime_avg1 = 0.0;
1791 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1792 f32 dtime_jitter1 = dtime - dtime_avg1;
1794 static f32 dtime_jitter1_max_sample = 0.0;
1795 static f32 dtime_jitter1_max_fraction = 0.0;
1797 static f32 jitter1_max = 0.0;
1798 static f32 counter = 0.0;
1799 if(dtime_jitter1 > jitter1_max)
1800 jitter1_max = dtime_jitter1;
1805 dtime_jitter1_max_sample = jitter1_max;
1806 dtime_jitter1_max_fraction
1807 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1813 Busytime average and jitter calculation
1816 static f32 busytime_avg1 = 0.0;
1817 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1818 f32 busytime_jitter1 = busytime - busytime_avg1;
1820 static f32 busytime_jitter1_max_sample = 0.0;
1821 static f32 busytime_jitter1_min_sample = 0.0;
1823 static f32 jitter1_max = 0.0;
1824 static f32 jitter1_min = 0.0;
1825 static f32 counter = 0.0;
1826 if(busytime_jitter1 > jitter1_max)
1827 jitter1_max = busytime_jitter1;
1828 if(busytime_jitter1 < jitter1_min)
1829 jitter1_min = busytime_jitter1;
1833 busytime_jitter1_max_sample = jitter1_max;
1834 busytime_jitter1_min_sample = jitter1_min;
1841 Handle miscellaneous stuff
1844 if(client.accessDenied())
1846 error_message = L"Access denied. Reason: "
1847 +client.accessDeniedReason();
1848 errorstream<<wide_to_narrow(error_message)<<std::endl;
1852 if(g_gamecallback->disconnect_requested)
1854 g_gamecallback->disconnect_requested = false;
1858 if(g_gamecallback->changepassword_requested)
1860 (new GUIPasswordChange(guienv, guiroot, -1,
1861 &g_menumgr, &client))->drop();
1862 g_gamecallback->changepassword_requested = false;
1865 if(g_gamecallback->changevolume_requested)
1867 (new GUIVolumeChange(guienv, guiroot, -1,
1868 &g_menumgr, &client))->drop();
1869 g_gamecallback->changevolume_requested = false;
1872 /* Process TextureSource's queue */
1873 tsrc->processQueue();
1875 /* Process ItemDefManager's queue */
1876 itemdef->processQueue(gamedef);
1879 Process ShaderSource's queue
1881 shsrc->processQueue();
1888 // Hilight boxes collected during the loop and displayed
1889 std::vector<aabb3f> hilightboxes;
1891 /* reset infotext */
1896 float profiler_print_interval =
1897 g_settings->getFloat("profiler_print_interval");
1898 bool print_to_log = true;
1899 if(profiler_print_interval == 0){
1900 print_to_log = false;
1901 profiler_print_interval = 5;
1903 if(m_profiler_interval.step(dtime, profiler_print_interval))
1906 infostream<<"Profiler:"<<std::endl;
1907 g_profiler->print(infostream);
1910 update_profiler_gui(guitext_profiler, font, text_height,
1911 show_profiler, show_profiler_max);
1913 g_profiler->clear();
1917 Direct handling of user input
1920 // Reset input if window not active or some menu is active
1921 if(device->isWindowActive() == false
1922 || noMenuActive() == false
1923 || guienv->hasFocus(gui_chat_console))
1927 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1929 gui_chat_console->closeConsoleAtOnce();
1932 // Input handler step() (used by the random input generator)
1934 #ifdef HAVE_TOUCHSCREENGUI
1935 if (g_touchscreengui) {
1936 g_touchscreengui->step(dtime);
1940 if (current_formspec != 0)
1941 current_formspec->getAndroidUIInput();
1944 // Increase timer for doubleclick of "jump"
1945 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1946 jump_timer += dtime;
1949 Launch menus and trigger stuff according to keys
1951 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1953 // drop selected item
1954 IDropAction *a = new IDropAction();
1956 a->from_inv.setCurrentPlayer();
1957 a->from_list = "main";
1958 a->from_i = client.getPlayerItem();
1959 client.inventoryAction(a);
1961 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1963 infostream<<"the_game: "
1964 <<"Launching inventory"<<std::endl;
1966 PlayerInventoryFormSource* fs_src = new PlayerInventoryFormSource(&client);
1967 TextDest* txt_dst = new TextDestPlayerInventory(&client);
1969 create_formspec_menu(¤t_formspec, &client, gamedef, tsrc, device, fs_src, txt_dst, &client);
1971 InventoryLocation inventoryloc;
1972 inventoryloc.setCurrentPlayer();
1973 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
1975 else if(input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey))
1977 show_pause_menu(¤t_formspec, &client, gamedef, tsrc, device,
1978 simple_singleplayer_mode);
1980 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1982 show_chat_menu(¤t_formspec, &client, gamedef, tsrc, device,
1985 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1987 show_chat_menu(¤t_formspec, &client, gamedef, tsrc, device,
1990 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1992 if (!gui_chat_console->isOpenInhibited())
1994 // Open up to over half of the screen
1995 gui_chat_console->openConsole(0.6);
1996 guienv->setFocus(gui_chat_console);
1999 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
2001 if(g_settings->getBool("free_move"))
2003 g_settings->set("free_move","false");
2004 statustext = L"free_move disabled";
2005 statustext_time = 0;
2009 g_settings->set("free_move","true");
2010 statustext = L"free_move enabled";
2011 statustext_time = 0;
2012 if(!client.checkPrivilege("fly"))
2013 statustext += L" (note: no 'fly' privilege)";
2016 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
2018 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
2020 if(g_settings->getBool("free_move"))
2022 g_settings->set("free_move","false");
2023 statustext = L"free_move disabled";
2024 statustext_time = 0;
2028 g_settings->set("free_move","true");
2029 statustext = L"free_move enabled";
2030 statustext_time = 0;
2031 if(!client.checkPrivilege("fly"))
2032 statustext += L" (note: no 'fly' privilege)";
2035 reset_jump_timer = true;
2037 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
2039 if(g_settings->getBool("fast_move"))
2041 g_settings->set("fast_move","false");
2042 statustext = L"fast_move disabled";
2043 statustext_time = 0;
2047 g_settings->set("fast_move","true");
2048 statustext = L"fast_move enabled";
2049 statustext_time = 0;
2050 if(!client.checkPrivilege("fast"))
2051 statustext += L" (note: no 'fast' privilege)";
2054 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
2056 if(g_settings->getBool("noclip"))
2058 g_settings->set("noclip","false");
2059 statustext = L"noclip disabled";
2060 statustext_time = 0;
2064 g_settings->set("noclip","true");
2065 statustext = L"noclip enabled";
2066 statustext_time = 0;
2067 if(!client.checkPrivilege("noclip"))
2068 statustext += L" (note: no 'noclip' privilege)";
2071 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
2073 client.makeScreenshot(device);
2075 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
2077 show_hud = !show_hud;
2079 statustext = L"HUD shown";
2080 client.setHighlighted(client.getHighlighted(), true);
2082 statustext = L"HUD hidden";
2083 client.setHighlighted(client.getHighlighted(), false);
2085 statustext_time = 0;
2087 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
2089 show_chat = !show_chat;
2091 statustext = L"Chat shown";
2093 statustext = L"Chat hidden";
2094 statustext_time = 0;
2096 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
2098 force_fog_off = !force_fog_off;
2100 statustext = L"Fog disabled";
2102 statustext = L"Fog enabled";
2103 statustext_time = 0;
2105 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
2107 disable_camera_update = !disable_camera_update;
2108 if(disable_camera_update)
2109 statustext = L"Camera update disabled";
2111 statustext = L"Camera update enabled";
2112 statustext_time = 0;
2114 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
2116 // Initial / 3x toggle: Chat only
2117 // 1x toggle: Debug text with chat
2118 // 2x toggle: Debug text with profiler graph
2122 show_profiler_graph = false;
2123 statustext = L"Debug info shown";
2124 statustext_time = 0;
2126 else if(show_profiler_graph)
2129 show_profiler_graph = false;
2130 statustext = L"Debug info and profiler graph hidden";
2131 statustext_time = 0;
2135 show_profiler_graph = true;
2136 statustext = L"Profiler graph shown";
2137 statustext_time = 0;
2140 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
2142 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
2144 // FIXME: This updates the profiler with incomplete values
2145 update_profiler_gui(guitext_profiler, font, text_height,
2146 show_profiler, show_profiler_max);
2148 if(show_profiler != 0)
2150 std::wstringstream sstr;
2151 sstr<<"Profiler shown (page "<<show_profiler
2152 <<" of "<<show_profiler_max<<")";
2153 statustext = sstr.str();
2154 statustext_time = 0;
2158 statustext = L"Profiler hidden";
2159 statustext_time = 0;
2162 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
2164 s16 range = g_settings->getS16("viewing_range_nodes_min");
2165 s16 range_new = range + 10;
2166 g_settings->set("viewing_range_nodes_min", itos(range_new));
2167 statustext = narrow_to_wide(
2168 "Minimum viewing range changed to "
2170 statustext_time = 0;
2172 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
2174 s16 range = g_settings->getS16("viewing_range_nodes_min");
2175 s16 range_new = range - 10;
2178 g_settings->set("viewing_range_nodes_min",
2180 statustext = narrow_to_wide(
2181 "Minimum viewing range changed to "
2183 statustext_time = 0;
2187 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
2189 reset_jump_timer = false;
2193 // Handle QuicktuneShortcutter
2194 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2196 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2198 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2200 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2203 std::string msg = quicktune.getMessage();
2205 statustext = narrow_to_wide(msg);
2206 statustext_time = 0;
2210 // Item selection with mouse wheel
2211 u16 new_playeritem = client.getPlayerItem();
2213 s32 wheel = input->getMouseWheel();
2214 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2215 player->hud_hotbar_itemcount-1);
2219 if(new_playeritem < max_item)
2226 if(new_playeritem > 0)
2229 new_playeritem = max_item;
2234 for(u16 i=0; i<10; i++)
2236 const KeyPress *kp = NumberKey + (i + 1) % 10;
2237 if(input->wasKeyDown(*kp))
2239 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2243 infostream<<"Selected item: "
2244 <<new_playeritem<<std::endl;
2249 // Viewing range selection
2250 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2252 draw_control.range_all = !draw_control.range_all;
2253 if(draw_control.range_all)
2255 infostream<<"Enabled full viewing range"<<std::endl;
2256 statustext = L"Enabled full viewing range";
2257 statustext_time = 0;
2261 infostream<<"Disabled full viewing range"<<std::endl;
2262 statustext = L"Disabled full viewing range";
2263 statustext_time = 0;
2267 // Print debug stacks
2268 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2270 dstream<<"-----------------------------------------"
2272 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2273 dstream<<"-----------------------------------------"
2275 debug_stacks_print();
2279 Mouse and camera control
2280 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2283 float turn_amount = 0;
2284 if((device->isWindowActive() && noMenuActive()) || random_input)
2289 // Mac OSX gets upset if this is set every frame
2290 if(device->getCursorControl()->isVisible())
2291 device->getCursorControl()->setVisible(false);
2295 if(first_loop_after_window_activation){
2296 //infostream<<"window active, first loop"<<std::endl;
2297 first_loop_after_window_activation = false;
2299 #ifdef HAVE_TOUCHSCREENGUI
2300 if (g_touchscreengui) {
2301 camera_yaw = g_touchscreengui->getYaw();
2302 camera_pitch = g_touchscreengui->getPitch();
2305 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width/2);
2306 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height/2);
2308 || (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)) {
2311 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2313 /*const float keyspeed = 500;
2314 if(input->isKeyDown(irr::KEY_UP))
2315 dy -= dtime * keyspeed;
2316 if(input->isKeyDown(irr::KEY_DOWN))
2317 dy += dtime * keyspeed;
2318 if(input->isKeyDown(irr::KEY_LEFT))
2319 dx -= dtime * keyspeed;
2320 if(input->isKeyDown(irr::KEY_RIGHT))
2321 dx += dtime * keyspeed;*/
2323 float d = g_settings->getFloat("mouse_sensitivity");
2324 d = rangelim(d, 0.01, 100.0);
2326 camera_pitch += dy*d;
2327 turn_amount = v2f(dx, dy).getLength() * d;
2329 #ifdef HAVE_TOUCHSCREENGUI
2332 if(camera_pitch < -89.5) camera_pitch = -89.5;
2333 if(camera_pitch > 89.5) camera_pitch = 89.5;
2335 input->setMousePos((driver->getScreenSize().Width/2),
2336 (driver->getScreenSize().Height/2));
2340 // Mac OSX gets upset if this is set every frame
2341 if(device->getCursorControl()->isVisible() == false)
2342 device->getCursorControl()->setVisible(true);
2345 //infostream<<"window inactive"<<std::endl;
2346 first_loop_after_window_activation = true;
2348 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2349 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2352 Player speed control
2366 PlayerControl control(
2367 input->isKeyDown(getKeySetting("keymap_forward")),
2368 input->isKeyDown(getKeySetting("keymap_backward")),
2369 input->isKeyDown(getKeySetting("keymap_left")),
2370 input->isKeyDown(getKeySetting("keymap_right")),
2371 input->isKeyDown(getKeySetting("keymap_jump")),
2372 input->isKeyDown(getKeySetting("keymap_special1")),
2373 input->isKeyDown(getKeySetting("keymap_sneak")),
2374 input->getLeftState(),
2375 input->getRightState(),
2379 client.setPlayerControl(control);
2380 LocalPlayer* player = client.getEnv().getLocalPlayer();
2382 (((int)input->isKeyDown(getKeySetting("keymap_forward")) & 0x1) << 0) |
2383 (((int)input->isKeyDown(getKeySetting("keymap_backward")) & 0x1) << 1) |
2384 (((int)input->isKeyDown(getKeySetting("keymap_left")) & 0x1) << 2) |
2385 (((int)input->isKeyDown(getKeySetting("keymap_right")) & 0x1) << 3) |
2386 (((int)input->isKeyDown(getKeySetting("keymap_jump")) & 0x1) << 4) |
2387 (((int)input->isKeyDown(getKeySetting("keymap_special1")) & 0x1) << 5) |
2388 (((int)input->isKeyDown(getKeySetting("keymap_sneak")) & 0x1) << 6) |
2389 (((int)input->getLeftState() & 0x1) << 7) |
2390 (((int)input->getRightState() & 0x1) << 8);
2394 Run server, client (and process environments)
2396 bool can_be_and_is_paused =
2397 (simple_singleplayer_mode && g_menumgr.pausesGame());
2398 if(can_be_and_is_paused)
2407 //TimeTaker timer("server->step(dtime)");
2408 server->step(dtime);
2411 //TimeTaker timer("client.step(dtime)");
2417 // Read client events
2419 ClientEvent event = client.getClientEvent();
2420 if(event.type == CE_NONE) {
2423 else if(event.type == CE_PLAYER_DAMAGE &&
2424 client.getHP() != 0) {
2425 //u16 damage = event.player_damage.amount;
2426 //infostream<<"Player damage: "<<damage<<std::endl;
2428 damage_flash += 100.0;
2429 damage_flash += 8.0 * event.player_damage.amount;
2431 player->hurt_tilt_timer = 1.5;
2432 player->hurt_tilt_strength = event.player_damage.amount/4;
2433 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
2435 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2436 gamedef->event()->put(e);
2438 else if(event.type == CE_PLAYER_FORCE_MOVE) {
2439 camera_yaw = event.player_force_move.yaw;
2440 camera_pitch = event.player_force_move.pitch;
2442 else if(event.type == CE_DEATHSCREEN) {
2443 show_deathscreen(¤t_formspec, &client, gamedef, tsrc,
2446 chat_backend.addMessage(L"", L"You died.");
2448 /* Handle visualization */
2451 LocalPlayer* player = client.getEnv().getLocalPlayer();
2452 player->hurt_tilt_timer = 0;
2453 player->hurt_tilt_strength = 0;
2456 else if (event.type == CE_SHOW_FORMSPEC) {
2457 FormspecFormSource* fs_src =
2458 new FormspecFormSource(*(event.show_formspec.formspec));
2459 TextDestPlayerInventory* txt_dst =
2460 new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2462 create_formspec_menu(¤t_formspec, &client, gamedef,
2463 tsrc, device, fs_src, txt_dst, &client);
2465 delete(event.show_formspec.formspec);
2466 delete(event.show_formspec.formname);
2468 else if(event.type == CE_SPAWN_PARTICLE) {
2469 LocalPlayer* player = client.getEnv().getLocalPlayer();
2470 video::ITexture *texture =
2471 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2473 new Particle(gamedef, smgr, player, client.getEnv(),
2474 *event.spawn_particle.pos,
2475 *event.spawn_particle.vel,
2476 *event.spawn_particle.acc,
2477 event.spawn_particle.expirationtime,
2478 event.spawn_particle.size,
2479 event.spawn_particle.collisiondetection,
2480 event.spawn_particle.vertical,
2485 else if(event.type == CE_ADD_PARTICLESPAWNER) {
2486 LocalPlayer* player = client.getEnv().getLocalPlayer();
2487 video::ITexture *texture =
2488 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2490 new ParticleSpawner(gamedef, smgr, player,
2491 event.add_particlespawner.amount,
2492 event.add_particlespawner.spawntime,
2493 *event.add_particlespawner.minpos,
2494 *event.add_particlespawner.maxpos,
2495 *event.add_particlespawner.minvel,
2496 *event.add_particlespawner.maxvel,
2497 *event.add_particlespawner.minacc,
2498 *event.add_particlespawner.maxacc,
2499 event.add_particlespawner.minexptime,
2500 event.add_particlespawner.maxexptime,
2501 event.add_particlespawner.minsize,
2502 event.add_particlespawner.maxsize,
2503 event.add_particlespawner.collisiondetection,
2504 event.add_particlespawner.vertical,
2506 event.add_particlespawner.id);
2508 else if(event.type == CE_DELETE_PARTICLESPAWNER) {
2509 delete_particlespawner (event.delete_particlespawner.id);
2511 else if (event.type == CE_HUDADD) {
2512 u32 id = event.hudadd.id;
2514 HudElement *e = player->getHud(id);
2517 delete event.hudadd.pos;
2518 delete event.hudadd.name;
2519 delete event.hudadd.scale;
2520 delete event.hudadd.text;
2521 delete event.hudadd.align;
2522 delete event.hudadd.offset;
2523 delete event.hudadd.world_pos;
2524 delete event.hudadd.size;
2529 e->type = (HudElementType)event.hudadd.type;
2530 e->pos = *event.hudadd.pos;
2531 e->name = *event.hudadd.name;
2532 e->scale = *event.hudadd.scale;
2533 e->text = *event.hudadd.text;
2534 e->number = event.hudadd.number;
2535 e->item = event.hudadd.item;
2536 e->dir = event.hudadd.dir;
2537 e->align = *event.hudadd.align;
2538 e->offset = *event.hudadd.offset;
2539 e->world_pos = *event.hudadd.world_pos;
2540 e->size = *event.hudadd.size;
2542 u32 new_id = player->addHud(e);
2543 //if this isn't true our huds aren't consistent
2544 assert(new_id == id);
2546 delete event.hudadd.pos;
2547 delete event.hudadd.name;
2548 delete event.hudadd.scale;
2549 delete event.hudadd.text;
2550 delete event.hudadd.align;
2551 delete event.hudadd.offset;
2552 delete event.hudadd.world_pos;
2553 delete event.hudadd.size;
2555 else if (event.type == CE_HUDRM) {
2556 HudElement* e = player->removeHud(event.hudrm.id);
2561 else if (event.type == CE_HUDCHANGE) {
2562 u32 id = event.hudchange.id;
2563 HudElement* e = player->getHud(id);
2566 delete event.hudchange.v3fdata;
2567 delete event.hudchange.v2fdata;
2568 delete event.hudchange.sdata;
2569 delete event.hudchange.v2s32data;
2573 switch (event.hudchange.stat) {
2575 e->pos = *event.hudchange.v2fdata;
2578 e->name = *event.hudchange.sdata;
2580 case HUD_STAT_SCALE:
2581 e->scale = *event.hudchange.v2fdata;
2584 e->text = *event.hudchange.sdata;
2586 case HUD_STAT_NUMBER:
2587 e->number = event.hudchange.data;
2590 e->item = event.hudchange.data;
2593 e->dir = event.hudchange.data;
2595 case HUD_STAT_ALIGN:
2596 e->align = *event.hudchange.v2fdata;
2598 case HUD_STAT_OFFSET:
2599 e->offset = *event.hudchange.v2fdata;
2601 case HUD_STAT_WORLD_POS:
2602 e->world_pos = *event.hudchange.v3fdata;
2605 e->size = *event.hudchange.v2s32data;
2609 delete event.hudchange.v3fdata;
2610 delete event.hudchange.v2fdata;
2611 delete event.hudchange.sdata;
2612 delete event.hudchange.v2s32data;
2614 else if (event.type == CE_SET_SKY) {
2615 sky->setVisible(false);
2620 // Handle according to type
2621 if(*event.set_sky.type == "regular") {
2622 sky->setVisible(true);
2624 else if(*event.set_sky.type == "skybox" &&
2625 event.set_sky.params->size() == 6) {
2626 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2627 skybox = smgr->addSkyBoxSceneNode(
2628 tsrc->getTexture((*event.set_sky.params)[0]),
2629 tsrc->getTexture((*event.set_sky.params)[1]),
2630 tsrc->getTexture((*event.set_sky.params)[2]),
2631 tsrc->getTexture((*event.set_sky.params)[3]),
2632 tsrc->getTexture((*event.set_sky.params)[4]),
2633 tsrc->getTexture((*event.set_sky.params)[5]));
2635 // Handle everything else as plain color
2637 if(*event.set_sky.type != "plain")
2638 infostream<<"Unknown sky type: "
2639 <<(*event.set_sky.type)<<std::endl;
2640 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2643 delete event.set_sky.bgcolor;
2644 delete event.set_sky.type;
2645 delete event.set_sky.params;
2647 else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
2648 bool enable = event.override_day_night_ratio.do_override;
2649 u32 value = event.override_day_night_ratio.ratio_f * 1000;
2650 client.getEnv().setDayNightRatioOverride(enable, value);
2655 //TimeTaker //timer2("//timer2");
2658 For interaction purposes, get info about the held item
2660 - Is it a usable item?
2661 - Can it point to liquids?
2663 ItemStack playeritem;
2665 InventoryList *mlist = local_inventory.getList("main");
2666 if((mlist != NULL) && (client.getPlayerItem() < mlist->getSize()))
2667 playeritem = mlist->getItem(client.getPlayerItem());
2669 const ItemDefinition &playeritem_def =
2670 playeritem.getDefinition(itemdef);
2671 ToolCapabilities playeritem_toolcap =
2672 playeritem.getToolCapabilities(itemdef);
2678 v3s16 old_camera_offset = camera.getOffset();
2680 LocalPlayer* player = client.getEnv().getLocalPlayer();
2681 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2682 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2684 if(input->wasKeyDown(getKeySetting("keymap_camera_mode"))) {
2685 camera.toggleCameraMode();
2686 GenericCAO* playercao = player->getCAO();
2688 assert( playercao != NULL );
2689 if (camera.getCameraMode() > CAMERA_MODE_FIRST) {
2690 playercao->setVisible(true);
2693 playercao->setVisible(false);
2696 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2697 camera.update(player, dtime, busytime, tool_reload_ratio,
2701 v3f player_position = player->getPosition();
2702 v3f camera_position = camera.getPosition();
2703 v3f camera_direction = camera.getDirection();
2704 f32 camera_fov = camera.getFovMax();
2705 v3s16 camera_offset = camera.getOffset();
2707 bool camera_offset_changed = (camera_offset != old_camera_offset);
2709 if(!disable_camera_update){
2710 client.getEnv().getClientMap().updateCamera(camera_position,
2711 camera_direction, camera_fov, camera_offset);
2712 if (camera_offset_changed){
2713 client.updateCameraOffset(camera_offset);
2714 client.getEnv().updateCameraOffset(camera_offset);
2716 clouds->updateCameraOffset(camera_offset);
2720 // Update sound listener
2721 sound->updateListener(camera.getCameraNode()->getPosition()+intToFloat(camera_offset, BS),
2722 v3f(0,0,0), // velocity
2723 camera.getDirection(),
2724 camera.getCameraNode()->getUpVector());
2725 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2731 soundmaker.step(dtime);
2733 ClientMap &map = client.getEnv().getClientMap();
2734 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2735 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2739 Calculate what block is the crosshair pointing to
2742 //u32 t1 = device->getTimer()->getRealTime();
2744 f32 d = playeritem_def.range; // max. distance
2745 f32 d_hand = itemdef->get("").range;
2746 if(d < 0 && d_hand >= 0)
2750 core::line3d<f32> shootline(camera_position,
2751 camera_position + camera_direction * BS * (d+1));
2754 // prevent player pointing anything in front-view
2755 if (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)
2756 shootline = core::line3d<f32>(0,0,0,0,0,0);
2758 #ifdef HAVE_TOUCHSCREENGUI
2759 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
2760 shootline = g_touchscreengui->getShootline();
2761 shootline.start += intToFloat(camera_offset,BS);
2762 shootline.end += intToFloat(camera_offset,BS);
2766 ClientActiveObject *selected_object = NULL;
2768 PointedThing pointed = getPointedThing(
2770 &client, player_position, camera_direction,
2771 camera_position, shootline, d,
2772 playeritem_def.liquids_pointable, !ldown_for_dig,
2778 if(pointed != pointed_old)
2780 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2781 if (g_settings->getBool("enable_node_highlighting"))
2782 client.setHighlighted(pointed.node_undersurface, show_hud);
2787 - releasing left mouse button
2788 - pointing away from node
2792 if(input->getLeftReleased())
2794 infostream<<"Left button released"
2795 <<" (stopped digging)"<<std::endl;
2798 else if(pointed != pointed_old)
2800 if (pointed.type == POINTEDTHING_NODE
2801 && pointed_old.type == POINTEDTHING_NODE
2802 && pointed.node_undersurface == pointed_old.node_undersurface)
2804 // Still pointing to the same node,
2805 // but a different face. Don't reset.
2809 infostream<<"Pointing away from node"
2810 <<" (stopped digging)"<<std::endl;
2816 client.interact(1, pointed_old);
2817 client.setCrack(-1, v3s16(0,0,0));
2821 if(!digging && ldown_for_dig && !input->getLeftState())
2823 ldown_for_dig = false;
2826 bool left_punch = false;
2827 soundmaker.m_player_leftpunch_sound.name = "";
2829 if(input->getRightState())
2830 repeat_rightclick_timer += dtime;
2832 repeat_rightclick_timer = 0;
2834 if(playeritem_def.usable && input->getLeftState())
2836 if(input->getLeftClicked())
2837 client.interact(4, pointed);
2839 else if(pointed.type == POINTEDTHING_NODE)
2841 v3s16 nodepos = pointed.node_undersurface;
2842 v3s16 neighbourpos = pointed.node_abovesurface;
2845 Check information text of node
2848 ClientMap &map = client.getEnv().getClientMap();
2849 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2851 infotext = narrow_to_wide(meta->getString("infotext"));
2853 MapNode n = map.getNode(nodepos);
2854 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2855 infotext = L"Unknown node: ";
2856 infotext += narrow_to_wide(nodedef->get(n).name);
2864 if(nodig_delay_timer <= 0.0 && input->getLeftState()
2865 && client.checkPrivilege("interact"))
2869 infostream<<"Started digging"<<std::endl;
2870 client.interact(0, pointed);
2872 ldown_for_dig = true;
2874 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2876 // NOTE: Similar piece of code exists on the server side for
2878 // Get digging parameters
2879 DigParams params = getDigParams(nodedef->get(n).groups,
2880 &playeritem_toolcap);
2881 // If can't dig, try hand
2882 if(!params.diggable){
2883 const ItemDefinition &hand = itemdef->get("");
2884 const ToolCapabilities *tp = hand.tool_capabilities;
2886 params = getDigParams(nodedef->get(n).groups, tp);
2889 float dig_time_complete = 0.0;
2891 if(params.diggable == false)
2893 // I guess nobody will wait for this long
2894 dig_time_complete = 10000000.0;
2898 dig_time_complete = params.time;
2899 if (g_settings->getBool("enable_particles"))
2901 const ContentFeatures &features =
2902 client.getNodeDefManager()->get(n);
2903 addPunchingParticles
2904 (gamedef, smgr, player, client.getEnv(),
2905 nodepos, features.tiles);
2909 if(dig_time_complete >= 0.001)
2911 dig_index = (u16)((float)crack_animation_length
2912 * dig_time/dig_time_complete);
2914 // This is for torches
2917 dig_index = crack_animation_length;
2920 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2921 if(sound_dig.exists() && params.diggable){
2922 if(sound_dig.name == "__group"){
2923 if(params.main_group != ""){
2924 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2925 soundmaker.m_player_leftpunch_sound.name =
2926 std::string("default_dig_") +
2930 soundmaker.m_player_leftpunch_sound = sound_dig;
2934 // Don't show cracks if not diggable
2935 if(dig_time_complete >= 100000.0)
2938 else if(dig_index < crack_animation_length)
2940 //TimeTaker timer("client.setTempMod");
2941 //infostream<<"dig_index="<<dig_index<<std::endl;
2942 client.setCrack(dig_index, nodepos);
2946 infostream<<"Digging completed"<<std::endl;
2947 client.interact(2, pointed);
2948 client.setCrack(-1, v3s16(0,0,0));
2949 MapNode wasnode = map.getNode(nodepos);
2950 client.removeNode(nodepos);
2952 if (g_settings->getBool("enable_particles"))
2954 const ContentFeatures &features =
2955 client.getNodeDefManager()->get(wasnode);
2957 (gamedef, smgr, player, client.getEnv(),
2958 nodepos, features.tiles);
2964 nodig_delay_timer = dig_time_complete
2965 / (float)crack_animation_length;
2967 // We don't want a corresponding delay to
2968 // very time consuming nodes
2969 if(nodig_delay_timer > 0.3)
2970 nodig_delay_timer = 0.3;
2971 // We want a slight delay to very little
2972 // time consuming nodes
2973 float mindelay = 0.15;
2974 if(nodig_delay_timer < mindelay)
2975 nodig_delay_timer = mindelay;
2977 // Send event to trigger sound
2978 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2979 gamedef->event()->put(e);
2982 if(dig_time_complete < 100000.0)
2986 client.setCrack(-1, nodepos);
2989 camera.setDigging(0); // left click animation
2992 if((input->getRightClicked() ||
2993 repeat_rightclick_timer >=
2994 g_settings->getFloat("repeat_rightclick_time")) &&
2995 client.checkPrivilege("interact"))
2997 repeat_rightclick_timer = 0;
2998 infostream<<"Ground right-clicked"<<std::endl;
3000 if(meta && meta->getString("formspec") != "" && !random_input
3001 && !input->isKeyDown(getKeySetting("keymap_sneak")))
3003 infostream<<"Launching custom inventory view"<<std::endl;
3005 InventoryLocation inventoryloc;
3006 inventoryloc.setNodeMeta(nodepos);
3008 NodeMetadataFormSource* fs_src = new NodeMetadataFormSource(
3009 &client.getEnv().getClientMap(), nodepos);
3010 TextDest* txt_dst = new TextDestNodeMetadata(nodepos, &client);
3012 create_formspec_menu(¤t_formspec, &client, gamedef,
3013 tsrc, device, fs_src, txt_dst, &client);
3015 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3017 // Otherwise report right click to server
3020 camera.setDigging(1); // right click animation (always shown for feedback)
3022 // If the wielded item has node placement prediction,
3024 bool placed = nodePlacementPrediction(client,
3026 nodepos, neighbourpos);
3030 client.interact(3, pointed);
3032 soundmaker.m_player_rightpunch_sound =
3033 playeritem_def.sound_place;
3035 soundmaker.m_player_rightpunch_sound =
3039 if (playeritem_def.node_placement_prediction == "" ||
3040 nodedef->get(map.getNode(nodepos)).rightclickable)
3041 client.interact(3, pointed); // Report to server
3045 else if(pointed.type == POINTEDTHING_OBJECT)
3047 infotext = narrow_to_wide(selected_object->infoText());
3049 if(infotext == L"" && show_debug){
3050 infotext = narrow_to_wide(selected_object->debugInfoText());
3053 //if(input->getLeftClicked())
3054 if(input->getLeftState())
3056 bool do_punch = false;
3057 bool do_punch_damage = false;
3058 if(object_hit_delay_timer <= 0.0){
3060 do_punch_damage = true;
3061 object_hit_delay_timer = object_hit_delay;
3063 if(input->getLeftClicked()){
3067 infostream<<"Left-clicked object"<<std::endl;
3070 if(do_punch_damage){
3071 // Report direct punch
3072 v3f objpos = selected_object->getPosition();
3073 v3f dir = (objpos - player_position).normalize();
3075 bool disable_send = selected_object->directReportPunch(
3076 dir, &playeritem, time_from_last_punch);
3077 time_from_last_punch = 0;
3079 client.interact(0, pointed);
3082 else if(input->getRightClicked())
3084 infostream<<"Right-clicked object"<<std::endl;
3085 client.interact(3, pointed); // place
3088 else if(input->getLeftState())
3090 // When button is held down in air, show continuous animation
3094 pointed_old = pointed;
3096 if(left_punch || input->getLeftClicked())
3098 camera.setDigging(0); // left click animation
3101 input->resetLeftClicked();
3102 input->resetRightClicked();
3104 input->resetLeftReleased();
3105 input->resetRightReleased();
3108 Calculate stuff for drawing
3115 if(draw_control.range_all)
3116 fog_range = 100000*BS;
3118 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
3119 fog_range = MYMIN(fog_range, (draw_control.farthest_drawn+20)*BS);
3124 Calculate general brightness
3126 u32 daynight_ratio = client.getEnv().getDayNightRatio();
3127 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
3128 float direct_brightness = 0;
3129 bool sunlight_seen = false;
3130 if(g_settings->getBool("free_move")){
3131 direct_brightness = time_brightness;
3132 sunlight_seen = true;
3134 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3135 float old_brightness = sky->getBrightness();
3136 direct_brightness = (float)client.getEnv().getClientMap()
3137 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
3138 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
3142 time_of_day = client.getEnv().getTimeOfDayF();
3144 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
3145 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3146 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3147 time_of_day_smooth = time_of_day;
3149 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
3150 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3151 + (time_of_day+1.0) * todsm;
3153 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3154 + time_of_day * todsm;
3156 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3157 sunlight_seen,camera.getCameraMode(), player->getYaw(),
3158 player->getPitch());
3160 video::SColor bgcolor = sky->getBgColor();
3161 video::SColor skycolor = sky->getSkyColor();
3167 if(sky->getCloudsVisible()){
3168 clouds->setVisible(true);
3169 clouds->step(dtime);
3170 clouds->update(v2f(player_position.X, player_position.Z),
3171 sky->getCloudColor());
3173 clouds->setVisible(false);
3181 allparticles_step(dtime);
3182 allparticlespawners_step(dtime, client.getEnv());
3188 if(g_settings->getBool("enable_fog") && !force_fog_off)
3192 video::EFT_FOG_LINEAR,
3204 video::EFT_FOG_LINEAR,
3214 Update gui stuff (0ms)
3217 //TimeTaker guiupdatetimer("Gui updating");
3221 static float drawtime_avg = 0;
3222 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
3223 /*static float beginscenetime_avg = 0;
3224 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
3225 static float scenetime_avg = 0;
3226 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
3227 static float endscenetime_avg = 0;
3228 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3230 u16 fps = (1.0/dtime_avg1);
3232 std::ostringstream os(std::ios_base::binary);
3234 <<"Minetest "<<minetest_version_hash
3236 <<" (R: range_all="<<draw_control.range_all<<")"
3237 <<std::setprecision(0)
3238 <<" drawtime = "<<drawtime_avg
3239 <<std::setprecision(1)
3240 <<", dtime_jitter = "
3241 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3242 <<std::setprecision(1)
3243 <<", v_range = "<<draw_control.wanted_range
3244 <<std::setprecision(3)
3245 <<", RTT = "<<client.getRTT();
3246 guitext->setText(narrow_to_wide(os.str()).c_str());
3247 guitext->setVisible(true);
3249 else if(show_hud || show_chat)
3251 std::ostringstream os(std::ios_base::binary);
3252 os<<"Minetest "<<minetest_version_hash;
3253 guitext->setText(narrow_to_wide(os.str()).c_str());
3254 guitext->setVisible(true);
3258 guitext->setVisible(false);
3261 if (guitext->isVisible())
3263 core::rect<s32> rect(
3269 guitext->setRelativePosition(rect);
3274 std::ostringstream os(std::ios_base::binary);
3275 os<<std::setprecision(1)<<std::fixed
3276 <<"(" <<(player_position.X/BS)
3277 <<", "<<(player_position.Y/BS)
3278 <<", "<<(player_position.Z/BS)
3279 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3280 <<") (seed = "<<((u64)client.getMapSeed())
3282 guitext2->setText(narrow_to_wide(os.str()).c_str());
3283 guitext2->setVisible(true);
3285 core::rect<s32> rect(
3289 5 + (text_height * 2)
3291 guitext2->setRelativePosition(rect);
3295 guitext2->setVisible(false);
3299 guitext_info->setText(infotext.c_str());
3300 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3304 float statustext_time_max = 1.5;
3305 if(!statustext.empty())
3307 statustext_time += dtime;
3308 if(statustext_time >= statustext_time_max)
3311 statustext_time = 0;
3314 guitext_status->setText(statustext.c_str());
3315 guitext_status->setVisible(!statustext.empty());
3317 if(!statustext.empty())
3319 s32 status_y = screensize.Y - 130;
3320 core::rect<s32> rect(
3322 status_y - guitext_status->getTextHeight(),
3323 10 + guitext_status->getTextWidth(),
3326 guitext_status->setRelativePosition(rect);
3329 video::SColor initial_color(255,0,0,0);
3330 if(guienv->getSkin())
3331 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3332 video::SColor final_color = initial_color;
3333 final_color.setAlpha(0);
3334 video::SColor fade_color =
3335 initial_color.getInterpolated_quadratic(
3338 pow(statustext_time / (float)statustext_time_max, 2.0f));
3339 guitext_status->setOverrideColor(fade_color);
3340 guitext_status->enableOverrideColor(true);
3345 Get chat messages from client
3347 updateChat(client, dtime, show_debug, screensize, show_chat,
3348 show_profiler, chat_backend, guitext_chat, font);
3354 if(client.getPlayerItem() != new_playeritem)
3356 client.selectPlayerItem(new_playeritem);
3358 if(client.getLocalInventoryUpdated())
3360 //infostream<<"Updating local inventory"<<std::endl;
3361 client.getLocalInventory(local_inventory);
3363 update_wielded_item_trigger = true;
3365 if(update_wielded_item_trigger)
3367 update_wielded_item_trigger = false;
3368 // Update wielded tool
3369 InventoryList *mlist = local_inventory.getList("main");
3371 if((mlist != NULL) && (client.getPlayerItem() < mlist->getSize()))
3372 item = mlist->getItem(client.getPlayerItem());
3373 camera.wield(item, client.getPlayerItem());
3377 Update block draw list every 200ms or when camera direction has
3380 update_draw_list_timer += dtime;
3381 if(update_draw_list_timer >= 0.2 ||
3382 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2 ||
3383 camera_offset_changed){
3384 update_draw_list_timer = 0;
3385 client.getEnv().getClientMap().updateDrawList(driver);
3386 update_draw_list_last_cam_dir = camera_direction;
3390 make sure menu is on top
3392 if ((!noMenuActive()) && (current_formspec)) {
3393 guiroot->bringToFront(current_formspec);
3399 TimeTaker tt_draw("mainloop: draw");
3401 TimeTaker timer("beginScene");
3402 driver->beginScene(true, true, skycolor);
3403 beginscenetime = timer.stop(true);
3407 draw_scene(driver, smgr, camera, client, player, hud, guienv,
3408 hilightboxes, screensize, skycolor, show_hud);
3413 if(show_profiler_graph)
3415 graph.draw(10, screensize.Y - 10, driver, font);
3421 if(damage_flash > 0.0)
3423 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3424 driver->draw2DRectangle(color,
3425 core::rect<s32>(0,0,screensize.X,screensize.Y),
3428 damage_flash -= 100.0*dtime;
3434 if(player->hurt_tilt_timer > 0.0)
3436 player->hurt_tilt_timer -= dtime*5;
3437 if(player->hurt_tilt_timer < 0)
3438 player->hurt_tilt_strength = 0;
3445 TimeTaker timer("endScene");
3447 endscenetime = timer.stop(true);
3450 drawtime = tt_draw.stop(true);
3451 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3458 Log times and stuff for visualization
3460 Profiler::GraphValues values;
3461 g_profiler->graphGet(values);
3470 if (gui_chat_console)
3471 gui_chat_console->drop();
3477 while (g_menumgr.menuCount() > 0)
3479 g_menumgr.m_stack.front()->setVisible(false);
3480 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
3483 Draw a "shutting down" screen, which will be shown while the map
3484 generator and other stuff quits
3487 wchar_t* text = wgettext("Shutting down stuff...");
3488 draw_load_screen(text, device, guienv, font, 0, -1, false);
3492 chat_backend.addMessage(L"", L"# Disconnected.");
3493 chat_backend.addMessage(L"", L"");
3497 //force answer all texture and shader jobs (TODO return empty values)
3499 while(!client.isShutdown()) {
3500 tsrc->processQueue();
3501 shsrc->processQueue();
3505 // Client scope (client is destructed before destructing *def and tsrc)
3508 catch(SerializationError &e)
3510 error_message = L"A serialization error occurred:\n"
3511 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3512 L" running a different version of Minetest.";
3513 errorstream<<wide_to_narrow(error_message)<<std::endl;
3515 catch(ServerError &e) {
3516 error_message = narrow_to_wide(e.what());
3517 errorstream << "ServerError: " << e.what() << std::endl;
3519 catch(ModError &e) {
3520 errorstream << "ModError: " << e.what() << std::endl;
3521 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3529 //has to be deleted first to stop all server threads
3537 //extended resource accounting
3538 infostream << "Irrlicht resources after cleanup:" << std::endl;
3539 infostream << "\tRemaining meshes : "
3540 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3541 infostream << "\tRemaining textures : "
3542 << driver->getTextureCount() << std::endl;
3543 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3544 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3545 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3548 clearTextureNameCache();
3549 infostream << "\tRemaining materials: "
3550 << driver-> getMaterialRendererCount ()
3551 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;