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
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 );
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);
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);
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);
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);
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 irr::video::IImage* const raw_image = driver->createScreenShot();
2075 irr::video::IImage* const image = driver->createImage(video::ECF_R8G8B8,
2076 raw_image->getDimension());
2079 raw_image->copyTo(image);
2080 irr::c8 filename[256];
2081 snprintf(filename, sizeof(filename), "%s" DIR_DELIM "screenshot_%u.png",
2082 g_settings->get("screenshot_path").c_str(),
2083 device->getTimer()->getRealTime());
2084 if (driver->writeImageToFile(image, filename)) {
2085 std::wstringstream sstr;
2086 sstr << "Saved screenshot to '" << filename << "'";
2087 infostream << "Saved screenshot to '" << filename << "'" << std::endl;
2088 statustext = sstr.str();
2089 statustext_time = 0;
2091 infostream << "Failed to save screenshot '" << filename << "'" << std::endl;
2098 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
2100 show_hud = !show_hud;
2102 statustext = L"HUD shown";
2103 client.setHighlighted(client.getHighlighted(), true);
2105 statustext = L"HUD hidden";
2106 client.setHighlighted(client.getHighlighted(), false);
2108 statustext_time = 0;
2110 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
2112 show_chat = !show_chat;
2114 statustext = L"Chat shown";
2116 statustext = L"Chat hidden";
2117 statustext_time = 0;
2119 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
2121 force_fog_off = !force_fog_off;
2123 statustext = L"Fog disabled";
2125 statustext = L"Fog enabled";
2126 statustext_time = 0;
2128 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
2130 disable_camera_update = !disable_camera_update;
2131 if(disable_camera_update)
2132 statustext = L"Camera update disabled";
2134 statustext = L"Camera update enabled";
2135 statustext_time = 0;
2137 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
2139 // Initial / 3x toggle: Chat only
2140 // 1x toggle: Debug text with chat
2141 // 2x toggle: Debug text with profiler graph
2145 show_profiler_graph = false;
2146 statustext = L"Debug info shown";
2147 statustext_time = 0;
2149 else if(show_profiler_graph)
2152 show_profiler_graph = false;
2153 statustext = L"Debug info and profiler graph hidden";
2154 statustext_time = 0;
2158 show_profiler_graph = true;
2159 statustext = L"Profiler graph shown";
2160 statustext_time = 0;
2163 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
2165 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
2167 // FIXME: This updates the profiler with incomplete values
2168 update_profiler_gui(guitext_profiler, font, text_height,
2169 show_profiler, show_profiler_max);
2171 if(show_profiler != 0)
2173 std::wstringstream sstr;
2174 sstr<<"Profiler shown (page "<<show_profiler
2175 <<" of "<<show_profiler_max<<")";
2176 statustext = sstr.str();
2177 statustext_time = 0;
2181 statustext = L"Profiler hidden";
2182 statustext_time = 0;
2185 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
2187 s16 range = g_settings->getS16("viewing_range_nodes_min");
2188 s16 range_new = range + 10;
2189 g_settings->set("viewing_range_nodes_min", itos(range_new));
2190 statustext = narrow_to_wide(
2191 "Minimum viewing range changed to "
2193 statustext_time = 0;
2195 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
2197 s16 range = g_settings->getS16("viewing_range_nodes_min");
2198 s16 range_new = range - 10;
2201 g_settings->set("viewing_range_nodes_min",
2203 statustext = narrow_to_wide(
2204 "Minimum viewing range changed to "
2206 statustext_time = 0;
2210 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
2212 reset_jump_timer = false;
2216 // Handle QuicktuneShortcutter
2217 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2219 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2221 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2223 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2226 std::string msg = quicktune.getMessage();
2228 statustext = narrow_to_wide(msg);
2229 statustext_time = 0;
2233 // Item selection with mouse wheel
2234 u16 new_playeritem = client.getPlayerItem();
2236 s32 wheel = input->getMouseWheel();
2237 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2238 player->hud_hotbar_itemcount-1);
2242 if(new_playeritem < max_item)
2249 if(new_playeritem > 0)
2252 new_playeritem = max_item;
2257 for(u16 i=0; i<10; i++)
2259 const KeyPress *kp = NumberKey + (i + 1) % 10;
2260 if(input->wasKeyDown(*kp))
2262 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2266 infostream<<"Selected item: "
2267 <<new_playeritem<<std::endl;
2272 // Viewing range selection
2273 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2275 draw_control.range_all = !draw_control.range_all;
2276 if(draw_control.range_all)
2278 infostream<<"Enabled full viewing range"<<std::endl;
2279 statustext = L"Enabled full viewing range";
2280 statustext_time = 0;
2284 infostream<<"Disabled full viewing range"<<std::endl;
2285 statustext = L"Disabled full viewing range";
2286 statustext_time = 0;
2290 // Print debug stacks
2291 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2293 dstream<<"-----------------------------------------"
2295 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2296 dstream<<"-----------------------------------------"
2298 debug_stacks_print();
2302 Mouse and camera control
2303 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2306 float turn_amount = 0;
2307 if((device->isWindowActive() && noMenuActive()) || random_input)
2312 // Mac OSX gets upset if this is set every frame
2313 if(device->getCursorControl()->isVisible())
2314 device->getCursorControl()->setVisible(false);
2318 if(first_loop_after_window_activation){
2319 //infostream<<"window active, first loop"<<std::endl;
2320 first_loop_after_window_activation = false;
2322 #ifdef HAVE_TOUCHSCREENGUI
2323 if (g_touchscreengui) {
2324 camera_yaw = g_touchscreengui->getYaw();
2325 camera_pitch = g_touchscreengui->getPitch();
2328 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width/2);
2329 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height/2);
2331 || (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)) {
2334 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2336 /*const float keyspeed = 500;
2337 if(input->isKeyDown(irr::KEY_UP))
2338 dy -= dtime * keyspeed;
2339 if(input->isKeyDown(irr::KEY_DOWN))
2340 dy += dtime * keyspeed;
2341 if(input->isKeyDown(irr::KEY_LEFT))
2342 dx -= dtime * keyspeed;
2343 if(input->isKeyDown(irr::KEY_RIGHT))
2344 dx += dtime * keyspeed;*/
2346 float d = g_settings->getFloat("mouse_sensitivity");
2347 d = rangelim(d, 0.01, 100.0);
2349 camera_pitch += dy*d;
2350 turn_amount = v2f(dx, dy).getLength() * d;
2352 #ifdef HAVE_TOUCHSCREENGUI
2355 if(camera_pitch < -89.5) camera_pitch = -89.5;
2356 if(camera_pitch > 89.5) camera_pitch = 89.5;
2358 input->setMousePos((driver->getScreenSize().Width/2),
2359 (driver->getScreenSize().Height/2));
2363 // Mac OSX gets upset if this is set every frame
2364 if(device->getCursorControl()->isVisible() == false)
2365 device->getCursorControl()->setVisible(true);
2368 //infostream<<"window inactive"<<std::endl;
2369 first_loop_after_window_activation = true;
2371 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2372 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2375 Player speed control
2389 PlayerControl control(
2390 input->isKeyDown(getKeySetting("keymap_forward")),
2391 input->isKeyDown(getKeySetting("keymap_backward")),
2392 input->isKeyDown(getKeySetting("keymap_left")),
2393 input->isKeyDown(getKeySetting("keymap_right")),
2394 input->isKeyDown(getKeySetting("keymap_jump")),
2395 input->isKeyDown(getKeySetting("keymap_special1")),
2396 input->isKeyDown(getKeySetting("keymap_sneak")),
2397 input->getLeftState(),
2398 input->getRightState(),
2402 client.setPlayerControl(control);
2403 LocalPlayer* player = client.getEnv().getLocalPlayer();
2405 (((int)input->isKeyDown(getKeySetting("keymap_forward")) & 0x1) << 0) |
2406 (((int)input->isKeyDown(getKeySetting("keymap_backward")) & 0x1) << 1) |
2407 (((int)input->isKeyDown(getKeySetting("keymap_left")) & 0x1) << 2) |
2408 (((int)input->isKeyDown(getKeySetting("keymap_right")) & 0x1) << 3) |
2409 (((int)input->isKeyDown(getKeySetting("keymap_jump")) & 0x1) << 4) |
2410 (((int)input->isKeyDown(getKeySetting("keymap_special1")) & 0x1) << 5) |
2411 (((int)input->isKeyDown(getKeySetting("keymap_sneak")) & 0x1) << 6) |
2412 (((int)input->getLeftState() & 0x1) << 7) |
2413 (((int)input->getRightState() & 0x1) << 8);
2417 Run server, client (and process environments)
2419 bool can_be_and_is_paused =
2420 (simple_singleplayer_mode && g_menumgr.pausesGame());
2421 if(can_be_and_is_paused)
2430 //TimeTaker timer("server->step(dtime)");
2431 server->step(dtime);
2434 //TimeTaker timer("client.step(dtime)");
2440 // Read client events
2442 ClientEvent event = client.getClientEvent();
2443 if(event.type == CE_NONE) {
2446 else if(event.type == CE_PLAYER_DAMAGE &&
2447 client.getHP() != 0) {
2448 //u16 damage = event.player_damage.amount;
2449 //infostream<<"Player damage: "<<damage<<std::endl;
2451 damage_flash += 100.0;
2452 damage_flash += 8.0 * event.player_damage.amount;
2454 player->hurt_tilt_timer = 1.5;
2455 player->hurt_tilt_strength = event.player_damage.amount/4;
2456 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
2458 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2459 gamedef->event()->put(e);
2461 else if(event.type == CE_PLAYER_FORCE_MOVE) {
2462 camera_yaw = event.player_force_move.yaw;
2463 camera_pitch = event.player_force_move.pitch;
2465 else if(event.type == CE_DEATHSCREEN) {
2466 show_deathscreen(¤t_formspec, &client, gamedef, tsrc,
2469 chat_backend.addMessage(L"", L"You died.");
2471 /* Handle visualization */
2474 LocalPlayer* player = client.getEnv().getLocalPlayer();
2475 player->hurt_tilt_timer = 0;
2476 player->hurt_tilt_strength = 0;
2479 else if (event.type == CE_SHOW_FORMSPEC) {
2480 FormspecFormSource* fs_src =
2481 new FormspecFormSource(*(event.show_formspec.formspec));
2482 TextDestPlayerInventory* txt_dst =
2483 new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2485 create_formspec_menu(¤t_formspec, &client, gamedef,
2486 tsrc, device, fs_src, txt_dst);
2488 delete(event.show_formspec.formspec);
2489 delete(event.show_formspec.formname);
2491 else if(event.type == CE_SPAWN_PARTICLE) {
2492 LocalPlayer* player = client.getEnv().getLocalPlayer();
2493 video::ITexture *texture =
2494 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2496 new Particle(gamedef, smgr, player, client.getEnv(),
2497 *event.spawn_particle.pos,
2498 *event.spawn_particle.vel,
2499 *event.spawn_particle.acc,
2500 event.spawn_particle.expirationtime,
2501 event.spawn_particle.size,
2502 event.spawn_particle.collisiondetection,
2503 event.spawn_particle.vertical,
2508 else if(event.type == CE_ADD_PARTICLESPAWNER) {
2509 LocalPlayer* player = client.getEnv().getLocalPlayer();
2510 video::ITexture *texture =
2511 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2513 new ParticleSpawner(gamedef, smgr, player,
2514 event.add_particlespawner.amount,
2515 event.add_particlespawner.spawntime,
2516 *event.add_particlespawner.minpos,
2517 *event.add_particlespawner.maxpos,
2518 *event.add_particlespawner.minvel,
2519 *event.add_particlespawner.maxvel,
2520 *event.add_particlespawner.minacc,
2521 *event.add_particlespawner.maxacc,
2522 event.add_particlespawner.minexptime,
2523 event.add_particlespawner.maxexptime,
2524 event.add_particlespawner.minsize,
2525 event.add_particlespawner.maxsize,
2526 event.add_particlespawner.collisiondetection,
2527 event.add_particlespawner.vertical,
2529 event.add_particlespawner.id);
2531 else if(event.type == CE_DELETE_PARTICLESPAWNER) {
2532 delete_particlespawner (event.delete_particlespawner.id);
2534 else if (event.type == CE_HUDADD) {
2535 u32 id = event.hudadd.id;
2537 HudElement *e = player->getHud(id);
2540 delete event.hudadd.pos;
2541 delete event.hudadd.name;
2542 delete event.hudadd.scale;
2543 delete event.hudadd.text;
2544 delete event.hudadd.align;
2545 delete event.hudadd.offset;
2546 delete event.hudadd.world_pos;
2547 delete event.hudadd.size;
2552 e->type = (HudElementType)event.hudadd.type;
2553 e->pos = *event.hudadd.pos;
2554 e->name = *event.hudadd.name;
2555 e->scale = *event.hudadd.scale;
2556 e->text = *event.hudadd.text;
2557 e->number = event.hudadd.number;
2558 e->item = event.hudadd.item;
2559 e->dir = event.hudadd.dir;
2560 e->align = *event.hudadd.align;
2561 e->offset = *event.hudadd.offset;
2562 e->world_pos = *event.hudadd.world_pos;
2563 e->size = *event.hudadd.size;
2565 u32 new_id = player->addHud(e);
2566 //if this isn't true our huds aren't consistent
2567 assert(new_id == id);
2569 delete event.hudadd.pos;
2570 delete event.hudadd.name;
2571 delete event.hudadd.scale;
2572 delete event.hudadd.text;
2573 delete event.hudadd.align;
2574 delete event.hudadd.offset;
2575 delete event.hudadd.world_pos;
2576 delete event.hudadd.size;
2578 else if (event.type == CE_HUDRM) {
2579 HudElement* e = player->removeHud(event.hudrm.id);
2584 else if (event.type == CE_HUDCHANGE) {
2585 u32 id = event.hudchange.id;
2586 HudElement* e = player->getHud(id);
2589 delete event.hudchange.v3fdata;
2590 delete event.hudchange.v2fdata;
2591 delete event.hudchange.sdata;
2592 delete event.hudchange.v2s32data;
2596 switch (event.hudchange.stat) {
2598 e->pos = *event.hudchange.v2fdata;
2601 e->name = *event.hudchange.sdata;
2603 case HUD_STAT_SCALE:
2604 e->scale = *event.hudchange.v2fdata;
2607 e->text = *event.hudchange.sdata;
2609 case HUD_STAT_NUMBER:
2610 e->number = event.hudchange.data;
2613 e->item = event.hudchange.data;
2616 e->dir = event.hudchange.data;
2618 case HUD_STAT_ALIGN:
2619 e->align = *event.hudchange.v2fdata;
2621 case HUD_STAT_OFFSET:
2622 e->offset = *event.hudchange.v2fdata;
2624 case HUD_STAT_WORLD_POS:
2625 e->world_pos = *event.hudchange.v3fdata;
2628 e->size = *event.hudchange.v2s32data;
2632 delete event.hudchange.v3fdata;
2633 delete event.hudchange.v2fdata;
2634 delete event.hudchange.sdata;
2635 delete event.hudchange.v2s32data;
2637 else if (event.type == CE_SET_SKY) {
2638 sky->setVisible(false);
2643 // Handle according to type
2644 if(*event.set_sky.type == "regular") {
2645 sky->setVisible(true);
2647 else if(*event.set_sky.type == "skybox" &&
2648 event.set_sky.params->size() == 6) {
2649 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2650 skybox = smgr->addSkyBoxSceneNode(
2651 tsrc->getTexture((*event.set_sky.params)[0]),
2652 tsrc->getTexture((*event.set_sky.params)[1]),
2653 tsrc->getTexture((*event.set_sky.params)[2]),
2654 tsrc->getTexture((*event.set_sky.params)[3]),
2655 tsrc->getTexture((*event.set_sky.params)[4]),
2656 tsrc->getTexture((*event.set_sky.params)[5]));
2658 // Handle everything else as plain color
2660 if(*event.set_sky.type != "plain")
2661 infostream<<"Unknown sky type: "
2662 <<(*event.set_sky.type)<<std::endl;
2663 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2666 delete event.set_sky.bgcolor;
2667 delete event.set_sky.type;
2668 delete event.set_sky.params;
2670 else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
2671 bool enable = event.override_day_night_ratio.do_override;
2672 u32 value = event.override_day_night_ratio.ratio_f * 1000;
2673 client.getEnv().setDayNightRatioOverride(enable, value);
2678 //TimeTaker //timer2("//timer2");
2681 For interaction purposes, get info about the held item
2683 - Is it a usable item?
2684 - Can it point to liquids?
2686 ItemStack playeritem;
2688 InventoryList *mlist = local_inventory.getList("main");
2689 if((mlist != NULL) && (client.getPlayerItem() < mlist->getSize()))
2690 playeritem = mlist->getItem(client.getPlayerItem());
2692 const ItemDefinition &playeritem_def =
2693 playeritem.getDefinition(itemdef);
2694 ToolCapabilities playeritem_toolcap =
2695 playeritem.getToolCapabilities(itemdef);
2701 v3s16 old_camera_offset = camera.getOffset();
2703 LocalPlayer* player = client.getEnv().getLocalPlayer();
2704 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2705 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2707 if(input->wasKeyDown(getKeySetting("keymap_camera_mode"))) {
2708 camera.toggleCameraMode();
2709 GenericCAO* playercao = player->getCAO();
2711 assert( playercao != NULL );
2712 if (camera.getCameraMode() > CAMERA_MODE_FIRST) {
2713 playercao->setVisible(true);
2716 playercao->setVisible(false);
2719 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2720 camera.update(player, dtime, busytime, tool_reload_ratio,
2724 v3f player_position = player->getPosition();
2725 v3f camera_position = camera.getPosition();
2726 v3f camera_direction = camera.getDirection();
2727 f32 camera_fov = camera.getFovMax();
2728 v3s16 camera_offset = camera.getOffset();
2730 bool camera_offset_changed = (camera_offset != old_camera_offset);
2732 if(!disable_camera_update){
2733 client.getEnv().getClientMap().updateCamera(camera_position,
2734 camera_direction, camera_fov, camera_offset);
2735 if (camera_offset_changed){
2736 client.updateCameraOffset(camera_offset);
2737 client.getEnv().updateCameraOffset(camera_offset);
2739 clouds->updateCameraOffset(camera_offset);
2743 // Update sound listener
2744 sound->updateListener(camera.getCameraNode()->getPosition()+intToFloat(camera_offset, BS),
2745 v3f(0,0,0), // velocity
2746 camera.getDirection(),
2747 camera.getCameraNode()->getUpVector());
2748 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2754 soundmaker.step(dtime);
2756 ClientMap &map = client.getEnv().getClientMap();
2757 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2758 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2762 Calculate what block is the crosshair pointing to
2765 //u32 t1 = device->getTimer()->getRealTime();
2767 f32 d = playeritem_def.range; // max. distance
2768 f32 d_hand = itemdef->get("").range;
2769 if(d < 0 && d_hand >= 0)
2773 core::line3d<f32> shootline(camera_position,
2774 camera_position + camera_direction * BS * (d+1));
2777 // prevent player pointing anything in front-view
2778 if (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)
2779 shootline = core::line3d<f32>(0,0,0,0,0,0);
2781 #ifdef HAVE_TOUCHSCREENGUI
2782 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
2783 shootline = g_touchscreengui->getShootline();
2784 shootline.start += intToFloat(camera_offset,BS);
2785 shootline.end += intToFloat(camera_offset,BS);
2789 ClientActiveObject *selected_object = NULL;
2791 PointedThing pointed = getPointedThing(
2793 &client, player_position, camera_direction,
2794 camera_position, shootline, d,
2795 playeritem_def.liquids_pointable, !ldown_for_dig,
2801 if(pointed != pointed_old)
2803 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2804 if (g_settings->getBool("enable_node_highlighting"))
2805 client.setHighlighted(pointed.node_undersurface, show_hud);
2810 - releasing left mouse button
2811 - pointing away from node
2815 if(input->getLeftReleased())
2817 infostream<<"Left button released"
2818 <<" (stopped digging)"<<std::endl;
2821 else if(pointed != pointed_old)
2823 if (pointed.type == POINTEDTHING_NODE
2824 && pointed_old.type == POINTEDTHING_NODE
2825 && pointed.node_undersurface == pointed_old.node_undersurface)
2827 // Still pointing to the same node,
2828 // but a different face. Don't reset.
2832 infostream<<"Pointing away from node"
2833 <<" (stopped digging)"<<std::endl;
2839 client.interact(1, pointed_old);
2840 client.setCrack(-1, v3s16(0,0,0));
2844 if(!digging && ldown_for_dig && !input->getLeftState())
2846 ldown_for_dig = false;
2849 bool left_punch = false;
2850 soundmaker.m_player_leftpunch_sound.name = "";
2852 if(input->getRightState())
2853 repeat_rightclick_timer += dtime;
2855 repeat_rightclick_timer = 0;
2857 if(playeritem_def.usable && input->getLeftState())
2859 if(input->getLeftClicked())
2860 client.interact(4, pointed);
2862 else if(pointed.type == POINTEDTHING_NODE)
2864 v3s16 nodepos = pointed.node_undersurface;
2865 v3s16 neighbourpos = pointed.node_abovesurface;
2868 Check information text of node
2871 ClientMap &map = client.getEnv().getClientMap();
2872 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2874 infotext = narrow_to_wide(meta->getString("infotext"));
2876 MapNode n = map.getNode(nodepos);
2877 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2878 infotext = L"Unknown node: ";
2879 infotext += narrow_to_wide(nodedef->get(n).name);
2887 if(nodig_delay_timer <= 0.0 && input->getLeftState()
2888 && client.checkPrivilege("interact"))
2892 infostream<<"Started digging"<<std::endl;
2893 client.interact(0, pointed);
2895 ldown_for_dig = true;
2897 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2899 // NOTE: Similar piece of code exists on the server side for
2901 // Get digging parameters
2902 DigParams params = getDigParams(nodedef->get(n).groups,
2903 &playeritem_toolcap);
2904 // If can't dig, try hand
2905 if(!params.diggable){
2906 const ItemDefinition &hand = itemdef->get("");
2907 const ToolCapabilities *tp = hand.tool_capabilities;
2909 params = getDigParams(nodedef->get(n).groups, tp);
2912 float dig_time_complete = 0.0;
2914 if(params.diggable == false)
2916 // I guess nobody will wait for this long
2917 dig_time_complete = 10000000.0;
2921 dig_time_complete = params.time;
2922 if (g_settings->getBool("enable_particles"))
2924 const ContentFeatures &features =
2925 client.getNodeDefManager()->get(n);
2926 addPunchingParticles
2927 (gamedef, smgr, player, client.getEnv(),
2928 nodepos, features.tiles);
2932 if(dig_time_complete >= 0.001)
2934 dig_index = (u16)((float)crack_animation_length
2935 * dig_time/dig_time_complete);
2937 // This is for torches
2940 dig_index = crack_animation_length;
2943 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2944 if(sound_dig.exists() && params.diggable){
2945 if(sound_dig.name == "__group"){
2946 if(params.main_group != ""){
2947 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2948 soundmaker.m_player_leftpunch_sound.name =
2949 std::string("default_dig_") +
2953 soundmaker.m_player_leftpunch_sound = sound_dig;
2957 // Don't show cracks if not diggable
2958 if(dig_time_complete >= 100000.0)
2961 else if(dig_index < crack_animation_length)
2963 //TimeTaker timer("client.setTempMod");
2964 //infostream<<"dig_index="<<dig_index<<std::endl;
2965 client.setCrack(dig_index, nodepos);
2969 infostream<<"Digging completed"<<std::endl;
2970 client.interact(2, pointed);
2971 client.setCrack(-1, v3s16(0,0,0));
2972 MapNode wasnode = map.getNode(nodepos);
2973 client.removeNode(nodepos);
2975 if (g_settings->getBool("enable_particles"))
2977 const ContentFeatures &features =
2978 client.getNodeDefManager()->get(wasnode);
2980 (gamedef, smgr, player, client.getEnv(),
2981 nodepos, features.tiles);
2987 nodig_delay_timer = dig_time_complete
2988 / (float)crack_animation_length;
2990 // We don't want a corresponding delay to
2991 // very time consuming nodes
2992 if(nodig_delay_timer > 0.3)
2993 nodig_delay_timer = 0.3;
2994 // We want a slight delay to very little
2995 // time consuming nodes
2996 float mindelay = 0.15;
2997 if(nodig_delay_timer < mindelay)
2998 nodig_delay_timer = mindelay;
3000 // Send event to trigger sound
3001 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3002 gamedef->event()->put(e);
3005 if(dig_time_complete < 100000.0)
3009 client.setCrack(-1, nodepos);
3012 camera.setDigging(0); // left click animation
3015 if((input->getRightClicked() ||
3016 repeat_rightclick_timer >=
3017 g_settings->getFloat("repeat_rightclick_time")) &&
3018 client.checkPrivilege("interact"))
3020 repeat_rightclick_timer = 0;
3021 infostream<<"Ground right-clicked"<<std::endl;
3023 if(meta && meta->getString("formspec") != "" && !random_input
3024 && !input->isKeyDown(getKeySetting("keymap_sneak")))
3026 infostream<<"Launching custom inventory view"<<std::endl;
3028 InventoryLocation inventoryloc;
3029 inventoryloc.setNodeMeta(nodepos);
3031 NodeMetadataFormSource* fs_src = new NodeMetadataFormSource(
3032 &client.getEnv().getClientMap(), nodepos);
3033 TextDest* txt_dst = new TextDestNodeMetadata(nodepos, &client);
3035 create_formspec_menu(¤t_formspec, &client, gamedef,
3036 tsrc, device, fs_src, txt_dst);
3038 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3040 // Otherwise report right click to server
3043 camera.setDigging(1); // right click animation (always shown for feedback)
3045 // If the wielded item has node placement prediction,
3047 bool placed = nodePlacementPrediction(client,
3049 nodepos, neighbourpos);
3053 client.interact(3, pointed);
3055 soundmaker.m_player_rightpunch_sound =
3056 playeritem_def.sound_place;
3058 soundmaker.m_player_rightpunch_sound =
3062 if (playeritem_def.node_placement_prediction == "" ||
3063 nodedef->get(map.getNode(nodepos)).rightclickable)
3064 client.interact(3, pointed); // Report to server
3068 else if(pointed.type == POINTEDTHING_OBJECT)
3070 infotext = narrow_to_wide(selected_object->infoText());
3072 if(infotext == L"" && show_debug){
3073 infotext = narrow_to_wide(selected_object->debugInfoText());
3076 //if(input->getLeftClicked())
3077 if(input->getLeftState())
3079 bool do_punch = false;
3080 bool do_punch_damage = false;
3081 if(object_hit_delay_timer <= 0.0){
3083 do_punch_damage = true;
3084 object_hit_delay_timer = object_hit_delay;
3086 if(input->getLeftClicked()){
3090 infostream<<"Left-clicked object"<<std::endl;
3093 if(do_punch_damage){
3094 // Report direct punch
3095 v3f objpos = selected_object->getPosition();
3096 v3f dir = (objpos - player_position).normalize();
3098 bool disable_send = selected_object->directReportPunch(
3099 dir, &playeritem, time_from_last_punch);
3100 time_from_last_punch = 0;
3102 client.interact(0, pointed);
3105 else if(input->getRightClicked())
3107 infostream<<"Right-clicked object"<<std::endl;
3108 client.interact(3, pointed); // place
3111 else if(input->getLeftState())
3113 // When button is held down in air, show continuous animation
3117 pointed_old = pointed;
3119 if(left_punch || input->getLeftClicked())
3121 camera.setDigging(0); // left click animation
3124 input->resetLeftClicked();
3125 input->resetRightClicked();
3127 input->resetLeftReleased();
3128 input->resetRightReleased();
3131 Calculate stuff for drawing
3138 if(draw_control.range_all)
3139 fog_range = 100000*BS;
3141 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
3142 fog_range = MYMIN(fog_range, (draw_control.farthest_drawn+20)*BS);
3147 Calculate general brightness
3149 u32 daynight_ratio = client.getEnv().getDayNightRatio();
3150 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
3151 float direct_brightness = 0;
3152 bool sunlight_seen = false;
3153 if(g_settings->getBool("free_move")){
3154 direct_brightness = time_brightness;
3155 sunlight_seen = true;
3157 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3158 float old_brightness = sky->getBrightness();
3159 direct_brightness = (float)client.getEnv().getClientMap()
3160 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
3161 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
3165 time_of_day = client.getEnv().getTimeOfDayF();
3167 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
3168 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3169 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3170 time_of_day_smooth = time_of_day;
3172 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
3173 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3174 + (time_of_day+1.0) * todsm;
3176 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3177 + time_of_day * todsm;
3179 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3180 sunlight_seen,camera.getCameraMode(), player->getYaw(),
3181 player->getPitch());
3183 video::SColor bgcolor = sky->getBgColor();
3184 video::SColor skycolor = sky->getSkyColor();
3190 if(sky->getCloudsVisible()){
3191 clouds->setVisible(true);
3192 clouds->step(dtime);
3193 clouds->update(v2f(player_position.X, player_position.Z),
3194 sky->getCloudColor());
3196 clouds->setVisible(false);
3204 allparticles_step(dtime);
3205 allparticlespawners_step(dtime, client.getEnv());
3211 if(g_settings->getBool("enable_fog") && !force_fog_off)
3215 video::EFT_FOG_LINEAR,
3227 video::EFT_FOG_LINEAR,
3237 Update gui stuff (0ms)
3240 //TimeTaker guiupdatetimer("Gui updating");
3244 static float drawtime_avg = 0;
3245 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
3246 /*static float beginscenetime_avg = 0;
3247 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
3248 static float scenetime_avg = 0;
3249 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
3250 static float endscenetime_avg = 0;
3251 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3253 u16 fps = (1.0/dtime_avg1);
3255 std::ostringstream os(std::ios_base::binary);
3257 <<"Minetest "<<minetest_version_hash
3259 <<" (R: range_all="<<draw_control.range_all<<")"
3260 <<std::setprecision(0)
3261 <<" drawtime = "<<drawtime_avg
3262 <<std::setprecision(1)
3263 <<", dtime_jitter = "
3264 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3265 <<std::setprecision(1)
3266 <<", v_range = "<<draw_control.wanted_range
3267 <<std::setprecision(3)
3268 <<", RTT = "<<client.getRTT();
3269 guitext->setText(narrow_to_wide(os.str()).c_str());
3270 guitext->setVisible(true);
3272 else if(show_hud || show_chat)
3274 std::ostringstream os(std::ios_base::binary);
3275 os<<"Minetest "<<minetest_version_hash;
3276 guitext->setText(narrow_to_wide(os.str()).c_str());
3277 guitext->setVisible(true);
3281 guitext->setVisible(false);
3284 if (guitext->isVisible())
3286 core::rect<s32> rect(
3292 guitext->setRelativePosition(rect);
3297 std::ostringstream os(std::ios_base::binary);
3298 os<<std::setprecision(1)<<std::fixed
3299 <<"(" <<(player_position.X/BS)
3300 <<", "<<(player_position.Y/BS)
3301 <<", "<<(player_position.Z/BS)
3302 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3303 <<") (seed = "<<((u64)client.getMapSeed())
3305 guitext2->setText(narrow_to_wide(os.str()).c_str());
3306 guitext2->setVisible(true);
3308 core::rect<s32> rect(
3312 5 + (text_height * 2)
3314 guitext2->setRelativePosition(rect);
3318 guitext2->setVisible(false);
3322 guitext_info->setText(infotext.c_str());
3323 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3327 float statustext_time_max = 1.5;
3328 if(!statustext.empty())
3330 statustext_time += dtime;
3331 if(statustext_time >= statustext_time_max)
3334 statustext_time = 0;
3337 guitext_status->setText(statustext.c_str());
3338 guitext_status->setVisible(!statustext.empty());
3340 if(!statustext.empty())
3342 s32 status_y = screensize.Y - 130;
3343 core::rect<s32> rect(
3345 status_y - guitext_status->getTextHeight(),
3346 10 + guitext_status->getTextWidth(),
3349 guitext_status->setRelativePosition(rect);
3352 video::SColor initial_color(255,0,0,0);
3353 if(guienv->getSkin())
3354 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3355 video::SColor final_color = initial_color;
3356 final_color.setAlpha(0);
3357 video::SColor fade_color =
3358 initial_color.getInterpolated_quadratic(
3361 pow(statustext_time / (float)statustext_time_max, 2.0f));
3362 guitext_status->setOverrideColor(fade_color);
3363 guitext_status->enableOverrideColor(true);
3368 Get chat messages from client
3370 updateChat(client, dtime, show_debug, screensize, show_chat,
3371 show_profiler, chat_backend, guitext_chat, font);
3377 if(client.getPlayerItem() != new_playeritem)
3379 client.selectPlayerItem(new_playeritem);
3381 if(client.getLocalInventoryUpdated())
3383 //infostream<<"Updating local inventory"<<std::endl;
3384 client.getLocalInventory(local_inventory);
3386 update_wielded_item_trigger = true;
3388 if(update_wielded_item_trigger)
3390 update_wielded_item_trigger = false;
3391 // Update wielded tool
3392 InventoryList *mlist = local_inventory.getList("main");
3394 if((mlist != NULL) && (client.getPlayerItem() < mlist->getSize()))
3395 item = mlist->getItem(client.getPlayerItem());
3396 camera.wield(item, client.getPlayerItem());
3400 Update block draw list every 200ms or when camera direction has
3403 update_draw_list_timer += dtime;
3404 if(update_draw_list_timer >= 0.2 ||
3405 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2 ||
3406 camera_offset_changed){
3407 update_draw_list_timer = 0;
3408 client.getEnv().getClientMap().updateDrawList(driver);
3409 update_draw_list_last_cam_dir = camera_direction;
3413 make sure menu is on top
3415 if ((!noMenuActive()) && (current_formspec)) {
3416 guiroot->bringToFront(current_formspec);
3422 TimeTaker tt_draw("mainloop: draw");
3424 TimeTaker timer("beginScene");
3425 driver->beginScene(true, true, skycolor);
3426 beginscenetime = timer.stop(true);
3430 draw_scene(driver, smgr, camera, client, player, hud, guienv,
3431 hilightboxes, screensize, skycolor, show_hud);
3436 if(show_profiler_graph)
3438 graph.draw(10, screensize.Y - 10, driver, font);
3444 if(damage_flash > 0.0)
3446 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3447 driver->draw2DRectangle(color,
3448 core::rect<s32>(0,0,screensize.X,screensize.Y),
3451 damage_flash -= 100.0*dtime;
3457 if(player->hurt_tilt_timer > 0.0)
3459 player->hurt_tilt_timer -= dtime*5;
3460 if(player->hurt_tilt_timer < 0)
3461 player->hurt_tilt_strength = 0;
3468 TimeTaker timer("endScene");
3470 endscenetime = timer.stop(true);
3473 drawtime = tt_draw.stop(true);
3474 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3481 Log times and stuff for visualization
3483 Profiler::GraphValues values;
3484 g_profiler->graphGet(values);
3493 if (gui_chat_console)
3494 gui_chat_console->drop();
3500 while (g_menumgr.menuCount() > 0)
3502 g_menumgr.m_stack.front()->setVisible(false);
3503 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
3506 Draw a "shutting down" screen, which will be shown while the map
3507 generator and other stuff quits
3510 wchar_t* text = wgettext("Shutting down stuff...");
3511 draw_load_screen(text, device, guienv, font, 0, -1, false);
3515 chat_backend.addMessage(L"", L"# Disconnected.");
3516 chat_backend.addMessage(L"", L"");
3520 //force answer all texture and shader jobs (TODO return empty values)
3522 while(!client.isShutdown()) {
3523 tsrc->processQueue();
3524 shsrc->processQueue();
3528 // Client scope (client is destructed before destructing *def and tsrc)
3531 catch(SerializationError &e)
3533 error_message = L"A serialization error occurred:\n"
3534 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3535 L" running a different version of Minetest.";
3536 errorstream<<wide_to_narrow(error_message)<<std::endl;
3538 catch(ServerError &e) {
3539 error_message = narrow_to_wide(e.what());
3540 errorstream << "ServerError: " << e.what() << std::endl;
3542 catch(ModError &e) {
3543 errorstream << "ModError: " << e.what() << std::endl;
3544 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3552 //has to be deleted first to stop all server threads
3560 //extended resource accounting
3561 infostream << "Irrlicht resources after cleanup:" << std::endl;
3562 infostream << "\tRemaining meshes : "
3563 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3564 infostream << "\tRemaining textures : "
3565 << driver->getTextureCount() << std::endl;
3566 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3567 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3568 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3571 clearTextureNameCache();
3572 infostream << "\tRemaining materials: "
3573 << driver-> getMaterialRendererCount ()
3574 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;