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 "guiKeyChangeMenu.h"
34 #include "guiFormSpecMenu.h"
36 #include "guiChatConsole.h"
40 #include "particles.h"
45 #include "mainmenumanager.h"
49 // Needed for determining pointing to nodes
51 #include "nodemetadata.h"
52 #include "main.h" // For g_settings
54 #include "tile.h" // For TextureSource
55 #include "shader.h" // For ShaderSource
56 #include "logoutputbuffer.h"
58 #include "quicktune_shortcutter.h"
59 #include "clientmap.h"
64 #include "sound_openal.h"
66 #include "event_manager.h"
69 #include "util/directiontables.h"
70 #include "util/pointedthing.h"
71 #include "drawscene.h"
72 #include "content_cao.h"
74 #ifdef HAVE_TOUCHSCREENGUI
75 #include "touchscreengui.h"
82 struct TextDestNodeMetadata : public TextDest
84 TextDestNodeMetadata(v3s16 p, Client *client)
89 // This is deprecated I guess? -celeron55
90 void gotText(std::wstring text)
92 std::string ntext = wide_to_narrow(text);
93 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
94 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
95 std::map<std::string, std::string> fields;
96 fields["text"] = ntext;
97 m_client->sendNodemetaFields(m_p, "", fields);
99 void gotText(std::map<std::string, std::string> fields)
101 m_client->sendNodemetaFields(m_p, "", fields);
108 struct TextDestPlayerInventory : public TextDest
110 TextDestPlayerInventory(Client *client)
115 TextDestPlayerInventory(Client *client, std::string formname)
118 m_formname = formname;
120 void gotText(std::map<std::string, std::string> fields)
122 m_client->sendInventoryFields(m_formname, fields);
128 struct LocalFormspecHandler : public TextDest
130 LocalFormspecHandler();
131 LocalFormspecHandler(std::string formname) :
134 m_formname = formname;
137 LocalFormspecHandler(std::string formname, Client *client) :
140 m_formname = formname;
143 void gotText(std::wstring message) {
144 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
147 void gotText(std::map<std::string, std::string> fields)
149 if (m_formname == "MT_PAUSE_MENU") {
150 if (fields.find("btn_sound") != fields.end()) {
151 g_gamecallback->changeVolume();
155 if (fields.find("btn_key_config") != fields.end()) {
156 g_gamecallback->keyConfig();
160 if (fields.find("btn_exit_menu") != fields.end()) {
161 g_gamecallback->disconnect();
165 if (fields.find("btn_exit_os") != fields.end()) {
166 g_gamecallback->exitToOS();
170 if (fields.find("btn_change_password") != fields.end()) {
171 g_gamecallback->changePassword();
175 if (fields.find("quit") != fields.end()) {
179 if (fields.find("btn_continue") != fields.end()) {
183 if (m_formname == "MT_CHAT_MENU") {
184 assert(m_client != 0);
185 if ((fields.find("btn_send") != fields.end()) ||
186 (fields.find("quit") != fields.end())) {
187 if (fields.find("f_text") != fields.end()) {
188 m_client->typeChatMessage(narrow_to_wide(fields["f_text"]));
194 if (m_formname == "MT_DEATH_SCREEN") {
195 assert(m_client != 0);
196 if ((fields.find("btn_respawn") != fields.end())) {
197 m_client->sendRespawn();
201 if (fields.find("quit") != fields.end()) {
202 m_client->sendRespawn();
207 // don't show error message for unhandled cursor keys
208 if ( (fields.find("key_up") != fields.end()) ||
209 (fields.find("key_down") != fields.end()) ||
210 (fields.find("key_left") != fields.end()) ||
211 (fields.find("key_right") != fields.end())) {
215 errorstream << "LocalFormspecHandler::gotText unhandled >" << m_formname << "< event" << std::endl;
217 for (std::map<std::string,std::string>::iterator iter = fields.begin();
218 iter != fields.end(); iter++) {
219 errorstream << "\t"<< i << ": " << iter->first << "=" << iter->second << std::endl;
227 /* Form update callback */
229 class NodeMetadataFormSource: public IFormSource
232 NodeMetadataFormSource(ClientMap *map, v3s16 p):
237 std::string getForm()
239 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
242 return meta->getString("formspec");
244 std::string resolveText(std::string str)
246 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
249 return meta->resolveString(str);
256 class PlayerInventoryFormSource: public IFormSource
259 PlayerInventoryFormSource(Client *client):
263 std::string getForm()
265 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
266 return player->inventory_formspec;
273 Check if a node is pointable
275 inline bool isPointableNode(const MapNode& n,
276 Client *client, bool liquids_pointable)
278 const ContentFeatures &features = client->getNodeDefManager()->get(n);
279 return features.pointable ||
280 (liquids_pointable && features.isLiquid());
284 Find what the player is pointing at
286 PointedThing getPointedThing(Client *client, v3f player_position,
287 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
288 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
289 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
293 hilightboxes.clear();
294 selected_object = NULL;
296 INodeDefManager *nodedef = client->getNodeDefManager();
297 ClientMap &map = client->getEnv().getClientMap();
299 f32 mindistance = BS * 1001;
301 // First try to find a pointed at active object
304 selected_object = client->getSelectedActiveObject(d*BS,
305 camera_position, shootline);
307 if(selected_object != NULL)
309 if(selected_object->doShowSelectionBox())
311 aabb3f *selection_box = selected_object->getSelectionBox();
312 // Box should exist because object was
313 // returned in the first place
314 assert(selection_box);
316 v3f pos = selected_object->getPosition();
317 hilightboxes.push_back(aabb3f(
318 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
319 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
322 mindistance = (selected_object->getPosition() - camera_position).getLength();
324 result.type = POINTEDTHING_OBJECT;
325 result.object_id = selected_object->getId();
329 // That didn't work, try to find a pointed at node
332 v3s16 pos_i = floatToInt(player_position, BS);
334 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
338 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
339 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
340 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
341 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
342 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
343 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
345 // Prevent signed number overflow
353 for(s16 y = ystart; y <= yend; y++)
354 for(s16 z = zstart; z <= zend; z++)
355 for(s16 x = xstart; x <= xend; x++)
360 n = map.getNode(v3s16(x,y,z));
362 catch(InvalidPositionException &e)
366 if(!isPointableNode(n, client, liquids_pointable))
369 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
372 v3f npf = intToFloat(np, BS);
374 for(std::vector<aabb3f>::const_iterator
376 i != boxes.end(); i++)
382 for(u16 j=0; j<6; j++)
384 v3s16 facedir = g_6dirs[j];
385 aabb3f facebox = box;
389 facebox.MinEdge.X = facebox.MaxEdge.X-d;
390 else if(facedir.X < 0)
391 facebox.MaxEdge.X = facebox.MinEdge.X+d;
392 else if(facedir.Y > 0)
393 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
394 else if(facedir.Y < 0)
395 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
396 else if(facedir.Z > 0)
397 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
398 else if(facedir.Z < 0)
399 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
401 v3f centerpoint = facebox.getCenter();
402 f32 distance = (centerpoint - camera_position).getLength();
403 if(distance >= mindistance)
405 if(!facebox.intersectsWithLine(shootline))
408 v3s16 np_above = np + facedir;
410 result.type = POINTEDTHING_NODE;
411 result.node_undersurface = np;
412 result.node_abovesurface = np_above;
413 mindistance = distance;
415 hilightboxes.clear();
416 if (!g_settings->getBool("enable_node_highlighting")) {
417 for(std::vector<aabb3f>::const_iterator
419 i2 != boxes.end(); i2++)
422 box.MinEdge += npf + v3f(-d,-d,-d) - intToFloat(camera_offset, BS);
423 box.MaxEdge += npf + v3f(d,d,d) - intToFloat(camera_offset, BS);
424 hilightboxes.push_back(box);
434 /* Profiler display */
436 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
437 gui::IGUIFont *font, u32 text_height, u32 show_profiler,
438 u32 show_profiler_max)
440 if(show_profiler == 0)
442 guitext_profiler->setVisible(false);
447 std::ostringstream os(std::ios_base::binary);
448 g_profiler->printPage(os, show_profiler, show_profiler_max);
449 std::wstring text = narrow_to_wide(os.str());
450 guitext_profiler->setText(text.c_str());
451 guitext_profiler->setVisible(true);
453 s32 w = font->getDimension(text.c_str()).Width;
456 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
457 8+(text_height+5)*2 +
458 font->getDimension(text.c_str()).Height);
459 guitext_profiler->setRelativePosition(rect);
460 guitext_profiler->setVisible(true);
468 Profiler::GraphValues values;
474 Meta(float initial=0, video::SColor color=
475 video::SColor(255,255,255,255)):
481 std::list<Piece> m_log;
489 void put(const Profiler::GraphValues &values)
492 piece.values = values;
493 m_log.push_back(piece);
494 while(m_log.size() > m_log_max_size)
495 m_log.erase(m_log.begin());
498 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
499 gui::IGUIFont* font) const
501 std::map<std::string, Meta> m_meta;
502 for(std::list<Piece>::const_iterator k = m_log.begin();
503 k != m_log.end(); k++)
505 const Piece &piece = *k;
506 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
507 i != piece.values.end(); i++){
508 const std::string &id = i->first;
509 const float &value = i->second;
510 std::map<std::string, Meta>::iterator j =
512 if(j == m_meta.end()){
513 m_meta[id] = Meta(value);
516 if(value < j->second.min)
517 j->second.min = value;
518 if(value > j->second.max)
519 j->second.max = value;
524 static const video::SColor usable_colors[] = {
525 video::SColor(255,255,100,100),
526 video::SColor(255,90,225,90),
527 video::SColor(255,100,100,255),
528 video::SColor(255,255,150,50),
529 video::SColor(255,220,220,100)
531 static const u32 usable_colors_count =
532 sizeof(usable_colors) / sizeof(*usable_colors);
533 u32 next_color_i = 0;
534 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
535 i != m_meta.end(); i++){
536 Meta &meta = i->second;
537 video::SColor color(255,200,200,200);
538 if(next_color_i < usable_colors_count)
539 color = usable_colors[next_color_i++];
544 s32 textx = x_left + m_log_max_size + 15;
545 s32 textx2 = textx + 200 - 15;
549 u32 num_graphs = m_meta.size();
550 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
552 video::SColor bgcolor(120,0,0,0);
553 driver->draw2DRectangle(bgcolor, rect, NULL);
557 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
558 i != m_meta.end(); i++){
559 const std::string &id = i->first;
560 const Meta &meta = i->second;
562 s32 y = y_bottom - meta_i * 50;
563 float show_min = meta.min;
564 float show_max = meta.max;
565 if(show_min >= -0.0001 && show_max >= -0.0001){
566 if(show_min <= show_max * 0.5)
571 snprintf(buf, 10, "%.3g", show_max);
572 font->draw(narrow_to_wide(buf).c_str(),
573 core::rect<s32>(textx, y - graphh,
574 textx2, y - graphh + texth),
576 snprintf(buf, 10, "%.3g", show_min);
577 font->draw(narrow_to_wide(buf).c_str(),
578 core::rect<s32>(textx, y - texth,
581 font->draw(narrow_to_wide(id).c_str(),
582 core::rect<s32>(textx, y - graphh/2 - texth/2,
583 textx2, y - graphh/2 + texth/2),
586 s32 graph1h = graphh;
587 bool relativegraph = (show_min != 0 && show_min != show_max);
588 float lastscaledvalue = 0.0;
589 bool lastscaledvalue_exists = false;
590 for(std::list<Piece>::const_iterator j = m_log.begin();
591 j != m_log.end(); j++)
593 const Piece &piece = *j;
595 bool value_exists = false;
596 Profiler::GraphValues::const_iterator k =
597 piece.values.find(id);
598 if(k != piece.values.end()){
604 lastscaledvalue_exists = false;
607 float scaledvalue = 1.0;
608 if(show_max != show_min)
609 scaledvalue = (value - show_min) / (show_max - show_min);
610 if(scaledvalue == 1.0 && value == 0){
612 lastscaledvalue_exists = false;
616 if(lastscaledvalue_exists){
617 s32 ivalue1 = lastscaledvalue * graph1h;
618 s32 ivalue2 = scaledvalue * graph1h;
619 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
620 v2s32(x, graph1y - ivalue2), meta.color);
622 lastscaledvalue = scaledvalue;
623 lastscaledvalue_exists = true;
625 s32 ivalue = scaledvalue * graph1h;
626 driver->draw2DLine(v2s32(x, graph1y),
627 v2s32(x, graph1y - ivalue), meta.color);
636 class NodeDugEvent: public MtEvent
642 NodeDugEvent(v3s16 p, MapNode n):
646 const char* getType() const
652 ISoundManager *m_sound;
653 INodeDefManager *m_ndef;
655 float m_player_step_timer;
657 SimpleSoundSpec m_player_step_sound;
658 SimpleSoundSpec m_player_leftpunch_sound;
659 SimpleSoundSpec m_player_rightpunch_sound;
661 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
664 m_player_step_timer(0)
668 void playPlayerStep()
670 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
671 m_player_step_timer = 0.03;
672 m_sound->playSound(m_player_step_sound, false);
676 static void viewBobbingStep(MtEvent *e, void *data)
678 SoundMaker *sm = (SoundMaker*)data;
679 sm->playPlayerStep();
682 static void playerRegainGround(MtEvent *e, void *data)
684 SoundMaker *sm = (SoundMaker*)data;
685 sm->playPlayerStep();
688 static void playerJump(MtEvent *e, void *data)
690 //SoundMaker *sm = (SoundMaker*)data;
693 static void cameraPunchLeft(MtEvent *e, void *data)
695 SoundMaker *sm = (SoundMaker*)data;
696 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
699 static void cameraPunchRight(MtEvent *e, void *data)
701 SoundMaker *sm = (SoundMaker*)data;
702 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
705 static void nodeDug(MtEvent *e, void *data)
707 SoundMaker *sm = (SoundMaker*)data;
708 NodeDugEvent *nde = (NodeDugEvent*)e;
709 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
712 static void playerDamage(MtEvent *e, void *data)
714 SoundMaker *sm = (SoundMaker*)data;
715 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
718 static void playerFallingDamage(MtEvent *e, void *data)
720 SoundMaker *sm = (SoundMaker*)data;
721 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
724 void registerReceiver(MtEventManager *mgr)
726 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
727 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
728 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
729 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
730 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
731 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
732 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
733 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
736 void step(float dtime)
738 m_player_step_timer -= dtime;
742 // Locally stored sounds don't need to be preloaded because of this
743 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
745 std::set<std::string> m_fetched;
748 void fetchSounds(const std::string &name,
749 std::set<std::string> &dst_paths,
750 std::set<std::string> &dst_datas)
752 if(m_fetched.count(name))
754 m_fetched.insert(name);
755 std::string base = porting::path_share + DIR_DELIM + "testsounds";
756 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
757 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
758 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
759 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
760 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
761 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
762 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
763 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
764 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
765 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
766 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
770 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
773 bool *m_force_fog_off;
778 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
779 f32 *fog_range, Client *client):
781 m_force_fog_off(force_fog_off),
782 m_fog_range(fog_range),
785 ~GameGlobalShaderConstantSetter() {}
787 virtual void onSetConstants(video::IMaterialRendererServices *services,
794 video::SColor bgcolor = m_sky->getBgColor();
795 video::SColorf bgcolorf(bgcolor);
796 float bgcolorfa[4] = {
802 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
805 float fog_distance = 10000*BS;
806 if(g_settings->getBool("enable_fog") && !*m_force_fog_off)
807 fog_distance = *m_fog_range;
808 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
811 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
812 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
813 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
815 u32 animation_timer = porting::getTimeMs() % 100000;
816 float animation_timer_f = (float)animation_timer / 100000.0;
817 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
818 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
820 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
821 v3f eye_position = player->getEyePosition();
822 services->setPixelShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
823 services->setVertexShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
825 // Uniform sampler layers
829 // before 1.8 there isn't a "integer interface", only float
830 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
831 services->setPixelShaderConstant("baseTexture" , (irr::f32*)&layer0, 1);
832 services->setPixelShaderConstant("normalTexture" , (irr::f32*)&layer1, 1);
833 services->setPixelShaderConstant("useNormalmap" , (irr::f32*)&layer2, 1);
835 services->setPixelShaderConstant("baseTexture" , (irr::s32*)&layer0, 1);
836 services->setPixelShaderConstant("normalTexture" , (irr::s32*)&layer1, 1);
837 services->setPixelShaderConstant("useNormalmap" , (irr::s32*)&layer2, 1);
842 bool nodePlacementPrediction(Client &client,
843 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
845 std::string prediction = playeritem_def.node_placement_prediction;
846 INodeDefManager *nodedef = client.ndef();
847 ClientMap &map = client.getEnv().getClientMap();
849 if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
851 verbosestream<<"Node placement prediction for "
852 <<playeritem_def.name<<" is "
853 <<prediction<<std::endl;
854 v3s16 p = neighbourpos;
855 // Place inside node itself if buildable_to
857 MapNode n_under = map.getNode(nodepos);
858 if(nodedef->get(n_under).buildable_to)
860 else if (!nodedef->get(map.getNode(p)).buildable_to)
862 }catch(InvalidPositionException &e){}
863 // Find id of predicted node
865 bool found = nodedef->getId(prediction, id);
867 errorstream<<"Node placement prediction failed for "
868 <<playeritem_def.name<<" (places "
870 <<") - Name not known"<<std::endl;
873 // Predict param2 for facedir and wallmounted nodes
875 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
876 v3s16 dir = nodepos - neighbourpos;
877 if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
878 param2 = dir.Y < 0 ? 1 : 0;
879 } else if(abs(dir.X) > abs(dir.Z)){
880 param2 = dir.X < 0 ? 3 : 2;
882 param2 = dir.Z < 0 ? 5 : 4;
885 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
886 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
887 if(abs(dir.X) > abs(dir.Z)){
888 param2 = dir.X < 0 ? 3 : 1;
890 param2 = dir.Z < 0 ? 2 : 0;
893 assert(param2 >= 0 && param2 <= 5);
894 //Check attachment if node is in group attached_node
895 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
896 static v3s16 wallmounted_dirs[8] = {
905 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
906 pp = p + wallmounted_dirs[param2];
908 pp = p + v3s16(0,-1,0);
909 if(!nodedef->get(map.getNode(pp)).walkable)
912 // Add node to client map
913 MapNode n(id, 0, param2);
915 LocalPlayer* player = client.getEnv().getLocalPlayer();
917 // Dont place node when player would be inside new node
918 // NOTE: This is to be eventually implemented by a mod as client-side Lua
919 if (!nodedef->get(n).walkable ||
920 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
921 (nodedef->get(n).walkable &&
922 neighbourpos != player->getStandingNodePos() + v3s16(0,1,0) &&
923 neighbourpos != player->getStandingNodePos() + v3s16(0,2,0))) {
925 // This triggers the required mesh update too
926 client.addNode(p, n);
929 }catch(InvalidPositionException &e){
930 errorstream<<"Node placement prediction failed for "
931 <<playeritem_def.name<<" (places "
933 <<") - Position not loaded"<<std::endl;
939 static inline void create_formspec_menu(GUIFormSpecMenu** cur_formspec,
940 InventoryManager *invmgr, IGameDef *gamedef,
941 IWritableTextureSource* tsrc, IrrlichtDevice * device,
942 IFormSource* fs_src, TextDest* txt_dest, Client* client
945 if (*cur_formspec == 0) {
946 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
947 invmgr, gamedef, tsrc, fs_src, txt_dest, cur_formspec, client);
948 (*cur_formspec)->doPause = false;
949 (*cur_formspec)->drop();
952 (*cur_formspec)->setFormSource(fs_src);
953 (*cur_formspec)->setTextDest(txt_dest);
958 #define SIZE_TAG "size[11,5.5]"
960 #define SIZE_TAG "size[11,5.5,true]"
963 static void show_chat_menu(GUIFormSpecMenu** cur_formspec,
964 InventoryManager *invmgr, IGameDef *gamedef,
965 IWritableTextureSource* tsrc, IrrlichtDevice * device,
966 Client* client, std::string text)
968 std::string formspec =
969 FORMSPEC_VERSION_STRING
971 "field[3,2.35;6,0.5;f_text;;" + text + "]"
972 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
976 /* Note: FormspecFormSource and LocalFormspecHandler
977 * are deleted by guiFormSpecMenu */
978 FormspecFormSource* fs_src = new FormspecFormSource(formspec);
979 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
981 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
984 static void show_deathscreen(GUIFormSpecMenu** cur_formspec,
985 InventoryManager *invmgr, IGameDef *gamedef,
986 IWritableTextureSource* tsrc, IrrlichtDevice * device, Client* client)
988 std::string formspec =
989 std::string(FORMSPEC_VERSION_STRING) +
991 "bgcolor[#320000b4;true]"
992 "label[4.85,1.35;You died.]"
993 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
997 /* Note: FormspecFormSource and LocalFormspecHandler
998 * are deleted by guiFormSpecMenu */
999 FormspecFormSource* fs_src = new FormspecFormSource(formspec);
1000 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1002 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1005 /******************************************************************************/
1006 static void show_pause_menu(GUIFormSpecMenu** cur_formspec,
1007 InventoryManager *invmgr, IGameDef *gamedef,
1008 IWritableTextureSource* tsrc, IrrlichtDevice * device,
1009 bool singleplayermode)
1012 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1013 "No menu visible:\n"
1014 "- single tap: button activate\n"
1015 "- double tap: place/use\n"
1016 "- slide finger: look around\n"
1017 "Menu/Inventory visible:\n"
1018 "- double tap (outside):\n"
1020 "- touch stack, touch slot:\n"
1022 "- touch&drag, tap 2nd finger\n"
1023 " --> place single item to slot\n"
1026 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1028 "- Space: jump/climb\n"
1029 "- Shift: sneak/go down\n"
1032 "- Mouse: turn/look\n"
1033 "- Mouse left: dig/punch\n"
1034 "- Mouse right: place/use\n"
1035 "- Mouse wheel: select item\n"
1039 float ypos = singleplayermode ? 1.0 : 0.5;
1040 std::ostringstream os;
1042 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1043 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1044 << wide_to_narrow(wstrgettext("Continue")) << "]";
1046 if (!singleplayermode) {
1047 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1048 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1051 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1052 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1053 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1054 << wide_to_narrow(wstrgettext("Change Keys")) << "]";
1055 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1056 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1057 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1058 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1059 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1060 << "textarea[0.4,0.25;3.5,6;;" << "Minetest\n"
1061 << minetest_build_info << "\n"
1062 << "path_user = " << wrap_rows(porting::path_user, 20)
1066 /* Note: FormspecFormSource and LocalFormspecHandler *
1067 * are deleted by guiFormSpecMenu */
1068 FormspecFormSource* fs_src = new FormspecFormSource(os.str());
1069 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1071 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1073 (*cur_formspec)->doPause = true;
1076 /******************************************************************************/
1077 static void updateChat(Client& client, f32 dtime, bool show_debug,
1078 const v2u32& screensize, bool show_chat, u32 show_profiler,
1079 ChatBackend& chat_backend, gui::IGUIStaticText* guitext_chat,
1080 gui::IGUIFont* font)
1082 // Add chat log output for errors to be shown in chat
1083 static LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1085 // Get new messages from error log buffer
1086 while(!chat_log_error_buf.empty()) {
1087 chat_backend.addMessage(L"", narrow_to_wide(chat_log_error_buf.get()));
1090 // Get new messages from client
1091 std::wstring message;
1092 while (client.getChatMessage(message)) {
1093 chat_backend.addUnparsedMessage(message);
1096 // Remove old messages
1097 chat_backend.step(dtime);
1099 // Display all messages in a static text element
1100 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1101 std::wstring recent_chat = chat_backend.getRecentChat();
1103 // TODO replace by fontengine fcts
1104 unsigned int line_height = font->getDimension(L"Ay").Height + font->getKerningHeight();
1106 guitext_chat->setText(recent_chat.c_str());
1108 // Update gui element size and position
1109 s32 chat_y = 5 + line_height;
1111 chat_y += line_height;
1113 // first pass to calculate height of text to be set
1114 s32 width = std::min(font->getDimension(recent_chat.c_str()).Width + 10,
1115 porting::getWindowSize().X - 20);
1116 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1117 guitext_chat->setRelativePosition(rect);
1119 //now use real height of text and adjust rect according to this size
1120 rect = core::rect<s32>(10, chat_y, width,
1121 chat_y + guitext_chat->getTextHeight());
1124 guitext_chat->setRelativePosition(rect);
1125 // Don't show chat if disabled or empty or profiler is enabled
1126 guitext_chat->setVisible(
1127 show_chat && recent_chat_count != 0 && !show_profiler);
1130 /******************************************************************************/
1131 void the_game(bool &kill, bool random_input, InputHandler *input,
1132 IrrlichtDevice *device, gui::IGUIFont* font, std::string map_dir,
1133 std::string playername, std::string password,
1134 std::string address /* If "", local server is used */,
1135 u16 port, std::wstring &error_message, ChatBackend &chat_backend,
1136 const SubgameSpec &gamespec /* Used for local game */,
1137 bool simple_singleplayer_mode)
1139 GUIFormSpecMenu* current_formspec = 0;
1140 video::IVideoDriver* driver = device->getVideoDriver();
1141 scene::ISceneManager* smgr = device->getSceneManager();
1143 // Calculate text height using the font
1144 u32 text_height = font->getDimension(L"Random test string").Height;
1147 Draw "Loading" screen
1151 wchar_t* text = wgettext("Loading...");
1152 draw_load_screen(text, device, guienv, font, 0, 0);
1156 // Create texture source
1157 IWritableTextureSource *tsrc = createTextureSource(device);
1159 // Create shader source
1160 IWritableShaderSource *shsrc = createShaderSource(device);
1162 // These will be filled by data received from the server
1163 // Create item definition manager
1164 IWritableItemDefManager *itemdef = createItemDefManager();
1165 // Create node definition manager
1166 IWritableNodeDefManager *nodedef = createNodeDefManager();
1168 // Sound fetcher (useful when testing)
1169 GameOnDemandSoundFetcher soundfetcher;
1172 ISoundManager *sound = NULL;
1173 bool sound_is_dummy = false;
1175 if(g_settings->getBool("enable_sound")){
1176 infostream<<"Attempting to use OpenAL audio"<<std::endl;
1177 sound = createOpenALSoundManager(&soundfetcher);
1179 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
1181 infostream<<"Sound disabled."<<std::endl;
1185 infostream<<"Using dummy audio."<<std::endl;
1186 sound = &dummySoundManager;
1187 sound_is_dummy = true;
1190 Server *server = NULL;
1194 EventManager eventmgr;
1197 SoundMaker soundmaker(sound, nodedef);
1198 soundmaker.registerReceiver(&eventmgr);
1200 // Create UI for modifying quicktune values
1201 QuicktuneShortcutter quicktune;
1208 wchar_t* text = wgettext("Creating server....");
1209 draw_load_screen(text, device, guienv, font, 0, 25);
1211 infostream<<"Creating server"<<std::endl;
1213 std::string bind_str = g_settings->get("bind_address");
1214 Address bind_addr(0,0,0,0, port);
1216 if (g_settings->getBool("ipv6_server")) {
1217 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1220 bind_addr.Resolve(bind_str.c_str());
1222 } catch (ResolveError &e) {
1223 infostream << "Resolving bind address \"" << bind_str
1224 << "\" failed: " << e.what()
1225 << " -- Listening on all addresses." << std::endl;
1228 if(bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1229 error_message = L"Unable to listen on " +
1230 narrow_to_wide(bind_addr.serializeString()) +
1231 L" because IPv6 is disabled";
1232 errorstream<<wide_to_narrow(error_message)<<std::endl;
1233 // Break out of client scope
1237 server = new Server(map_dir, gamespec,
1238 simple_singleplayer_mode,
1239 bind_addr.isIPv6());
1241 server->start(bind_addr);
1244 do{ // Client scope (breakable do-while(0))
1251 wchar_t* text = wgettext("Creating client...");
1252 draw_load_screen(text, device, guienv, font, 0, 50);
1255 infostream<<"Creating client"<<std::endl;
1257 MapDrawControl draw_control;
1260 wchar_t* text = wgettext("Resolving address...");
1261 draw_load_screen(text, device, guienv, font, 0, 75);
1264 Address connect_address(0,0,0,0, port);
1266 connect_address.Resolve(address.c_str());
1267 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1268 //connect_address.Resolve("localhost");
1269 if (connect_address.isIPv6()) {
1270 IPv6AddressBytes addr_bytes;
1271 addr_bytes.bytes[15] = 1;
1272 connect_address.setAddress(&addr_bytes);
1274 connect_address.setAddress(127,0,0,1);
1278 catch(ResolveError &e) {
1279 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1280 errorstream<<wide_to_narrow(error_message)<<std::endl;
1281 // Break out of client scope
1284 if(connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1285 error_message = L"Unable to connect to " +
1286 narrow_to_wide(connect_address.serializeString()) +
1287 L" because IPv6 is disabled";
1288 errorstream<<wide_to_narrow(error_message)<<std::endl;
1289 // Break out of client scope
1296 Client client(device, playername.c_str(), password, draw_control,
1297 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1298 connect_address.isIPv6());
1300 // Client acts as our GameDef
1301 IGameDef *gamedef = &client;
1304 Attempt to connect to the server
1307 infostream<<"Connecting to server at ";
1308 connect_address.print(&infostream);
1309 infostream<<std::endl;
1310 client.connect(connect_address);
1313 Wait for server to accept connection
1315 bool could_connect = false;
1316 bool connect_aborted = false;
1318 float time_counter = 0.0;
1320 float fps_max = g_settings->getFloat("fps_max");
1321 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1322 u32 lasttime = device->getTimer()->getTime();
1323 while(device->run())
1325 f32 dtime = 0.033; // in seconds
1326 if (cloud_menu_background) {
1327 u32 time = device->getTimer()->getTime();
1329 dtime = (time - lasttime) / 1000.0;
1334 // Update client and server
1337 server->step(dtime);
1340 if(client.getState() == LC_Init) {
1341 could_connect = true;
1345 if(client.accessDenied()) {
1346 error_message = L"Access denied. Reason: "
1347 +client.accessDeniedReason();
1348 errorstream<<wide_to_narrow(error_message)<<std::endl;
1351 if(input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
1352 connect_aborted = true;
1353 infostream<<"Connect aborted [Escape]"<<std::endl;
1359 wchar_t* text = wgettext("Connecting to server...");
1360 draw_load_screen(text, device, guienv, font, dtime, 100);
1364 // On some computers framerate doesn't seem to be
1365 // automatically limited
1366 if (cloud_menu_background) {
1367 // Time of frame without fps limit
1370 // not using getRealTime is necessary for wine
1371 u32 time = device->getTimer()->getTime();
1373 busytime_u32 = time - lasttime;
1376 busytime = busytime_u32 / 1000.0;
1379 u32 frametime_min = 1000./fps_max;
1381 if(busytime_u32 < frametime_min) {
1382 u32 sleeptime = frametime_min - busytime_u32;
1383 device->sleep(sleeptime);
1388 time_counter += dtime;
1391 catch(con::PeerNotFoundException &e)
1395 Handle failure to connect
1397 if(!could_connect) {
1398 if(error_message == L"" && !connect_aborted) {
1399 error_message = L"Connection failed";
1400 errorstream<<wide_to_narrow(error_message)<<std::endl;
1402 // Break out of client scope
1407 Wait until content has been received
1409 bool got_content = false;
1410 bool content_aborted = false;
1412 float time_counter = 0.0;
1414 float fps_max = g_settings->getFloat("fps_max");
1415 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1416 u32 lasttime = device->getTimer()->getTime();
1417 while (device->run()) {
1418 f32 dtime = 0.033; // in seconds
1419 if (cloud_menu_background) {
1420 u32 time = device->getTimer()->getTime();
1422 dtime = (time - lasttime) / 1000.0;
1427 // Update client and server
1430 server->step(dtime);
1433 if (client.mediaReceived() &&
1434 client.itemdefReceived() &&
1435 client.nodedefReceived()) {
1440 if (client.accessDenied()) {
1441 error_message = L"Access denied. Reason: "
1442 +client.accessDeniedReason();
1443 errorstream<<wide_to_narrow(error_message)<<std::endl;
1446 if (client.getState() < LC_Init) {
1447 error_message = L"Client disconnected";
1448 errorstream<<wide_to_narrow(error_message)<<std::endl;
1451 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
1452 content_aborted = true;
1453 infostream<<"Connect aborted [Escape]"<<std::endl;
1459 if (!client.itemdefReceived())
1461 wchar_t* text = wgettext("Item definitions...");
1463 draw_load_screen(text, device, guienv, font, dtime, progress);
1466 else if (!client.nodedefReceived())
1468 wchar_t* text = wgettext("Node definitions...");
1470 draw_load_screen(text, device, guienv, font, dtime, progress);
1476 std::stringstream message;
1477 message.precision(3);
1478 message << gettext("Media...");
1480 if ( ( USE_CURL == 0) ||
1481 (!g_settings->getBool("enable_remote_media_server"))) {
1482 float cur = client.getCurRate();
1483 std::string cur_unit = gettext(" KB/s");
1487 cur_unit = gettext(" MB/s");
1489 message << " ( " << cur << cur_unit << " )";
1491 progress = 50+client.mediaReceiveProgress()*50+0.5;
1492 draw_load_screen(narrow_to_wide(message.str().c_str()), device,
1493 guienv, font, dtime, progress);
1496 // On some computers framerate doesn't seem to be
1497 // automatically limited
1498 if (cloud_menu_background) {
1499 // Time of frame without fps limit
1502 // not using getRealTime is necessary for wine
1503 u32 time = device->getTimer()->getTime();
1505 busytime_u32 = time - lasttime;
1508 busytime = busytime_u32 / 1000.0;
1511 u32 frametime_min = 1000./fps_max;
1513 if(busytime_u32 < frametime_min) {
1514 u32 sleeptime = frametime_min - busytime_u32;
1515 device->sleep(sleeptime);
1520 time_counter += dtime;
1525 if(error_message == L"" && !content_aborted){
1526 error_message = L"Something failed";
1527 errorstream<<wide_to_narrow(error_message)<<std::endl;
1529 // Break out of client scope
1534 After all content has been received:
1535 Update cached textures, meshes and materials
1537 client.afterContentReceived(device,font);
1540 Create the camera node
1542 Camera camera(smgr, draw_control, gamedef);
1543 if (!camera.successfullyCreated(error_message))
1546 f32 camera_yaw = 0; // "right/left"
1547 f32 camera_pitch = 0; // "up/down"
1553 Clouds *clouds = NULL;
1554 if(g_settings->getBool("enable_clouds"))
1556 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1564 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1566 scene::ISceneNode* skybox = NULL;
1569 A copy of the local inventory
1571 Inventory local_inventory(itemdef);
1574 Find out size of crack animation
1576 int crack_animation_length = 5;
1578 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1579 v2u32 size = t->getOriginalSize();
1580 crack_animation_length = size.Y / size.X;
1587 // First line of debug text
1588 gui::IGUIStaticText *guitext = guienv->addStaticText(
1590 core::rect<s32>(0, 0, 0, 0),
1591 false, false, guiroot);
1592 // Second line of debug text
1593 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1595 core::rect<s32>(0, 0, 0, 0),
1596 false, false, guiroot);
1597 // At the middle of the screen
1598 // Object infos are shown in this
1599 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1601 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1602 false, true, guiroot);
1604 // Status text (displays info when showing and hiding GUI stuff, etc.)
1605 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1607 core::rect<s32>(0,0,0,0),
1608 false, false, guiroot);
1609 guitext_status->setVisible(false);
1611 std::wstring statustext;
1612 float statustext_time = 0;
1615 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1617 core::rect<s32>(0,0,0,0),
1618 //false, false); // Disable word wrap as of now
1619 false, true, guiroot);
1620 // Remove stale "recent" chat messages from previous connections
1621 chat_backend.clearRecentChat();
1622 // Chat backend and console
1623 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1625 // Profiler text (size is updated when text is updated)
1626 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1628 core::rect<s32>(0,0,0,0),
1629 false, false, guiroot);
1630 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1631 guitext_profiler->setVisible(false);
1632 guitext_profiler->setWordWrap(true);
1634 #ifdef HAVE_TOUCHSCREENGUI
1635 if (g_touchscreengui)
1636 g_touchscreengui->init(tsrc,porting::getDisplayDensity());
1640 Some statistics are collected in these
1643 u32 beginscenetime = 0;
1644 u32 endscenetime = 0;
1646 float recent_turn_speed = 0.0;
1648 ProfilerGraph graph;
1649 // Initially clear the profiler
1650 Profiler::GraphValues dummyvalues;
1651 g_profiler->graphGet(dummyvalues);
1653 float nodig_delay_timer = 0.0;
1654 float dig_time = 0.0;
1656 PointedThing pointed_old;
1657 bool digging = false;
1658 bool ldown_for_dig = false;
1660 float damage_flash = 0;
1662 float jump_timer = 0;
1663 bool reset_jump_timer = false;
1665 const float object_hit_delay = 0.2;
1666 float object_hit_delay_timer = 0.0;
1667 float time_from_last_punch = 10;
1669 float update_draw_list_timer = 0.0;
1670 v3f update_draw_list_last_cam_dir;
1672 bool invert_mouse = g_settings->getBool("invert_mouse");
1674 bool update_wielded_item_trigger = true;
1676 bool show_hud = true;
1677 bool show_chat = true;
1678 bool force_fog_off = false;
1679 f32 fog_range = 100*BS;
1680 bool disable_camera_update = false;
1681 bool show_debug = g_settings->getBool("show_debug");
1682 bool show_profiler_graph = false;
1683 u32 show_profiler = 0;
1684 u32 show_profiler_max = 3; // Number of pages
1686 float time_of_day = 0;
1687 float time_of_day_smooth = 0;
1689 float repeat_rightclick_timer = 0;
1694 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1695 sky, &force_fog_off, &fog_range, &client));
1701 bool first_loop_after_window_activation = true;
1703 // TODO: Convert the static interval timers to these
1704 // Interval limiter for profiler
1705 IntervalLimiter m_profiler_interval;
1707 // Time is in milliseconds
1708 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1709 // NOTE: So we have to use getTime() and call run()s between them
1710 u32 lasttime = device->getTimer()->getTime();
1712 LocalPlayer* player = client.getEnv().getLocalPlayer();
1713 player->hurt_tilt_timer = 0;
1714 player->hurt_tilt_strength = 0;
1719 Hud hud(driver, smgr, guienv, font, text_height,
1720 gamedef, player, &local_inventory);
1722 core::stringw str = L"Minetest [";
1723 str += driver->getName();
1725 device->setWindowCaption(str.c_str());
1728 std::wstring infotext;
1732 if(device->run() == false || kill == true ||
1733 g_gamecallback->shutdown_requested)
1736 v2u32 screensize = driver->getScreenSize();
1738 // Time of frame without fps limit
1742 // not using getRealTime is necessary for wine
1743 u32 time = device->getTimer()->getTime();
1745 busytime_u32 = time - lasttime;
1748 busytime = busytime_u32 / 1000.0;
1751 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1753 // Necessary for device->getTimer()->getTime()
1761 float fps_max = g_menumgr.pausesGame() ?
1762 g_settings->getFloat("pause_fps_max") :
1763 g_settings->getFloat("fps_max");
1764 u32 frametime_min = 1000./fps_max;
1766 if(busytime_u32 < frametime_min)
1768 u32 sleeptime = frametime_min - busytime_u32;
1769 device->sleep(sleeptime);
1770 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1774 // Necessary for device->getTimer()->getTime()
1778 Time difference calculation
1780 f32 dtime; // in seconds
1782 u32 time = device->getTimer()->getTime();
1784 dtime = (time - lasttime) / 1000.0;
1789 g_profiler->graphAdd("mainloop_dtime", dtime);
1793 if(nodig_delay_timer >= 0)
1794 nodig_delay_timer -= dtime;
1795 if(object_hit_delay_timer >= 0)
1796 object_hit_delay_timer -= dtime;
1797 time_from_last_punch += dtime;
1799 g_profiler->add("Elapsed time", dtime);
1800 g_profiler->avg("FPS", 1./dtime);
1803 Time average and jitter calculation
1806 static f32 dtime_avg1 = 0.0;
1807 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1808 f32 dtime_jitter1 = dtime - dtime_avg1;
1810 static f32 dtime_jitter1_max_sample = 0.0;
1811 static f32 dtime_jitter1_max_fraction = 0.0;
1813 static f32 jitter1_max = 0.0;
1814 static f32 counter = 0.0;
1815 if(dtime_jitter1 > jitter1_max)
1816 jitter1_max = dtime_jitter1;
1821 dtime_jitter1_max_sample = jitter1_max;
1822 dtime_jitter1_max_fraction
1823 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1829 Busytime average and jitter calculation
1832 static f32 busytime_avg1 = 0.0;
1833 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1834 f32 busytime_jitter1 = busytime - busytime_avg1;
1836 static f32 busytime_jitter1_max_sample = 0.0;
1837 static f32 busytime_jitter1_min_sample = 0.0;
1839 static f32 jitter1_max = 0.0;
1840 static f32 jitter1_min = 0.0;
1841 static f32 counter = 0.0;
1842 if(busytime_jitter1 > jitter1_max)
1843 jitter1_max = busytime_jitter1;
1844 if(busytime_jitter1 < jitter1_min)
1845 jitter1_min = busytime_jitter1;
1849 busytime_jitter1_max_sample = jitter1_max;
1850 busytime_jitter1_min_sample = jitter1_min;
1857 Handle miscellaneous stuff
1860 if(client.accessDenied())
1862 error_message = L"Access denied. Reason: "
1863 +client.accessDeniedReason();
1864 errorstream<<wide_to_narrow(error_message)<<std::endl;
1868 if(g_gamecallback->disconnect_requested)
1870 g_gamecallback->disconnect_requested = false;
1874 if(g_gamecallback->changepassword_requested)
1876 (new GUIPasswordChange(guienv, guiroot, -1,
1877 &g_menumgr, &client))->drop();
1878 g_gamecallback->changepassword_requested = false;
1881 if(g_gamecallback->changevolume_requested)
1883 (new GUIVolumeChange(guienv, guiroot, -1,
1884 &g_menumgr, &client))->drop();
1885 g_gamecallback->changevolume_requested = false;
1888 if(g_gamecallback->keyconfig_requested)
1890 (new GUIKeyChangeMenu(guienv, guiroot, -1,
1891 &g_menumgr))->drop();
1892 g_gamecallback->keyconfig_requested = false;
1896 /* Process TextureSource's queue */
1897 tsrc->processQueue();
1899 /* Process ItemDefManager's queue */
1900 itemdef->processQueue(gamedef);
1903 Process ShaderSource's queue
1905 shsrc->processQueue();
1912 // Hilight boxes collected during the loop and displayed
1913 std::vector<aabb3f> hilightboxes;
1915 /* reset infotext */
1920 float profiler_print_interval =
1921 g_settings->getFloat("profiler_print_interval");
1922 bool print_to_log = true;
1923 if(profiler_print_interval == 0){
1924 print_to_log = false;
1925 profiler_print_interval = 5;
1927 if(m_profiler_interval.step(dtime, profiler_print_interval))
1930 infostream<<"Profiler:"<<std::endl;
1931 g_profiler->print(infostream);
1934 update_profiler_gui(guitext_profiler, font, text_height,
1935 show_profiler, show_profiler_max);
1937 g_profiler->clear();
1941 Direct handling of user input
1944 // Reset input if window not active or some menu is active
1945 if(device->isWindowActive() == false
1946 || noMenuActive() == false
1947 || guienv->hasFocus(gui_chat_console))
1951 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1953 gui_chat_console->closeConsoleAtOnce();
1956 // Input handler step() (used by the random input generator)
1958 #ifdef HAVE_TOUCHSCREENGUI
1959 if (g_touchscreengui) {
1960 g_touchscreengui->step(dtime);
1964 if (current_formspec != 0)
1965 current_formspec->getAndroidUIInput();
1968 // Increase timer for doubleclick of "jump"
1969 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1970 jump_timer += dtime;
1973 Launch menus and trigger stuff according to keys
1975 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1977 // drop selected item
1978 IDropAction *a = new IDropAction();
1980 a->from_inv.setCurrentPlayer();
1981 a->from_list = "main";
1982 a->from_i = client.getPlayerItem();
1983 client.inventoryAction(a);
1985 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1987 infostream<<"the_game: "
1988 <<"Launching inventory"<<std::endl;
1990 PlayerInventoryFormSource* fs_src = new PlayerInventoryFormSource(&client);
1991 TextDest* txt_dst = new TextDestPlayerInventory(&client);
1993 create_formspec_menu(¤t_formspec, &client, gamedef, tsrc, device, fs_src, txt_dst, &client);
1995 InventoryLocation inventoryloc;
1996 inventoryloc.setCurrentPlayer();
1997 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
1999 else if(input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey))
2001 show_pause_menu(¤t_formspec, &client, gamedef, tsrc, device,
2002 simple_singleplayer_mode);
2004 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
2006 show_chat_menu(¤t_formspec, &client, gamedef, tsrc, device,
2009 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
2011 show_chat_menu(¤t_formspec, &client, gamedef, tsrc, device,
2014 else if(input->wasKeyDown(getKeySetting("keymap_console")))
2016 if (!gui_chat_console->isOpenInhibited())
2018 // Open up to over half of the screen
2019 gui_chat_console->openConsole(0.6);
2020 guienv->setFocus(gui_chat_console);
2023 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
2025 if(g_settings->getBool("free_move"))
2027 g_settings->set("free_move","false");
2028 statustext = L"free_move disabled";
2029 statustext_time = 0;
2033 g_settings->set("free_move","true");
2034 statustext = L"free_move enabled";
2035 statustext_time = 0;
2036 if(!client.checkPrivilege("fly"))
2037 statustext += L" (note: no 'fly' privilege)";
2040 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
2042 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
2044 if(g_settings->getBool("free_move"))
2046 g_settings->set("free_move","false");
2047 statustext = L"free_move disabled";
2048 statustext_time = 0;
2052 g_settings->set("free_move","true");
2053 statustext = L"free_move enabled";
2054 statustext_time = 0;
2055 if(!client.checkPrivilege("fly"))
2056 statustext += L" (note: no 'fly' privilege)";
2059 reset_jump_timer = true;
2061 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
2063 if(g_settings->getBool("fast_move"))
2065 g_settings->set("fast_move","false");
2066 statustext = L"fast_move disabled";
2067 statustext_time = 0;
2071 g_settings->set("fast_move","true");
2072 statustext = L"fast_move enabled";
2073 statustext_time = 0;
2074 if(!client.checkPrivilege("fast"))
2075 statustext += L" (note: no 'fast' privilege)";
2078 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
2080 if(g_settings->getBool("noclip"))
2082 g_settings->set("noclip","false");
2083 statustext = L"noclip disabled";
2084 statustext_time = 0;
2088 g_settings->set("noclip","true");
2089 statustext = L"noclip enabled";
2090 statustext_time = 0;
2091 if(!client.checkPrivilege("noclip"))
2092 statustext += L" (note: no 'noclip' privilege)";
2095 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
2097 client.makeScreenshot(device);
2099 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
2101 show_hud = !show_hud;
2103 statustext = L"HUD shown";
2104 client.setHighlighted(client.getHighlighted(), true);
2106 statustext = L"HUD hidden";
2107 client.setHighlighted(client.getHighlighted(), false);
2109 statustext_time = 0;
2111 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
2113 show_chat = !show_chat;
2115 statustext = L"Chat shown";
2117 statustext = L"Chat hidden";
2118 statustext_time = 0;
2120 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
2122 force_fog_off = !force_fog_off;
2124 statustext = L"Fog disabled";
2126 statustext = L"Fog enabled";
2127 statustext_time = 0;
2129 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
2131 disable_camera_update = !disable_camera_update;
2132 if(disable_camera_update)
2133 statustext = L"Camera update disabled";
2135 statustext = L"Camera update enabled";
2136 statustext_time = 0;
2138 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
2140 // Initial / 3x toggle: Chat only
2141 // 1x toggle: Debug text with chat
2142 // 2x toggle: Debug text with profiler graph
2146 show_profiler_graph = false;
2147 statustext = L"Debug info shown";
2148 statustext_time = 0;
2150 else if(show_profiler_graph)
2153 show_profiler_graph = false;
2154 statustext = L"Debug info and profiler graph hidden";
2155 statustext_time = 0;
2159 show_profiler_graph = true;
2160 statustext = L"Profiler graph shown";
2161 statustext_time = 0;
2164 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
2166 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
2168 // FIXME: This updates the profiler with incomplete values
2169 update_profiler_gui(guitext_profiler, font, text_height,
2170 show_profiler, show_profiler_max);
2172 if(show_profiler != 0)
2174 std::wstringstream sstr;
2175 sstr<<"Profiler shown (page "<<show_profiler
2176 <<" of "<<show_profiler_max<<")";
2177 statustext = sstr.str();
2178 statustext_time = 0;
2182 statustext = L"Profiler hidden";
2183 statustext_time = 0;
2186 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
2188 s16 range = g_settings->getS16("viewing_range_nodes_min");
2189 s16 range_new = range + 10;
2190 g_settings->set("viewing_range_nodes_min", itos(range_new));
2191 statustext = narrow_to_wide(
2192 "Minimum viewing range changed to "
2194 statustext_time = 0;
2196 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
2198 s16 range = g_settings->getS16("viewing_range_nodes_min");
2199 s16 range_new = range - 10;
2202 g_settings->set("viewing_range_nodes_min",
2204 statustext = narrow_to_wide(
2205 "Minimum viewing range changed to "
2207 statustext_time = 0;
2211 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
2213 reset_jump_timer = false;
2217 // Handle QuicktuneShortcutter
2218 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2220 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2222 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2224 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2227 std::string msg = quicktune.getMessage();
2229 statustext = narrow_to_wide(msg);
2230 statustext_time = 0;
2234 // Item selection with mouse wheel
2235 u16 new_playeritem = client.getPlayerItem();
2237 s32 wheel = input->getMouseWheel();
2238 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2239 player->hud_hotbar_itemcount-1);
2243 if(new_playeritem < max_item)
2250 if(new_playeritem > 0)
2253 new_playeritem = max_item;
2258 for(u16 i=0; i<10; i++)
2260 const KeyPress *kp = NumberKey + (i + 1) % 10;
2261 if(input->wasKeyDown(*kp))
2263 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2267 infostream<<"Selected item: "
2268 <<new_playeritem<<std::endl;
2273 // Viewing range selection
2274 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2276 draw_control.range_all = !draw_control.range_all;
2277 if(draw_control.range_all)
2279 infostream<<"Enabled full viewing range"<<std::endl;
2280 statustext = L"Enabled full viewing range";
2281 statustext_time = 0;
2285 infostream<<"Disabled full viewing range"<<std::endl;
2286 statustext = L"Disabled full viewing range";
2287 statustext_time = 0;
2291 // Print debug stacks
2292 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2294 dstream<<"-----------------------------------------"
2296 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2297 dstream<<"-----------------------------------------"
2299 debug_stacks_print();
2303 Mouse and camera control
2304 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2307 float turn_amount = 0;
2308 if((device->isWindowActive() && noMenuActive()) || random_input)
2313 // Mac OSX gets upset if this is set every frame
2314 if(device->getCursorControl()->isVisible())
2315 device->getCursorControl()->setVisible(false);
2319 if(first_loop_after_window_activation){
2320 //infostream<<"window active, first loop"<<std::endl;
2321 first_loop_after_window_activation = false;
2323 #ifdef HAVE_TOUCHSCREENGUI
2324 if (g_touchscreengui) {
2325 camera_yaw = g_touchscreengui->getYaw();
2326 camera_pitch = g_touchscreengui->getPitch();
2329 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width/2);
2330 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height/2);
2332 || (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)) {
2335 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2337 /*const float keyspeed = 500;
2338 if(input->isKeyDown(irr::KEY_UP))
2339 dy -= dtime * keyspeed;
2340 if(input->isKeyDown(irr::KEY_DOWN))
2341 dy += dtime * keyspeed;
2342 if(input->isKeyDown(irr::KEY_LEFT))
2343 dx -= dtime * keyspeed;
2344 if(input->isKeyDown(irr::KEY_RIGHT))
2345 dx += dtime * keyspeed;*/
2347 float d = g_settings->getFloat("mouse_sensitivity");
2348 d = rangelim(d, 0.01, 100.0);
2350 camera_pitch += dy*d;
2351 turn_amount = v2f(dx, dy).getLength() * d;
2353 #ifdef HAVE_TOUCHSCREENGUI
2356 if(camera_pitch < -89.5) camera_pitch = -89.5;
2357 if(camera_pitch > 89.5) camera_pitch = 89.5;
2359 input->setMousePos((driver->getScreenSize().Width/2),
2360 (driver->getScreenSize().Height/2));
2364 // Mac OSX gets upset if this is set every frame
2365 if(device->getCursorControl()->isVisible() == false)
2366 device->getCursorControl()->setVisible(true);
2369 //infostream<<"window inactive"<<std::endl;
2370 first_loop_after_window_activation = true;
2372 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2373 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2376 Player speed control
2390 PlayerControl control(
2391 input->isKeyDown(getKeySetting("keymap_forward")),
2392 input->isKeyDown(getKeySetting("keymap_backward")),
2393 input->isKeyDown(getKeySetting("keymap_left")),
2394 input->isKeyDown(getKeySetting("keymap_right")),
2395 input->isKeyDown(getKeySetting("keymap_jump")),
2396 input->isKeyDown(getKeySetting("keymap_special1")),
2397 input->isKeyDown(getKeySetting("keymap_sneak")),
2398 input->getLeftState(),
2399 input->getRightState(),
2403 client.setPlayerControl(control);
2404 LocalPlayer* player = client.getEnv().getLocalPlayer();
2406 (((int)input->isKeyDown(getKeySetting("keymap_forward")) & 0x1) << 0) |
2407 (((int)input->isKeyDown(getKeySetting("keymap_backward")) & 0x1) << 1) |
2408 (((int)input->isKeyDown(getKeySetting("keymap_left")) & 0x1) << 2) |
2409 (((int)input->isKeyDown(getKeySetting("keymap_right")) & 0x1) << 3) |
2410 (((int)input->isKeyDown(getKeySetting("keymap_jump")) & 0x1) << 4) |
2411 (((int)input->isKeyDown(getKeySetting("keymap_special1")) & 0x1) << 5) |
2412 (((int)input->isKeyDown(getKeySetting("keymap_sneak")) & 0x1) << 6) |
2413 (((int)input->getLeftState() & 0x1) << 7) |
2414 (((int)input->getRightState() & 0x1) << 8);
2418 Run server, client (and process environments)
2420 bool can_be_and_is_paused =
2421 (simple_singleplayer_mode && g_menumgr.pausesGame());
2422 if(can_be_and_is_paused)
2431 //TimeTaker timer("server->step(dtime)");
2432 server->step(dtime);
2435 //TimeTaker timer("client.step(dtime)");
2441 // Read client events
2443 ClientEvent event = client.getClientEvent();
2444 if(event.type == CE_NONE) {
2447 else if(event.type == CE_PLAYER_DAMAGE &&
2448 client.getHP() != 0) {
2449 //u16 damage = event.player_damage.amount;
2450 //infostream<<"Player damage: "<<damage<<std::endl;
2452 damage_flash += 100.0;
2453 damage_flash += 8.0 * event.player_damage.amount;
2455 player->hurt_tilt_timer = 1.5;
2456 player->hurt_tilt_strength = event.player_damage.amount/4;
2457 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
2459 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2460 gamedef->event()->put(e);
2462 else if(event.type == CE_PLAYER_FORCE_MOVE) {
2463 camera_yaw = event.player_force_move.yaw;
2464 camera_pitch = event.player_force_move.pitch;
2466 else if(event.type == CE_DEATHSCREEN) {
2467 show_deathscreen(¤t_formspec, &client, gamedef, tsrc,
2470 chat_backend.addMessage(L"", L"You died.");
2472 /* Handle visualization */
2475 LocalPlayer* player = client.getEnv().getLocalPlayer();
2476 player->hurt_tilt_timer = 0;
2477 player->hurt_tilt_strength = 0;
2480 else if (event.type == CE_SHOW_FORMSPEC) {
2481 FormspecFormSource* fs_src =
2482 new FormspecFormSource(*(event.show_formspec.formspec));
2483 TextDestPlayerInventory* txt_dst =
2484 new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2486 create_formspec_menu(¤t_formspec, &client, gamedef,
2487 tsrc, device, fs_src, txt_dst, &client);
2489 delete(event.show_formspec.formspec);
2490 delete(event.show_formspec.formname);
2492 else if(event.type == CE_SPAWN_PARTICLE) {
2493 LocalPlayer* player = client.getEnv().getLocalPlayer();
2494 video::ITexture *texture =
2495 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2497 new Particle(gamedef, smgr, player, client.getEnv(),
2498 *event.spawn_particle.pos,
2499 *event.spawn_particle.vel,
2500 *event.spawn_particle.acc,
2501 event.spawn_particle.expirationtime,
2502 event.spawn_particle.size,
2503 event.spawn_particle.collisiondetection,
2504 event.spawn_particle.vertical,
2509 else if(event.type == CE_ADD_PARTICLESPAWNER) {
2510 LocalPlayer* player = client.getEnv().getLocalPlayer();
2511 video::ITexture *texture =
2512 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2514 new ParticleSpawner(gamedef, smgr, player,
2515 event.add_particlespawner.amount,
2516 event.add_particlespawner.spawntime,
2517 *event.add_particlespawner.minpos,
2518 *event.add_particlespawner.maxpos,
2519 *event.add_particlespawner.minvel,
2520 *event.add_particlespawner.maxvel,
2521 *event.add_particlespawner.minacc,
2522 *event.add_particlespawner.maxacc,
2523 event.add_particlespawner.minexptime,
2524 event.add_particlespawner.maxexptime,
2525 event.add_particlespawner.minsize,
2526 event.add_particlespawner.maxsize,
2527 event.add_particlespawner.collisiondetection,
2528 event.add_particlespawner.vertical,
2530 event.add_particlespawner.id);
2532 else if(event.type == CE_DELETE_PARTICLESPAWNER) {
2533 delete_particlespawner (event.delete_particlespawner.id);
2535 else if (event.type == CE_HUDADD) {
2536 u32 id = event.hudadd.id;
2538 HudElement *e = player->getHud(id);
2541 delete event.hudadd.pos;
2542 delete event.hudadd.name;
2543 delete event.hudadd.scale;
2544 delete event.hudadd.text;
2545 delete event.hudadd.align;
2546 delete event.hudadd.offset;
2547 delete event.hudadd.world_pos;
2548 delete event.hudadd.size;
2553 e->type = (HudElementType)event.hudadd.type;
2554 e->pos = *event.hudadd.pos;
2555 e->name = *event.hudadd.name;
2556 e->scale = *event.hudadd.scale;
2557 e->text = *event.hudadd.text;
2558 e->number = event.hudadd.number;
2559 e->item = event.hudadd.item;
2560 e->dir = event.hudadd.dir;
2561 e->align = *event.hudadd.align;
2562 e->offset = *event.hudadd.offset;
2563 e->world_pos = *event.hudadd.world_pos;
2564 e->size = *event.hudadd.size;
2566 u32 new_id = player->addHud(e);
2567 //if this isn't true our huds aren't consistent
2568 assert(new_id == id);
2570 delete event.hudadd.pos;
2571 delete event.hudadd.name;
2572 delete event.hudadd.scale;
2573 delete event.hudadd.text;
2574 delete event.hudadd.align;
2575 delete event.hudadd.offset;
2576 delete event.hudadd.world_pos;
2577 delete event.hudadd.size;
2579 else if (event.type == CE_HUDRM) {
2580 HudElement* e = player->removeHud(event.hudrm.id);
2585 else if (event.type == CE_HUDCHANGE) {
2586 u32 id = event.hudchange.id;
2587 HudElement* e = player->getHud(id);
2590 delete event.hudchange.v3fdata;
2591 delete event.hudchange.v2fdata;
2592 delete event.hudchange.sdata;
2593 delete event.hudchange.v2s32data;
2597 switch (event.hudchange.stat) {
2599 e->pos = *event.hudchange.v2fdata;
2602 e->name = *event.hudchange.sdata;
2604 case HUD_STAT_SCALE:
2605 e->scale = *event.hudchange.v2fdata;
2608 e->text = *event.hudchange.sdata;
2610 case HUD_STAT_NUMBER:
2611 e->number = event.hudchange.data;
2614 e->item = event.hudchange.data;
2617 e->dir = event.hudchange.data;
2619 case HUD_STAT_ALIGN:
2620 e->align = *event.hudchange.v2fdata;
2622 case HUD_STAT_OFFSET:
2623 e->offset = *event.hudchange.v2fdata;
2625 case HUD_STAT_WORLD_POS:
2626 e->world_pos = *event.hudchange.v3fdata;
2629 e->size = *event.hudchange.v2s32data;
2633 delete event.hudchange.v3fdata;
2634 delete event.hudchange.v2fdata;
2635 delete event.hudchange.sdata;
2636 delete event.hudchange.v2s32data;
2638 else if (event.type == CE_SET_SKY) {
2639 sky->setVisible(false);
2644 // Handle according to type
2645 if(*event.set_sky.type == "regular") {
2646 sky->setVisible(true);
2648 else if(*event.set_sky.type == "skybox" &&
2649 event.set_sky.params->size() == 6) {
2650 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2651 skybox = smgr->addSkyBoxSceneNode(
2652 tsrc->getTexture((*event.set_sky.params)[0]),
2653 tsrc->getTexture((*event.set_sky.params)[1]),
2654 tsrc->getTexture((*event.set_sky.params)[2]),
2655 tsrc->getTexture((*event.set_sky.params)[3]),
2656 tsrc->getTexture((*event.set_sky.params)[4]),
2657 tsrc->getTexture((*event.set_sky.params)[5]));
2659 // Handle everything else as plain color
2661 if(*event.set_sky.type != "plain")
2662 infostream<<"Unknown sky type: "
2663 <<(*event.set_sky.type)<<std::endl;
2664 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2667 delete event.set_sky.bgcolor;
2668 delete event.set_sky.type;
2669 delete event.set_sky.params;
2671 else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
2672 bool enable = event.override_day_night_ratio.do_override;
2673 u32 value = event.override_day_night_ratio.ratio_f * 1000;
2674 client.getEnv().setDayNightRatioOverride(enable, value);
2679 //TimeTaker //timer2("//timer2");
2682 For interaction purposes, get info about the held item
2684 - Is it a usable item?
2685 - Can it point to liquids?
2687 ItemStack playeritem;
2689 InventoryList *mlist = local_inventory.getList("main");
2690 if((mlist != NULL) && (client.getPlayerItem() < mlist->getSize()))
2691 playeritem = mlist->getItem(client.getPlayerItem());
2693 const ItemDefinition &playeritem_def =
2694 playeritem.getDefinition(itemdef);
2695 ToolCapabilities playeritem_toolcap =
2696 playeritem.getToolCapabilities(itemdef);
2702 v3s16 old_camera_offset = camera.getOffset();
2704 LocalPlayer* player = client.getEnv().getLocalPlayer();
2705 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2706 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2708 if(input->wasKeyDown(getKeySetting("keymap_camera_mode"))) {
2709 camera.toggleCameraMode();
2710 GenericCAO* playercao = player->getCAO();
2712 assert( playercao != NULL );
2713 if (camera.getCameraMode() > CAMERA_MODE_FIRST) {
2714 playercao->setVisible(true);
2717 playercao->setVisible(false);
2720 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2721 camera.update(player, dtime, busytime, tool_reload_ratio,
2725 v3f player_position = player->getPosition();
2726 v3f camera_position = camera.getPosition();
2727 v3f camera_direction = camera.getDirection();
2728 f32 camera_fov = camera.getFovMax();
2729 v3s16 camera_offset = camera.getOffset();
2731 bool camera_offset_changed = (camera_offset != old_camera_offset);
2733 if(!disable_camera_update){
2734 client.getEnv().getClientMap().updateCamera(camera_position,
2735 camera_direction, camera_fov, camera_offset);
2736 if (camera_offset_changed){
2737 client.updateCameraOffset(camera_offset);
2738 client.getEnv().updateCameraOffset(camera_offset);
2740 clouds->updateCameraOffset(camera_offset);
2744 // Update sound listener
2745 sound->updateListener(camera.getCameraNode()->getPosition()+intToFloat(camera_offset, BS),
2746 v3f(0,0,0), // velocity
2747 camera.getDirection(),
2748 camera.getCameraNode()->getUpVector());
2749 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2755 soundmaker.step(dtime);
2757 ClientMap &map = client.getEnv().getClientMap();
2758 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2759 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2763 Calculate what block is the crosshair pointing to
2766 //u32 t1 = device->getTimer()->getRealTime();
2768 f32 d = playeritem_def.range; // max. distance
2769 f32 d_hand = itemdef->get("").range;
2770 if(d < 0 && d_hand >= 0)
2774 core::line3d<f32> shootline(camera_position,
2775 camera_position + camera_direction * BS * (d+1));
2778 // prevent player pointing anything in front-view
2779 if (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)
2780 shootline = core::line3d<f32>(0,0,0,0,0,0);
2782 #ifdef HAVE_TOUCHSCREENGUI
2783 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
2784 shootline = g_touchscreengui->getShootline();
2785 shootline.start += intToFloat(camera_offset,BS);
2786 shootline.end += intToFloat(camera_offset,BS);
2790 ClientActiveObject *selected_object = NULL;
2792 PointedThing pointed = getPointedThing(
2794 &client, player_position, camera_direction,
2795 camera_position, shootline, d,
2796 playeritem_def.liquids_pointable, !ldown_for_dig,
2802 if(pointed != pointed_old)
2804 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2805 if (g_settings->getBool("enable_node_highlighting")) {
2806 if (pointed.type == POINTEDTHING_NODE) {
2807 client.setHighlighted(pointed.node_undersurface, show_hud);
2809 client.setHighlighted(pointed.node_undersurface, false);
2816 - releasing left mouse button
2817 - pointing away from node
2821 if(input->getLeftReleased())
2823 infostream<<"Left button released"
2824 <<" (stopped digging)"<<std::endl;
2827 else if(pointed != pointed_old)
2829 if (pointed.type == POINTEDTHING_NODE
2830 && pointed_old.type == POINTEDTHING_NODE
2831 && pointed.node_undersurface == pointed_old.node_undersurface)
2833 // Still pointing to the same node,
2834 // but a different face. Don't reset.
2838 infostream<<"Pointing away from node"
2839 <<" (stopped digging)"<<std::endl;
2845 client.interact(1, pointed_old);
2846 client.setCrack(-1, v3s16(0,0,0));
2850 if(!digging && ldown_for_dig && !input->getLeftState())
2852 ldown_for_dig = false;
2855 bool left_punch = false;
2856 soundmaker.m_player_leftpunch_sound.name = "";
2858 if(input->getRightState())
2859 repeat_rightclick_timer += dtime;
2861 repeat_rightclick_timer = 0;
2863 if(playeritem_def.usable && input->getLeftState())
2865 if(input->getLeftClicked())
2866 client.interact(4, pointed);
2868 else if(pointed.type == POINTEDTHING_NODE)
2870 v3s16 nodepos = pointed.node_undersurface;
2871 v3s16 neighbourpos = pointed.node_abovesurface;
2874 Check information text of node
2877 ClientMap &map = client.getEnv().getClientMap();
2878 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2880 infotext = narrow_to_wide(meta->getString("infotext"));
2882 MapNode n = map.getNode(nodepos);
2883 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2884 infotext = L"Unknown node: ";
2885 infotext += narrow_to_wide(nodedef->get(n).name);
2893 if(nodig_delay_timer <= 0.0 && input->getLeftState()
2894 && client.checkPrivilege("interact"))
2898 infostream<<"Started digging"<<std::endl;
2899 client.interact(0, pointed);
2901 ldown_for_dig = true;
2903 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2905 // NOTE: Similar piece of code exists on the server side for
2907 // Get digging parameters
2908 DigParams params = getDigParams(nodedef->get(n).groups,
2909 &playeritem_toolcap);
2910 // If can't dig, try hand
2911 if(!params.diggable){
2912 const ItemDefinition &hand = itemdef->get("");
2913 const ToolCapabilities *tp = hand.tool_capabilities;
2915 params = getDigParams(nodedef->get(n).groups, tp);
2918 float dig_time_complete = 0.0;
2920 if(params.diggable == false)
2922 // I guess nobody will wait for this long
2923 dig_time_complete = 10000000.0;
2927 dig_time_complete = params.time;
2928 if (g_settings->getBool("enable_particles"))
2930 const ContentFeatures &features =
2931 client.getNodeDefManager()->get(n);
2932 addPunchingParticles
2933 (gamedef, smgr, player, client.getEnv(),
2934 nodepos, features.tiles);
2938 if(dig_time_complete >= 0.001)
2940 dig_index = (u16)((float)crack_animation_length
2941 * dig_time/dig_time_complete);
2943 // This is for torches
2946 dig_index = crack_animation_length;
2949 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2950 if(sound_dig.exists() && params.diggable){
2951 if(sound_dig.name == "__group"){
2952 if(params.main_group != ""){
2953 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2954 soundmaker.m_player_leftpunch_sound.name =
2955 std::string("default_dig_") +
2959 soundmaker.m_player_leftpunch_sound = sound_dig;
2963 // Don't show cracks if not diggable
2964 if(dig_time_complete >= 100000.0)
2967 else if(dig_index < crack_animation_length)
2969 //TimeTaker timer("client.setTempMod");
2970 //infostream<<"dig_index="<<dig_index<<std::endl;
2971 client.setCrack(dig_index, nodepos);
2975 infostream<<"Digging completed"<<std::endl;
2976 client.interact(2, pointed);
2977 client.setCrack(-1, v3s16(0,0,0));
2978 MapNode wasnode = map.getNode(nodepos);
2979 client.removeNode(nodepos);
2981 if (g_settings->getBool("enable_particles"))
2983 const ContentFeatures &features =
2984 client.getNodeDefManager()->get(wasnode);
2986 (gamedef, smgr, player, client.getEnv(),
2987 nodepos, features.tiles);
2993 nodig_delay_timer = dig_time_complete
2994 / (float)crack_animation_length;
2996 // We don't want a corresponding delay to
2997 // very time consuming nodes
2998 if(nodig_delay_timer > 0.3)
2999 nodig_delay_timer = 0.3;
3000 // We want a slight delay to very little
3001 // time consuming nodes
3002 float mindelay = 0.15;
3003 if(nodig_delay_timer < mindelay)
3004 nodig_delay_timer = mindelay;
3006 // Send event to trigger sound
3007 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3008 gamedef->event()->put(e);
3011 if(dig_time_complete < 100000.0)
3015 client.setCrack(-1, nodepos);
3018 camera.setDigging(0); // left click animation
3021 if((input->getRightClicked() ||
3022 repeat_rightclick_timer >=
3023 g_settings->getFloat("repeat_rightclick_time")) &&
3024 client.checkPrivilege("interact"))
3026 repeat_rightclick_timer = 0;
3027 infostream<<"Ground right-clicked"<<std::endl;
3029 if(meta && meta->getString("formspec") != "" && !random_input
3030 && !input->isKeyDown(getKeySetting("keymap_sneak")))
3032 infostream<<"Launching custom inventory view"<<std::endl;
3034 InventoryLocation inventoryloc;
3035 inventoryloc.setNodeMeta(nodepos);
3037 NodeMetadataFormSource* fs_src = new NodeMetadataFormSource(
3038 &client.getEnv().getClientMap(), nodepos);
3039 TextDest* txt_dst = new TextDestNodeMetadata(nodepos, &client);
3041 create_formspec_menu(¤t_formspec, &client, gamedef,
3042 tsrc, device, fs_src, txt_dst, &client);
3044 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3046 // Otherwise report right click to server
3049 camera.setDigging(1); // right click animation (always shown for feedback)
3051 // If the wielded item has node placement prediction,
3053 bool placed = nodePlacementPrediction(client,
3055 nodepos, neighbourpos);
3059 client.interact(3, pointed);
3061 soundmaker.m_player_rightpunch_sound =
3062 playeritem_def.sound_place;
3064 soundmaker.m_player_rightpunch_sound =
3068 if (playeritem_def.node_placement_prediction == "" ||
3069 nodedef->get(map.getNode(nodepos)).rightclickable)
3070 client.interact(3, pointed); // Report to server
3074 else if(pointed.type == POINTEDTHING_OBJECT)
3076 infotext = narrow_to_wide(selected_object->infoText());
3078 if(infotext == L"" && show_debug){
3079 infotext = narrow_to_wide(selected_object->debugInfoText());
3082 //if(input->getLeftClicked())
3083 if(input->getLeftState())
3085 bool do_punch = false;
3086 bool do_punch_damage = false;
3087 if(object_hit_delay_timer <= 0.0){
3089 do_punch_damage = true;
3090 object_hit_delay_timer = object_hit_delay;
3092 if(input->getLeftClicked()){
3096 infostream<<"Left-clicked object"<<std::endl;
3099 if(do_punch_damage){
3100 // Report direct punch
3101 v3f objpos = selected_object->getPosition();
3102 v3f dir = (objpos - player_position).normalize();
3104 bool disable_send = selected_object->directReportPunch(
3105 dir, &playeritem, time_from_last_punch);
3106 time_from_last_punch = 0;
3108 client.interact(0, pointed);
3111 else if(input->getRightClicked())
3113 infostream<<"Right-clicked object"<<std::endl;
3114 client.interact(3, pointed); // place
3117 else if(input->getLeftState())
3119 // When button is held down in air, show continuous animation
3123 pointed_old = pointed;
3125 if(left_punch || input->getLeftClicked())
3127 camera.setDigging(0); // left click animation
3130 input->resetLeftClicked();
3131 input->resetRightClicked();
3133 input->resetLeftReleased();
3134 input->resetRightReleased();
3137 Calculate stuff for drawing
3144 if(draw_control.range_all)
3145 fog_range = 100000*BS;
3147 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
3148 fog_range = MYMIN(fog_range, (draw_control.farthest_drawn+20)*BS);
3153 Calculate general brightness
3155 u32 daynight_ratio = client.getEnv().getDayNightRatio();
3156 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
3157 float direct_brightness = 0;
3158 bool sunlight_seen = false;
3159 if(g_settings->getBool("free_move")){
3160 direct_brightness = time_brightness;
3161 sunlight_seen = true;
3163 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3164 float old_brightness = sky->getBrightness();
3165 direct_brightness = (float)client.getEnv().getClientMap()
3166 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
3167 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
3171 time_of_day = client.getEnv().getTimeOfDayF();
3173 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
3174 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3175 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3176 time_of_day_smooth = time_of_day;
3178 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
3179 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3180 + (time_of_day+1.0) * todsm;
3182 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3183 + time_of_day * todsm;
3185 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3186 sunlight_seen,camera.getCameraMode(), player->getYaw(),
3187 player->getPitch());
3189 video::SColor bgcolor = sky->getBgColor();
3190 video::SColor skycolor = sky->getSkyColor();
3196 if(sky->getCloudsVisible()){
3197 clouds->setVisible(true);
3198 clouds->step(dtime);
3199 clouds->update(v2f(player_position.X, player_position.Z),
3200 sky->getCloudColor());
3202 clouds->setVisible(false);
3210 allparticles_step(dtime);
3211 allparticlespawners_step(dtime, client.getEnv());
3217 if(g_settings->getBool("enable_fog") && !force_fog_off)
3221 video::EFT_FOG_LINEAR,
3233 video::EFT_FOG_LINEAR,
3243 Update gui stuff (0ms)
3246 //TimeTaker guiupdatetimer("Gui updating");
3250 static float drawtime_avg = 0;
3251 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
3252 /*static float beginscenetime_avg = 0;
3253 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
3254 static float scenetime_avg = 0;
3255 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
3256 static float endscenetime_avg = 0;
3257 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3259 u16 fps = (1.0/dtime_avg1);
3261 std::ostringstream os(std::ios_base::binary);
3263 <<"Minetest "<<minetest_version_hash
3265 <<" (R: range_all="<<draw_control.range_all<<")"
3266 <<std::setprecision(0)
3267 <<" drawtime = "<<drawtime_avg
3268 <<std::setprecision(1)
3269 <<", dtime_jitter = "
3270 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3271 <<std::setprecision(1)
3272 <<", v_range = "<<draw_control.wanted_range
3273 <<std::setprecision(3)
3274 <<", RTT = "<<client.getRTT();
3275 guitext->setText(narrow_to_wide(os.str()).c_str());
3276 guitext->setVisible(true);
3278 else if(show_hud || show_chat)
3280 std::ostringstream os(std::ios_base::binary);
3281 os<<"Minetest "<<minetest_version_hash;
3282 guitext->setText(narrow_to_wide(os.str()).c_str());
3283 guitext->setVisible(true);
3287 guitext->setVisible(false);
3290 if (guitext->isVisible())
3292 core::rect<s32> rect(
3298 guitext->setRelativePosition(rect);
3303 std::ostringstream os(std::ios_base::binary);
3304 os<<std::setprecision(1)<<std::fixed
3305 <<"(" <<(player_position.X/BS)
3306 <<", "<<(player_position.Y/BS)
3307 <<", "<<(player_position.Z/BS)
3308 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3309 <<") (seed = "<<((u64)client.getMapSeed())
3311 guitext2->setText(narrow_to_wide(os.str()).c_str());
3312 guitext2->setVisible(true);
3314 core::rect<s32> rect(
3318 5 + (text_height * 2)
3320 guitext2->setRelativePosition(rect);
3324 guitext2->setVisible(false);
3328 guitext_info->setText(infotext.c_str());
3329 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3333 float statustext_time_max = 1.5;
3334 if(!statustext.empty())
3336 statustext_time += dtime;
3337 if(statustext_time >= statustext_time_max)
3340 statustext_time = 0;
3343 guitext_status->setText(statustext.c_str());
3344 guitext_status->setVisible(!statustext.empty());
3346 if(!statustext.empty())
3348 s32 status_y = screensize.Y - 130;
3349 core::rect<s32> rect(
3351 status_y - guitext_status->getTextHeight(),
3352 10 + guitext_status->getTextWidth(),
3355 guitext_status->setRelativePosition(rect);
3358 video::SColor initial_color(255,0,0,0);
3359 if(guienv->getSkin())
3360 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3361 video::SColor final_color = initial_color;
3362 final_color.setAlpha(0);
3363 video::SColor fade_color =
3364 initial_color.getInterpolated_quadratic(
3367 pow(statustext_time / (float)statustext_time_max, 2.0f));
3368 guitext_status->setOverrideColor(fade_color);
3369 guitext_status->enableOverrideColor(true);
3374 Get chat messages from client
3376 updateChat(client, dtime, show_debug, screensize, show_chat,
3377 show_profiler, chat_backend, guitext_chat, font);
3383 if(client.getPlayerItem() != new_playeritem)
3385 client.selectPlayerItem(new_playeritem);
3387 if(client.getLocalInventoryUpdated())
3389 //infostream<<"Updating local inventory"<<std::endl;
3390 client.getLocalInventory(local_inventory);
3392 update_wielded_item_trigger = true;
3394 if(update_wielded_item_trigger)
3396 update_wielded_item_trigger = false;
3397 // Update wielded tool
3398 InventoryList *mlist = local_inventory.getList("main");
3400 if((mlist != NULL) && (client.getPlayerItem() < mlist->getSize()))
3401 item = mlist->getItem(client.getPlayerItem());
3402 camera.wield(item, client.getPlayerItem());
3406 Update block draw list every 200ms or when camera direction has
3409 update_draw_list_timer += dtime;
3410 if(update_draw_list_timer >= 0.2 ||
3411 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2 ||
3412 camera_offset_changed){
3413 update_draw_list_timer = 0;
3414 client.getEnv().getClientMap().updateDrawList(driver);
3415 update_draw_list_last_cam_dir = camera_direction;
3419 make sure menu is on top
3421 if ((!noMenuActive()) && (current_formspec)) {
3422 guiroot->bringToFront(current_formspec);
3428 TimeTaker tt_draw("mainloop: draw");
3430 TimeTaker timer("beginScene");
3431 driver->beginScene(true, true, skycolor);
3432 beginscenetime = timer.stop(true);
3436 draw_scene(driver, smgr, camera, client, player, hud, guienv,
3437 hilightboxes, screensize, skycolor, show_hud);
3442 if(show_profiler_graph)
3444 graph.draw(10, screensize.Y - 10, driver, font);
3450 if(damage_flash > 0.0)
3452 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3453 driver->draw2DRectangle(color,
3454 core::rect<s32>(0,0,screensize.X,screensize.Y),
3457 damage_flash -= 100.0*dtime;
3463 if(player->hurt_tilt_timer > 0.0)
3465 player->hurt_tilt_timer -= dtime*5;
3466 if(player->hurt_tilt_timer < 0)
3467 player->hurt_tilt_strength = 0;
3474 TimeTaker timer("endScene");
3476 endscenetime = timer.stop(true);
3479 drawtime = tt_draw.stop(true);
3480 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3487 Log times and stuff for visualization
3489 Profiler::GraphValues values;
3490 g_profiler->graphGet(values);
3499 if (gui_chat_console)
3500 gui_chat_console->drop();
3506 while (g_menumgr.menuCount() > 0)
3508 g_menumgr.m_stack.front()->setVisible(false);
3509 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
3512 Draw a "shutting down" screen, which will be shown while the map
3513 generator and other stuff quits
3516 wchar_t* text = wgettext("Shutting down stuff...");
3517 draw_load_screen(text, device, guienv, font, 0, -1, false);
3521 chat_backend.addMessage(L"", L"# Disconnected.");
3522 chat_backend.addMessage(L"", L"");
3526 //force answer all texture and shader jobs (TODO return empty values)
3528 while(!client.isShutdown()) {
3529 tsrc->processQueue();
3530 shsrc->processQueue();
3534 // Client scope (client is destructed before destructing *def and tsrc)
3537 catch(SerializationError &e)
3539 error_message = L"A serialization error occurred:\n"
3540 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3541 L" running a different version of Minetest.";
3542 errorstream<<wide_to_narrow(error_message)<<std::endl;
3544 catch(ServerError &e) {
3545 error_message = narrow_to_wide(e.what());
3546 errorstream << "ServerError: " << e.what() << std::endl;
3548 catch(ModError &e) {
3549 errorstream << "ModError: " << e.what() << std::endl;
3550 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3558 //has to be deleted first to stop all server threads
3566 //extended resource accounting
3567 infostream << "Irrlicht resources after cleanup:" << std::endl;
3568 infostream << "\tRemaining meshes : "
3569 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3570 infostream << "\tRemaining textures : "
3571 << driver->getTextureCount() << std::endl;
3572 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3573 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3574 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3577 clearTextureNameCache();
3578 infostream << "\tRemaining materials: "
3579 << driver-> getMaterialRendererCount ()
3580 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;