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"
73 #include "fontengine.h"
75 #ifdef HAVE_TOUCHSCREENGUI
76 #include "touchscreengui.h"
83 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 {
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 {
128 LocalFormspecHandler();
129 LocalFormspecHandler(std::string formname) :
132 m_formname = formname;
135 LocalFormspecHandler(std::string formname, Client *client) :
138 m_formname = formname;
141 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_key_config") != fields.end()) {
155 g_gamecallback->keyConfig();
159 if (fields.find("btn_exit_menu") != fields.end()) {
160 g_gamecallback->disconnect();
164 if (fields.find("btn_exit_os") != fields.end()) {
165 g_gamecallback->exitToOS();
169 if (fields.find("btn_change_password") != fields.end()) {
170 g_gamecallback->changePassword();
174 if (fields.find("quit") != fields.end()) {
178 if (fields.find("btn_continue") != fields.end()) {
183 if (m_formname == "MT_CHAT_MENU") {
184 assert(m_client != 0);
186 if ((fields.find("btn_send") != fields.end()) ||
187 (fields.find("quit") != fields.end())) {
188 if (fields.find("f_text") != fields.end()) {
189 m_client->typeChatMessage(narrow_to_wide(fields["f_text"]));
196 if (m_formname == "MT_DEATH_SCREEN") {
197 assert(m_client != 0);
199 if ((fields.find("btn_respawn") != fields.end())) {
200 m_client->sendRespawn();
204 if (fields.find("quit") != fields.end()) {
205 m_client->sendRespawn();
210 // don't show error message for unhandled cursor keys
211 if ((fields.find("key_up") != fields.end()) ||
212 (fields.find("key_down") != fields.end()) ||
213 (fields.find("key_left") != fields.end()) ||
214 (fields.find("key_right") != fields.end())) {
218 errorstream << "LocalFormspecHandler::gotText unhandled >" << m_formname << "< event" << std::endl;
221 for (std::map<std::string, std::string>::iterator iter = fields.begin();
222 iter != fields.end(); iter++) {
223 errorstream << "\t" << i << ": " << iter->first << "=" << iter->second << std::endl;
231 /* Form update callback */
233 class NodeMetadataFormSource: public IFormSource
236 NodeMetadataFormSource(ClientMap *map, v3s16 p):
241 std::string getForm()
243 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
248 return meta->getString("formspec");
250 std::string resolveText(std::string str)
252 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
257 return meta->resolveString(str);
264 class PlayerInventoryFormSource: public IFormSource
267 PlayerInventoryFormSource(Client *client):
271 std::string getForm()
273 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
274 return player->inventory_formspec;
281 Check if a node is pointable
283 inline bool isPointableNode(const MapNode &n,
284 Client *client, bool liquids_pointable)
286 const ContentFeatures &features = client->getNodeDefManager()->get(n);
287 return features.pointable ||
288 (liquids_pointable && features.isLiquid());
292 Find what the player is pointing at
294 PointedThing getPointedThing(Client *client, v3f player_position,
295 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
296 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
297 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
301 hilightboxes.clear();
302 selected_object = NULL;
304 INodeDefManager *nodedef = client->getNodeDefManager();
305 ClientMap &map = client->getEnv().getClientMap();
307 f32 mindistance = BS * 1001;
309 // First try to find a pointed at active object
310 if (look_for_object) {
311 selected_object = client->getSelectedActiveObject(d * BS,
312 camera_position, shootline);
314 if (selected_object != NULL) {
315 if (selected_object->doShowSelectionBox()) {
316 aabb3f *selection_box = selected_object->getSelectionBox();
317 // Box should exist because object was
318 // returned in the first place
319 assert(selection_box);
321 v3f pos = selected_object->getPosition();
322 hilightboxes.push_back(aabb3f(
323 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
324 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
327 mindistance = (selected_object->getPosition() - camera_position).getLength();
329 result.type = POINTEDTHING_OBJECT;
330 result.object_id = selected_object->getId();
334 // That didn't work, try to find a pointed at node
337 v3s16 pos_i = floatToInt(player_position, BS);
339 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
343 s16 ystart = pos_i.Y + 0 - (camera_direction.Y < 0 ? a : 1);
344 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
345 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
346 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
347 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
348 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
350 // Prevent signed number overflow
360 for (s16 y = ystart; y <= yend; y++)
361 for (s16 z = zstart; z <= zend; z++)
362 for (s16 x = xstart; x <= xend; x++) {
364 bool is_valid_position;
366 n = map.getNodeNoEx(v3s16(x, y, z), &is_valid_position);
367 if (!is_valid_position)
370 if (!isPointableNode(n, client, liquids_pointable))
373 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
376 v3f npf = intToFloat(np, BS);
378 for (std::vector<aabb3f>::const_iterator
380 i != boxes.end(); i++) {
385 for (u16 j = 0; j < 6; j++) {
386 v3s16 facedir = g_6dirs[j];
387 aabb3f facebox = box;
392 facebox.MinEdge.X = facebox.MaxEdge.X - d;
393 else if (facedir.X < 0)
394 facebox.MaxEdge.X = facebox.MinEdge.X + d;
395 else if (facedir.Y > 0)
396 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
397 else if (facedir.Y < 0)
398 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
399 else if (facedir.Z > 0)
400 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
401 else if (facedir.Z < 0)
402 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
404 v3f centerpoint = facebox.getCenter();
405 f32 distance = (centerpoint - camera_position).getLength();
407 if (distance >= mindistance)
410 if (!facebox.intersectsWithLine(shootline))
413 v3s16 np_above = np + facedir;
415 result.type = POINTEDTHING_NODE;
416 result.node_undersurface = np;
417 result.node_abovesurface = np_above;
418 mindistance = distance;
420 hilightboxes.clear();
422 if (!g_settings->getBool("enable_node_highlighting")) {
423 for (std::vector<aabb3f>::const_iterator
425 i2 != boxes.end(); i2++) {
427 box.MinEdge += npf + v3f(-d, -d, -d) - intToFloat(camera_offset, BS);
428 box.MaxEdge += npf + v3f(d, d, d) - intToFloat(camera_offset, BS);
429 hilightboxes.push_back(box);
439 /* Profiler display */
441 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
442 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
444 if (show_profiler == 0) {
445 guitext_profiler->setVisible(false);
448 std::ostringstream os(std::ios_base::binary);
449 g_profiler->printPage(os, show_profiler, show_profiler_max);
450 std::wstring text = narrow_to_wide(os.str());
451 guitext_profiler->setText(text.c_str());
452 guitext_profiler->setVisible(true);
454 s32 w = fe->getTextWidth(text.c_str());
459 unsigned text_height = fe->getTextHeight();
461 core::position2di upper_left, lower_right;
464 upper_left.Y = (text_height + 5) * 2;
465 lower_right.X = 12 + w;
466 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
468 if (lower_right.Y > screen_height * 2 / 3)
469 lower_right.Y = screen_height * 2 / 3;
471 core::rect<s32> rect(upper_left, lower_right);
473 guitext_profiler->setRelativePosition(rect);
474 guitext_profiler->setVisible(true);
482 Profiler::GraphValues values;
488 Meta(float initial = 0,
489 video::SColor color = video::SColor(255, 255, 255, 255)):
495 std::list<Piece> m_log;
503 void put(const Profiler::GraphValues &values)
506 piece.values = values;
507 m_log.push_back(piece);
509 while (m_log.size() > m_log_max_size)
510 m_log.erase(m_log.begin());
513 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
514 gui::IGUIFont *font) const
516 std::map<std::string, Meta> m_meta;
518 for (std::list<Piece>::const_iterator k = m_log.begin();
519 k != m_log.end(); k++) {
520 const Piece &piece = *k;
522 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
523 i != piece.values.end(); i++) {
524 const std::string &id = i->first;
525 const float &value = i->second;
526 std::map<std::string, Meta>::iterator j =
529 if (j == m_meta.end()) {
530 m_meta[id] = Meta(value);
534 if (value < j->second.min)
535 j->second.min = value;
537 if (value > j->second.max)
538 j->second.max = value;
543 static const video::SColor usable_colors[] = {
544 video::SColor(255, 255, 100, 100),
545 video::SColor(255, 90, 225, 90),
546 video::SColor(255, 100, 100, 255),
547 video::SColor(255, 255, 150, 50),
548 video::SColor(255, 220, 220, 100)
550 static const u32 usable_colors_count =
551 sizeof(usable_colors) / sizeof(*usable_colors);
552 u32 next_color_i = 0;
554 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
555 i != m_meta.end(); i++) {
556 Meta &meta = i->second;
557 video::SColor color(255, 200, 200, 200);
559 if (next_color_i < usable_colors_count)
560 color = usable_colors[next_color_i++];
566 s32 textx = x_left + m_log_max_size + 15;
567 s32 textx2 = textx + 200 - 15;
571 u32 num_graphs = m_meta.size();
572 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
574 video::SColor bgcolor(120,0,0,0);
575 driver->draw2DRectangle(bgcolor, rect, NULL);
580 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
581 i != m_meta.end(); i++) {
582 const std::string &id = i->first;
583 const Meta &meta = i->second;
585 s32 y = y_bottom - meta_i * 50;
586 float show_min = meta.min;
587 float show_max = meta.max;
589 if (show_min >= -0.0001 && show_max >= -0.0001) {
590 if (show_min <= show_max * 0.5)
596 snprintf(buf, 10, "%.3g", show_max);
597 font->draw(narrow_to_wide(buf).c_str(),
598 core::rect<s32>(textx, y - graphh,
599 textx2, y - graphh + texth),
601 snprintf(buf, 10, "%.3g", show_min);
602 font->draw(narrow_to_wide(buf).c_str(),
603 core::rect<s32>(textx, y - texth,
606 font->draw(narrow_to_wide(id).c_str(),
607 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
608 textx2, y - graphh / 2 + texth / 2),
611 s32 graph1h = graphh;
612 bool relativegraph = (show_min != 0 && show_min != show_max);
613 float lastscaledvalue = 0.0;
614 bool lastscaledvalue_exists = false;
616 for (std::list<Piece>::const_iterator j = m_log.begin();
617 j != m_log.end(); j++) {
618 const Piece &piece = *j;
620 bool value_exists = false;
621 Profiler::GraphValues::const_iterator k =
622 piece.values.find(id);
624 if (k != piece.values.end()) {
631 lastscaledvalue_exists = false;
635 float scaledvalue = 1.0;
637 if (show_max != show_min)
638 scaledvalue = (value - show_min) / (show_max - show_min);
640 if (scaledvalue == 1.0 && value == 0) {
642 lastscaledvalue_exists = false;
647 if (lastscaledvalue_exists) {
648 s32 ivalue1 = lastscaledvalue * graph1h;
649 s32 ivalue2 = scaledvalue * graph1h;
650 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
651 v2s32(x, graph1y - ivalue2), meta.color);
654 lastscaledvalue = scaledvalue;
655 lastscaledvalue_exists = true;
657 s32 ivalue = scaledvalue * graph1h;
658 driver->draw2DLine(v2s32(x, graph1y),
659 v2s32(x, graph1y - ivalue), meta.color);
670 class NodeDugEvent: public MtEvent
676 NodeDugEvent(v3s16 p, MapNode n):
680 const char *getType() const
688 ISoundManager *m_sound;
689 INodeDefManager *m_ndef;
691 float m_player_step_timer;
693 SimpleSoundSpec m_player_step_sound;
694 SimpleSoundSpec m_player_leftpunch_sound;
695 SimpleSoundSpec m_player_rightpunch_sound;
697 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
700 m_player_step_timer(0)
704 void playPlayerStep()
706 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
707 m_player_step_timer = 0.03;
708 m_sound->playSound(m_player_step_sound, false);
712 static void viewBobbingStep(MtEvent *e, void *data)
714 SoundMaker *sm = (SoundMaker *)data;
715 sm->playPlayerStep();
718 static void playerRegainGround(MtEvent *e, void *data)
720 SoundMaker *sm = (SoundMaker *)data;
721 sm->playPlayerStep();
724 static void playerJump(MtEvent *e, void *data)
726 //SoundMaker *sm = (SoundMaker*)data;
729 static void cameraPunchLeft(MtEvent *e, void *data)
731 SoundMaker *sm = (SoundMaker *)data;
732 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
735 static void cameraPunchRight(MtEvent *e, void *data)
737 SoundMaker *sm = (SoundMaker *)data;
738 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
741 static void nodeDug(MtEvent *e, void *data)
743 SoundMaker *sm = (SoundMaker *)data;
744 NodeDugEvent *nde = (NodeDugEvent *)e;
745 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
748 static void playerDamage(MtEvent *e, void *data)
750 SoundMaker *sm = (SoundMaker *)data;
751 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
754 static void playerFallingDamage(MtEvent *e, void *data)
756 SoundMaker *sm = (SoundMaker *)data;
757 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
760 void registerReceiver(MtEventManager *mgr)
762 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
763 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
764 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
765 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
766 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
767 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
768 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
769 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
772 void step(float dtime)
774 m_player_step_timer -= dtime;
778 // Locally stored sounds don't need to be preloaded because of this
779 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
781 std::set<std::string> m_fetched;
783 void fetchSounds(const std::string &name,
784 std::set<std::string> &dst_paths,
785 std::set<std::string> &dst_datas)
787 if (m_fetched.count(name))
790 m_fetched.insert(name);
791 std::string base = porting::path_share + DIR_DELIM + "testsounds";
792 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
793 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
794 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
795 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
796 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
797 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
798 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
799 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
800 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
801 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
802 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
806 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
809 bool *m_force_fog_off;
814 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
815 f32 *fog_range, Client *client) :
817 m_force_fog_off(force_fog_off),
818 m_fog_range(fog_range),
821 ~GameGlobalShaderConstantSetter() {}
823 virtual void onSetConstants(video::IMaterialRendererServices *services,
830 video::SColor bgcolor = m_sky->getBgColor();
831 video::SColorf bgcolorf(bgcolor);
832 float bgcolorfa[4] = {
838 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
841 float fog_distance = 10000 * BS;
843 if (g_settings->getBool("enable_fog") && !*m_force_fog_off)
844 fog_distance = *m_fog_range;
846 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
849 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
850 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
851 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
853 u32 animation_timer = porting::getTimeMs() % 100000;
854 float animation_timer_f = (float)animation_timer / 100000.0;
855 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
856 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
858 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
859 v3f eye_position = player->getEyePosition();
860 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
861 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
863 // Uniform sampler layers
867 // before 1.8 there isn't a "integer interface", only float
868 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
869 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
870 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
871 services->setPixelShaderConstant("useNormalmap" , (irr::f32 *)&layer2, 1);
873 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
874 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
875 services->setPixelShaderConstant("useNormalmap" , (irr::s32 *)&layer2, 1);
880 bool nodePlacementPrediction(Client &client,
881 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
883 std::string prediction = playeritem_def.node_placement_prediction;
884 INodeDefManager *nodedef = client.ndef();
885 ClientMap &map = client.getEnv().getClientMap();
887 bool is_valid_position;
889 node = map.getNodeNoEx(nodepos, &is_valid_position);
890 if (!is_valid_position)
893 if (prediction != "" && !nodedef->get(node).rightclickable) {
894 verbosestream << "Node placement prediction for "
895 << playeritem_def.name << " is "
896 << prediction << std::endl;
897 v3s16 p = neighbourpos;
899 // Place inside node itself if buildable_to
900 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
901 if (is_valid_position)
903 if (nodedef->get(n_under).buildable_to)
906 node = map.getNodeNoEx(p, &is_valid_position);
907 if (is_valid_position &&!nodedef->get(node).buildable_to)
912 // Find id of predicted node
914 bool found = nodedef->getId(prediction, id);
917 errorstream << "Node placement prediction failed for "
918 << playeritem_def.name << " (places "
920 << ") - Name not known" << std::endl;
924 // Predict param2 for facedir and wallmounted nodes
927 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
928 v3s16 dir = nodepos - neighbourpos;
930 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
931 param2 = dir.Y < 0 ? 1 : 0;
932 } else if (abs(dir.X) > abs(dir.Z)) {
933 param2 = dir.X < 0 ? 3 : 2;
935 param2 = dir.Z < 0 ? 5 : 4;
939 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
940 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
942 if (abs(dir.X) > abs(dir.Z)) {
943 param2 = dir.X < 0 ? 3 : 1;
945 param2 = dir.Z < 0 ? 2 : 0;
951 //Check attachment if node is in group attached_node
952 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
953 static v3s16 wallmounted_dirs[8] = {
963 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
964 pp = p + wallmounted_dirs[param2];
966 pp = p + v3s16(0, -1, 0);
968 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
972 // Add node to client map
973 MapNode n(id, 0, param2);
976 LocalPlayer *player = client.getEnv().getLocalPlayer();
978 // Dont place node when player would be inside new node
979 // NOTE: This is to be eventually implemented by a mod as client-side Lua
980 if (!nodedef->get(n).walkable ||
981 g_settings->getBool("enable_build_where_you_stand") ||
982 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
983 (nodedef->get(n).walkable &&
984 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
985 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
987 // This triggers the required mesh update too
988 client.addNode(p, n);
991 } catch (InvalidPositionException &e) {
992 errorstream << "Node placement prediction failed for "
993 << playeritem_def.name << " (places "
995 << ") - Position not loaded" << std::endl;
1002 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1003 InventoryManager *invmgr, IGameDef *gamedef,
1004 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1005 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1008 if (*cur_formspec == 0) {
1009 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1010 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1011 (*cur_formspec)->doPause = false;
1014 Caution: do not call (*cur_formspec)->drop() here --
1015 the reference might outlive the menu, so we will
1016 periodically check if *cur_formspec is the only
1017 remaining reference (i.e. the menu was removed)
1018 and delete it in that case.
1022 (*cur_formspec)->setFormSource(fs_src);
1023 (*cur_formspec)->setTextDest(txt_dest);
1028 #define SIZE_TAG "size[11,5.5]"
1030 #define SIZE_TAG "size[11,5.5,true]"
1033 static void show_chat_menu(GUIFormSpecMenu **cur_formspec,
1034 InventoryManager *invmgr, IGameDef *gamedef,
1035 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1036 Client *client, std::string text)
1038 std::string formspec =
1039 FORMSPEC_VERSION_STRING
1041 "field[3,2.35;6,0.5;f_text;;" + text + "]"
1042 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
1046 /* Note: FormspecFormSource and LocalFormspecHandler
1047 * are deleted by guiFormSpecMenu */
1048 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1049 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
1051 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1054 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1055 InventoryManager *invmgr, IGameDef *gamedef,
1056 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1058 std::string formspec =
1059 std::string(FORMSPEC_VERSION_STRING) +
1061 "bgcolor[#320000b4;true]"
1062 "label[4.85,1.35;You died.]"
1063 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1067 /* Note: FormspecFormSource and LocalFormspecHandler
1068 * are deleted by guiFormSpecMenu */
1069 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1070 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1072 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1075 /******************************************************************************/
1076 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1077 InventoryManager *invmgr, IGameDef *gamedef,
1078 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1079 bool singleplayermode)
1082 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1083 "No menu visible:\n"
1084 "- single tap: button activate\n"
1085 "- double tap: place/use\n"
1086 "- slide finger: look around\n"
1087 "Menu/Inventory visible:\n"
1088 "- double tap (outside):\n"
1090 "- touch stack, touch slot:\n"
1092 "- touch&drag, tap 2nd finger\n"
1093 " --> place single item to slot\n"
1096 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1098 "- Space: jump/climb\n"
1099 "- Shift: sneak/go down\n"
1102 "- Mouse: turn/look\n"
1103 "- Mouse left: dig/punch\n"
1104 "- Mouse right: place/use\n"
1105 "- Mouse wheel: select item\n"
1110 float ypos = singleplayermode ? 0.5 : 0.1;
1111 std::ostringstream os;
1113 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1114 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1115 << wide_to_narrow(wstrgettext("Continue")) << "]";
1117 if (!singleplayermode) {
1118 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1119 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1122 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1123 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1124 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1125 << wide_to_narrow(wstrgettext("Change Keys")) << "]";
1126 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1127 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1128 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1129 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1130 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1131 << "textarea[0.4,0.25;3.5,6;;" << "Minetest\n"
1132 << minetest_build_info << "\n"
1133 << "path_user = " << wrap_rows(porting::path_user, 20)
1137 /* Note: FormspecFormSource and LocalFormspecHandler *
1138 * are deleted by guiFormSpecMenu */
1139 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1140 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1142 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1144 (*cur_formspec)->doPause = true;
1147 /******************************************************************************/
1148 static void updateChat(Client &client, f32 dtime, bool show_debug,
1149 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1150 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1152 // Add chat log output for errors to be shown in chat
1153 static LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1155 // Get new messages from error log buffer
1156 while (!chat_log_error_buf.empty()) {
1157 chat_backend.addMessage(L"", narrow_to_wide(chat_log_error_buf.get()));
1160 // Get new messages from client
1161 std::wstring message;
1163 while (client.getChatMessage(message)) {
1164 chat_backend.addUnparsedMessage(message);
1167 // Remove old messages
1168 chat_backend.step(dtime);
1170 // Display all messages in a static text element
1171 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1172 std::wstring recent_chat = chat_backend.getRecentChat();
1173 unsigned int line_height = g_fontengine->getLineHeight();
1175 guitext_chat->setText(recent_chat.c_str());
1177 // Update gui element size and position
1178 s32 chat_y = 5 + line_height;
1181 chat_y += line_height;
1183 // first pass to calculate height of text to be set
1184 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1185 porting::getWindowSize().X - 20);
1186 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1187 guitext_chat->setRelativePosition(rect);
1189 //now use real height of text and adjust rect according to this size
1190 rect = core::rect<s32>(10, chat_y, width,
1191 chat_y + guitext_chat->getTextHeight());
1194 guitext_chat->setRelativePosition(rect);
1195 // Don't show chat if disabled or empty or profiler is enabled
1196 guitext_chat->setVisible(
1197 show_chat && recent_chat_count != 0 && !show_profiler);
1201 /****************************************************************************
1202 Fast key cache for main game loop
1203 ****************************************************************************/
1205 /* This is faster than using getKeySetting with the tradeoff that functions
1206 * using it must make sure that it's initialised before using it and there is
1207 * no error handling (for example bounds checking). This is really intended for
1208 * use only in the main running loop of the client (the_game()) where the faster
1209 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1210 * (e.g. formspecs) should continue using getKeySetting().
1214 KeyCache() { populate(); }
1228 KEYMAP_ID_INVENTORY,
1235 KEYMAP_ID_SCREENSHOT,
1236 KEYMAP_ID_TOGGLE_HUD,
1237 KEYMAP_ID_TOGGLE_CHAT,
1238 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1239 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1240 KEYMAP_ID_TOGGLE_DEBUG,
1241 KEYMAP_ID_TOGGLE_PROFILER,
1242 KEYMAP_ID_CAMERA_MODE,
1243 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1244 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1245 KEYMAP_ID_RANGESELECT,
1247 KEYMAP_ID_QUICKTUNE_NEXT,
1248 KEYMAP_ID_QUICKTUNE_PREV,
1249 KEYMAP_ID_QUICKTUNE_INC,
1250 KEYMAP_ID_QUICKTUNE_DEC,
1252 KEYMAP_ID_DEBUG_STACKS,
1254 // Fake keycode for array size and internal checks
1255 KEYMAP_INTERNAL_ENUM_COUNT
1262 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1265 void KeyCache::populate()
1267 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1268 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1269 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1270 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1271 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1272 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1273 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1275 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1276 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1277 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1278 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1279 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1280 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1281 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1282 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1283 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1284 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1285 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1286 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1287 = getKeySetting("keymap_toggle_force_fog_off");
1288 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1289 = getKeySetting("keymap_toggle_update_camera");
1290 key[KEYMAP_ID_TOGGLE_DEBUG]
1291 = getKeySetting("keymap_toggle_debug");
1292 key[KEYMAP_ID_TOGGLE_PROFILER]
1293 = getKeySetting("keymap_toggle_profiler");
1294 key[KEYMAP_ID_CAMERA_MODE]
1295 = getKeySetting("keymap_camera_mode");
1296 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1297 = getKeySetting("keymap_increase_viewing_range_min");
1298 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1299 = getKeySetting("keymap_decrease_viewing_range_min");
1300 key[KEYMAP_ID_RANGESELECT]
1301 = getKeySetting("keymap_rangeselect");
1303 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1304 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1305 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1306 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1308 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1312 /****************************************************************************
1314 ****************************************************************************/
1316 const float object_hit_delay = 0.2;
1319 u32 last_time, busy_time, sleep_time;
1323 /* The reason the following structs are not anonymous structs within the
1324 * class is that they are not used by the majority of member functions and
1325 * many functions that do require objects of thse types do not modify them
1326 * (so they can be passed as a const qualified parameter)
1328 struct CameraOrientation {
1329 f32 camera_yaw; // "right/left"
1330 f32 camera_pitch; // "up/down"
1333 struct GameRunData {
1336 PointedThing pointed_old;
1340 bool update_wielded_item_trigger;
1341 bool reset_jump_timer;
1342 float nodig_delay_timer;
1344 float dig_time_complete;
1345 float repeat_rightclick_timer;
1346 float object_hit_delay_timer;
1347 float time_from_last_punch;
1348 ClientActiveObject *selected_object;
1352 float update_draw_list_timer;
1353 float statustext_time;
1357 v3f update_draw_list_last_cam_dir;
1359 u32 profiler_current_page;
1360 u32 profiler_max_page; // Number of pages
1363 float time_of_day_smooth;
1367 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1375 Jitter dtime_jitter, busy_time_jitter;
1378 /* Flags that can, or may, change during main game loop
1380 struct VolatileRunFlags {
1386 bool show_profiler_graph;
1387 bool disable_camera_update;
1388 bool first_loop_after_window_activation;
1389 bool camera_offset_changed;
1393 /****************************************************************************
1395 ****************************************************************************/
1397 /* This is not intended to be a public class. If a public class becomes
1398 * desirable then it may be better to create another 'wrapper' class that
1399 * hides most of the stuff in this class (nothing in this class is required
1400 * by any other file) but exposes the public methods/data only.
1408 bool startup(bool *kill,
1410 InputHandler *input,
1411 IrrlichtDevice *device,
1412 const std::string &map_dir,
1413 const std::string &playername,
1414 const std::string &password,
1415 // If address is "", local server is used and address is updated
1416 std::string *address,
1418 std::wstring *error_message,
1419 ChatBackend *chat_backend,
1420 const SubgameSpec &gamespec, // Used for local game
1421 bool simple_singleplayer_mode);
1428 void extendedResourceCleanup();
1430 // Basic initialisation
1431 bool init(const std::string &map_dir, std::string *address,
1433 const SubgameSpec &gamespec);
1435 bool createSingleplayerServer(const std::string map_dir,
1436 const SubgameSpec &gamespec, u16 port, std::string *address);
1439 bool createClient(const std::string &playername,
1440 const std::string &password, std::string *address, u16 port,
1441 std::wstring *error_message);
1442 bool initGui(std::wstring *error_message);
1444 // Client connection
1445 bool connectToServer(const std::string &playername,
1446 const std::string &password, std::string *address, u16 port,
1447 bool *connect_ok, bool *aborted);
1448 bool getServerContent(bool *aborted);
1452 void updateInteractTimers(GameRunData *args, f32 dtime);
1453 bool checkConnection();
1454 bool handleCallbacks();
1455 void processQueues();
1456 void updateProfilers(const GameRunData &run_data, const RunStats &stats,
1457 const FpsControl &draw_times, f32 dtime);
1458 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1460 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1462 void processUserInput(VolatileRunFlags *flags, GameRunData *interact_args,
1464 void processKeyboardInput(VolatileRunFlags *flags,
1465 float *statustext_time,
1467 bool *reset_jump_timer,
1468 u32 *profiler_current_page,
1469 u32 profiler_max_page);
1470 void processItemSelection(u16 *new_playeritem);
1472 void dropSelectedItem();
1473 void openInventory();
1475 void toggleFreeMove(float *statustext_time);
1476 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1477 void toggleFast(float *statustext_time);
1478 void toggleNoClip(float *statustext_time);
1480 void toggleChat(float *statustext_time, bool *flag);
1481 void toggleHud(float *statustext_time, bool *flag);
1482 void toggleFog(float *statustext_time, bool *flag);
1483 void toggleDebug(float *statustext_time, bool *show_debug,
1484 bool *show_profiler_graph);
1485 void toggleUpdateCamera(float *statustext_time, bool *flag);
1486 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1487 u32 profiler_max_page);
1489 void increaseViewRange(float *statustext_time);
1490 void decreaseViewRange(float *statustext_time);
1491 void toggleFullViewRange(float *statustext_time);
1493 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1494 void updateCameraOrientation(CameraOrientation *cam,
1495 const VolatileRunFlags &flags);
1496 void updatePlayerControl(const CameraOrientation &cam);
1497 void step(f32 *dtime);
1498 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1499 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1500 float time_from_last_punch);
1501 void updateSound(f32 dtime);
1502 void processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
1503 GameRunData *runData, f32 dtime, bool show_hud,
1505 void handlePointingAtNode(GameRunData *runData,
1506 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1507 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1508 void handlePointingAtObject(GameRunData *runData,
1509 const PointedThing &pointed, const ItemStack &playeritem,
1510 const v3f &player_position, bool show_debug);
1511 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1512 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1514 void updateFrame(std::vector<aabb3f> &highlight_boxes, ProfilerGraph *graph,
1515 RunStats *stats, GameRunData *runData,
1516 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1517 void updateGui(float *statustext_time, const RunStats &stats,
1518 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1519 const CameraOrientation &cam);
1520 void updateProfilerGraphs(ProfilerGraph *graph);
1523 void limitFps(FpsControl *fps_timings, f32 *dtime);
1525 void showOverlayMessage(const char *msg, float dtime, int percent,
1526 bool draw_clouds = true);
1529 InputHandler *input;
1534 IWritableTextureSource *texture_src;
1535 IWritableShaderSource *shader_src;
1537 // When created, these will be filled with data received from the server
1538 IWritableItemDefManager *itemdef_manager;
1539 IWritableNodeDefManager *nodedef_manager;
1541 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1542 ISoundManager *sound;
1543 bool sound_is_dummy;
1544 SoundMaker *soundmaker;
1546 ChatBackend *chat_backend;
1548 GUIFormSpecMenu *current_formspec;
1550 EventManager *eventmgr;
1551 QuicktuneShortcutter *quicktune;
1553 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1554 MapDrawControl *draw_control;
1556 Clouds *clouds; // Free using ->Drop()
1557 Sky *sky; // Free using ->Drop()
1558 Inventory *local_inventory;
1562 This class does take ownership/responsibily for cleaning up etc of any of
1563 these items (e.g. device)
1565 IrrlichtDevice *device;
1566 video::IVideoDriver *driver;
1567 scene::ISceneManager *smgr;
1569 std::wstring *error_message;
1570 IGameDef *gamedef; // Convenience (same as *client)
1571 scene::ISceneNode *skybox;
1574 bool simple_singleplayer_mode;
1577 /* Pre-calculated values
1579 int crack_animation_length;
1583 gui::IGUIStaticText *guitext; // First line of debug text
1584 gui::IGUIStaticText *guitext2; // Second line of debug text
1585 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1586 gui::IGUIStaticText *guitext_status;
1587 gui::IGUIStaticText *guitext_chat; // Chat text
1588 gui::IGUIStaticText *guitext_profiler; // Profiler text
1590 std::wstring infotext;
1591 std::wstring statustext;
1595 IntervalLimiter profiler_interval;
1597 /* TODO: Add a callback function so these can be updated when a setting
1598 * changes. At this point in time it doesn't matter (e.g. /set
1599 * is documented to change server settings only)
1601 * TODO: Local caching of settings is not optimal and should at some stage
1602 * be updated to use a global settings object for getting thse values
1603 * (as opposed to the this local caching). This can be addressed in
1606 bool m_cache_doubletap_jump;
1607 bool m_cache_enable_node_highlighting;
1608 bool m_cache_enable_clouds;
1609 bool m_cache_enable_particles;
1610 bool m_cache_enable_fog;
1611 f32 m_cache_mouse_sensitivity;
1612 f32 m_repeat_right_click_time;
1620 itemdef_manager(NULL),
1621 nodedef_manager(NULL),
1623 sound_is_dummy(false),
1626 current_formspec(NULL),
1629 gui_chat_console(NULL),
1634 local_inventory(NULL),
1637 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
1638 m_cache_enable_node_highlighting = g_settings->getBool("enable_node_highlighting");
1639 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
1640 m_cache_enable_particles = g_settings->getBool("enable_particles");
1641 m_cache_enable_fog = g_settings->getBool("enable_fog");
1642 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
1643 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
1645 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
1650 /****************************************************************************
1652 ****************************************************************************/
1658 if (!sound_is_dummy)
1661 delete server; // deleted first to stop all server threads
1664 delete local_inventory;
1670 delete nodedef_manager;
1671 delete itemdef_manager;
1672 delete draw_control;
1674 extendedResourceCleanup();
1677 bool Game::startup(bool *kill,
1679 InputHandler *input,
1680 IrrlichtDevice *device,
1681 const std::string &map_dir,
1682 const std::string &playername,
1683 const std::string &password,
1684 std::string *address, // can change if simple_singleplayer_mode
1686 std::wstring *error_message,
1687 ChatBackend *chat_backend,
1688 const SubgameSpec &gamespec,
1689 bool simple_singleplayer_mode)
1692 this->device = device;
1694 this->error_message = error_message;
1695 this->random_input = random_input;
1696 this->input = input;
1697 this->chat_backend = chat_backend;
1698 this->simple_singleplayer_mode = simple_singleplayer_mode;
1700 driver = device->getVideoDriver();
1701 smgr = device->getSceneManager();
1703 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1705 if (!init(map_dir, address, port, gamespec))
1708 if (!createClient(playername, password, address, port, error_message))
1717 ProfilerGraph graph;
1718 RunStats stats = { 0 };
1719 CameraOrientation cam_view = { 0 };
1720 GameRunData runData = { 0 };
1721 FpsControl draw_times = { 0 };
1722 VolatileRunFlags flags = { 0 };
1723 f32 dtime; // in seconds
1725 runData.time_from_last_punch = 10.0;
1726 runData.profiler_max_page = 3;
1727 runData.update_wielded_item_trigger = true;
1729 flags.show_chat = true;
1730 flags.show_hud = true;
1731 flags.show_debug = g_settings->getBool("show_debug");
1732 flags.invert_mouse = g_settings->getBool("invert_mouse");
1733 flags.first_loop_after_window_activation = true;
1735 /* Clear the profiler */
1736 Profiler::GraphValues dummyvalues;
1737 g_profiler->graphGet(dummyvalues);
1739 draw_times.last_time = device->getTimer()->getTime();
1741 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1743 &flags.force_fog_off,
1747 std::vector<aabb3f> highlight_boxes;
1749 set_light_table(g_settings->getFloat("display_gamma"));
1751 while (device->run() && !(*kill || g_gamecallback->shutdown_requested)) {
1753 /* Must be called immediately after a device->run() call because it
1754 * uses device->getTimer()->getTime()
1756 limitFps(&draw_times, &dtime);
1758 updateStats(&stats, draw_times, dtime);
1759 updateInteractTimers(&runData, dtime);
1761 if (!checkConnection())
1763 if (!handleCallbacks())
1769 hud->resizeHotbar();
1771 updateProfilers(runData, stats, draw_times, dtime);
1772 processUserInput(&flags, &runData, dtime);
1773 // Update camera before player movement to avoid camera lag of one frame
1774 updateCameraDirection(&cam_view, &flags);
1775 updatePlayerControl(cam_view);
1777 processClientEvents(&cam_view, &runData.damage_flash);
1778 updateCamera(&flags, draw_times.busy_time, dtime,
1779 runData.time_from_last_punch);
1781 processPlayerInteraction(highlight_boxes, &runData, dtime,
1782 flags.show_hud, flags.show_debug);
1783 updateFrame(highlight_boxes, &graph, &stats, &runData, dtime,
1785 updateProfilerGraphs(&graph);
1790 void Game::shutdown()
1792 showOverlayMessage("Shutting down...", 0, 0, false);
1797 if (gui_chat_console)
1798 gui_chat_console->drop();
1806 while (g_menumgr.menuCount() > 0) {
1807 g_menumgr.m_stack.front()->setVisible(false);
1808 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1811 if (current_formspec) {
1812 current_formspec->drop();
1813 current_formspec = NULL;
1816 chat_backend->addMessage(L"", L"# Disconnected.");
1817 chat_backend->addMessage(L"", L"");
1821 while (!client->isShutdown()) {
1822 assert(texture_src != NULL);
1823 assert(shader_src != NULL);
1824 texture_src->processQueue();
1825 shader_src->processQueue();
1833 /****************************************************************************
1835 ****************************************************************************/
1838 const std::string &map_dir,
1839 std::string *address,
1841 const SubgameSpec &gamespec)
1843 showOverlayMessage("Loading...", 0, 0);
1845 texture_src = createTextureSource(device);
1846 shader_src = createShaderSource(device);
1848 itemdef_manager = createItemDefManager();
1849 nodedef_manager = createNodeDefManager();
1851 eventmgr = new EventManager();
1852 quicktune = new QuicktuneShortcutter();
1854 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1855 && eventmgr && quicktune))
1861 // Create a server if not connecting to an existing one
1862 if (*address == "") {
1863 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1870 bool Game::initSound()
1873 if (g_settings->getBool("enable_sound")) {
1874 infostream << "Attempting to use OpenAL audio" << std::endl;
1875 sound = createOpenALSoundManager(&soundfetcher);
1877 infostream << "Failed to initialize OpenAL audio" << std::endl;
1879 infostream << "Sound disabled." << std::endl;
1883 infostream << "Using dummy audio." << std::endl;
1884 sound = &dummySoundManager;
1885 sound_is_dummy = true;
1888 soundmaker = new SoundMaker(sound, nodedef_manager);
1892 soundmaker->registerReceiver(eventmgr);
1897 bool Game::createSingleplayerServer(const std::string map_dir,
1898 const SubgameSpec &gamespec, u16 port, std::string *address)
1900 showOverlayMessage("Creating server...", 0, 5);
1902 std::string bind_str = g_settings->get("bind_address");
1903 Address bind_addr(0, 0, 0, 0, port);
1905 if (g_settings->getBool("ipv6_server")) {
1906 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1910 bind_addr.Resolve(bind_str.c_str());
1911 *address = bind_str;
1912 } catch (ResolveError &e) {
1913 infostream << "Resolving bind address \"" << bind_str
1914 << "\" failed: " << e.what()
1915 << " -- Listening on all addresses." << std::endl;
1918 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1919 *error_message = L"Unable to listen on " +
1920 narrow_to_wide(bind_addr.serializeString()) +
1921 L" because IPv6 is disabled";
1922 errorstream << wide_to_narrow(*error_message) << std::endl;
1926 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1927 bind_addr.isIPv6());
1929 server->start(bind_addr);
1934 bool Game::createClient(const std::string &playername,
1935 const std::string &password, std::string *address, u16 port,
1936 std::wstring *error_message)
1938 showOverlayMessage("Creating client...", 0, 10);
1940 draw_control = new MapDrawControl;
1944 bool could_connect, connect_aborted;
1946 if (!connectToServer(playername, password, address, port,
1947 &could_connect, &connect_aborted))
1950 if (!could_connect) {
1951 if (*error_message == L"" && !connect_aborted) {
1952 // Should not happen if error messages are set properly
1953 *error_message = L"Connection failed for unknown reason";
1954 errorstream << wide_to_narrow(*error_message) << std::endl;
1959 if (!getServerContent(&connect_aborted)) {
1960 if (*error_message == L"" && !connect_aborted) {
1961 // Should not happen if error messages are set properly
1962 *error_message = L"Connection failed for unknown reason";
1963 errorstream << wide_to_narrow(*error_message) << std::endl;
1968 // Update cached textures, meshes and materials
1969 client->afterContentReceived(device, g_fontengine->getFont());
1973 camera = new Camera(smgr, *draw_control, gamedef);
1974 if (!camera || !camera->successfullyCreated(*error_message))
1979 if (m_cache_enable_clouds) {
1980 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1982 *error_message = L"Memory allocation error";
1983 *error_message += narrow_to_wide(" (clouds)");
1984 errorstream << wide_to_narrow(*error_message) << std::endl;
1991 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1992 skybox = NULL; // This is used/set later on in the main run loop
1994 local_inventory = new Inventory(itemdef_manager);
1996 if (!(sky && local_inventory)) {
1997 *error_message = L"Memory allocation error";
1998 *error_message += narrow_to_wide(" (sky or local inventory)");
1999 errorstream << wide_to_narrow(*error_message) << std::endl;
2003 /* Pre-calculated values
2005 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2007 v2u32 size = t->getOriginalSize();
2008 crack_animation_length = size.Y / size.X;
2010 crack_animation_length = 5;
2013 if (!initGui(error_message))
2016 /* Set window caption
2018 core::stringw str = L"Minetest [";
2019 str += driver->getName();
2021 device->setWindowCaption(str.c_str());
2023 LocalPlayer *player = client->getEnv().getLocalPlayer();
2024 player->hurt_tilt_timer = 0;
2025 player->hurt_tilt_strength = 0;
2027 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2030 *error_message = L"Memory error: could not create HUD";
2031 errorstream << wide_to_narrow(*error_message) << std::endl;
2038 bool Game::initGui(std::wstring *error_message)
2040 // First line of debug text
2041 guitext = guienv->addStaticText(
2043 core::rect<s32>(0, 0, 0, 0),
2044 false, false, guiroot);
2046 // Second line of debug text
2047 guitext2 = guienv->addStaticText(
2049 core::rect<s32>(0, 0, 0, 0),
2050 false, false, guiroot);
2052 // At the middle of the screen
2053 // Object infos are shown in this
2054 guitext_info = guienv->addStaticText(
2056 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2057 false, true, guiroot);
2059 // Status text (displays info when showing and hiding GUI stuff, etc.)
2060 guitext_status = guienv->addStaticText(
2062 core::rect<s32>(0, 0, 0, 0),
2063 false, false, guiroot);
2064 guitext_status->setVisible(false);
2067 guitext_chat = guienv->addStaticText(
2069 core::rect<s32>(0, 0, 0, 0),
2070 //false, false); // Disable word wrap as of now
2071 false, true, guiroot);
2072 // Remove stale "recent" chat messages from previous connections
2073 chat_backend->clearRecentChat();
2075 // Chat backend and console
2076 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2077 -1, chat_backend, client);
2078 if (!gui_chat_console) {
2079 *error_message = L"Could not allocate memory for chat console";
2080 errorstream << wide_to_narrow(*error_message) << std::endl;
2084 // Profiler text (size is updated when text is updated)
2085 guitext_profiler = guienv->addStaticText(
2087 core::rect<s32>(0, 0, 0, 0),
2088 false, false, guiroot);
2089 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2090 guitext_profiler->setVisible(false);
2091 guitext_profiler->setWordWrap(true);
2093 #ifdef HAVE_TOUCHSCREENGUI
2095 if (g_touchscreengui)
2096 g_touchscreengui->init(texture_src, porting::getDisplayDensity());
2103 bool Game::connectToServer(const std::string &playername,
2104 const std::string &password, std::string *address, u16 port,
2105 bool *connect_ok, bool *aborted)
2107 showOverlayMessage("Resolving address...", 0, 15);
2109 Address connect_address(0, 0, 0, 0, port);
2112 connect_address.Resolve(address->c_str());
2114 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2115 //connect_address.Resolve("localhost");
2116 if (connect_address.isIPv6()) {
2117 IPv6AddressBytes addr_bytes;
2118 addr_bytes.bytes[15] = 1;
2119 connect_address.setAddress(&addr_bytes);
2121 connect_address.setAddress(127, 0, 0, 1);
2124 } catch (ResolveError &e) {
2125 *error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
2126 errorstream << wide_to_narrow(*error_message) << std::endl;
2130 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2131 *error_message = L"Unable to connect to " +
2132 narrow_to_wide(connect_address.serializeString()) +
2133 L" because IPv6 is disabled";
2134 errorstream << wide_to_narrow(*error_message) << std::endl;
2138 client = new Client(device,
2139 playername.c_str(), password, simple_singleplayer_mode,
2140 *draw_control, texture_src, shader_src,
2141 itemdef_manager, nodedef_manager, sound, eventmgr,
2142 connect_address.isIPv6());
2147 gamedef = client; // Client acts as our GameDef
2150 infostream << "Connecting to server at ";
2151 connect_address.print(&infostream);
2152 infostream << std::endl;
2154 client->connect(connect_address);
2158 Wait for server to accept connection
2164 FpsControl fps_control = { 0 };
2165 f32 dtime; // in seconds
2167 while (device->run()) {
2169 limitFps(&fps_control, &dtime);
2171 // Update client and server
2172 client->step(dtime);
2175 server->step(dtime);
2178 if (client->getState() == LC_Init) {
2184 if (client->accessDenied()) {
2185 *error_message = L"Access denied. Reason: "
2186 + client->accessDeniedReason();
2187 errorstream << wide_to_narrow(*error_message) << std::endl;
2191 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2193 infostream << "Connect aborted [Escape]" << std::endl;
2198 showOverlayMessage("Connecting to server...", dtime, 20);
2200 } catch (con::PeerNotFoundException &e) {
2201 // TODO: Should something be done here? At least an info/error
2209 bool Game::getServerContent(bool *aborted)
2213 FpsControl fps_control = { 0 };
2214 f32 dtime; // in seconds
2216 while (device->run()) {
2218 limitFps(&fps_control, &dtime);
2220 // Update client and server
2221 client->step(dtime);
2224 server->step(dtime);
2227 if (client->mediaReceived() && client->itemdefReceived() &&
2228 client->nodedefReceived()) {
2233 if (client->accessDenied()) {
2234 *error_message = L"Access denied. Reason: "
2235 + client->accessDeniedReason();
2236 errorstream << wide_to_narrow(*error_message) << std::endl;
2240 if (client->getState() < LC_Init) {
2241 *error_message = L"Client disconnected";
2242 errorstream << wide_to_narrow(*error_message) << std::endl;
2246 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2248 infostream << "Connect aborted [Escape]" << std::endl;
2255 if (!client->itemdefReceived()) {
2256 wchar_t *text = wgettext("Item definitions...");
2258 draw_load_screen(text, device, guienv, dtime, progress);
2260 } else if (!client->nodedefReceived()) {
2261 wchar_t *text = wgettext("Node definitions...");
2263 draw_load_screen(text, device, guienv, dtime, progress);
2266 std::stringstream message;
2267 message.precision(3);
2268 message << gettext("Media...");
2270 if ((USE_CURL == 0) ||
2271 (!g_settings->getBool("enable_remote_media_server"))) {
2272 float cur = client->getCurRate();
2273 std::string cur_unit = gettext(" KB/s");
2277 cur_unit = gettext(" MB/s");
2280 message << " ( " << cur << cur_unit << " )";
2283 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2284 draw_load_screen(narrow_to_wide(message.str().c_str()), device,
2285 guienv, dtime, progress);
2294 /****************************************************************************
2296 ****************************************************************************/
2298 inline void Game::updateInteractTimers(GameRunData *args, f32 dtime)
2300 if (args->nodig_delay_timer >= 0)
2301 args->nodig_delay_timer -= dtime;
2303 if (args->object_hit_delay_timer >= 0)
2304 args->object_hit_delay_timer -= dtime;
2306 args->time_from_last_punch += dtime;
2310 /* returns false if game should exit, otherwise true
2312 inline bool Game::checkConnection()
2314 if (client->accessDenied()) {
2315 *error_message = L"Access denied. Reason: "
2316 + client->accessDeniedReason();
2317 errorstream << wide_to_narrow(*error_message) << std::endl;
2325 /* returns false if game should exit, otherwise true
2327 inline bool Game::handleCallbacks()
2329 if (g_gamecallback->disconnect_requested) {
2330 g_gamecallback->disconnect_requested = false;
2334 if (g_gamecallback->changepassword_requested) {
2335 (new GUIPasswordChange(guienv, guiroot, -1,
2336 &g_menumgr, client))->drop();
2337 g_gamecallback->changepassword_requested = false;
2340 if (g_gamecallback->changevolume_requested) {
2341 (new GUIVolumeChange(guienv, guiroot, -1,
2342 &g_menumgr, client))->drop();
2343 g_gamecallback->changevolume_requested = false;
2346 if (g_gamecallback->keyconfig_requested) {
2347 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2348 &g_menumgr))->drop();
2349 g_gamecallback->keyconfig_requested = false;
2352 if (g_gamecallback->keyconfig_changed) {
2353 keycache.populate(); // update the cache with new settings
2354 g_gamecallback->keyconfig_changed = false;
2361 void Game::processQueues()
2363 texture_src->processQueue();
2364 itemdef_manager->processQueue(gamedef);
2365 shader_src->processQueue();
2369 void Game::updateProfilers(const GameRunData &run_data, const RunStats &stats,
2370 const FpsControl &draw_times, f32 dtime)
2372 float profiler_print_interval =
2373 g_settings->getFloat("profiler_print_interval");
2374 bool print_to_log = true;
2376 if (profiler_print_interval == 0) {
2377 print_to_log = false;
2378 profiler_print_interval = 5;
2381 if (profiler_interval.step(dtime, profiler_print_interval)) {
2383 infostream << "Profiler:" << std::endl;
2384 g_profiler->print(infostream);
2387 update_profiler_gui(guitext_profiler, g_fontengine,
2388 run_data.profiler_current_page, run_data.profiler_max_page,
2389 driver->getScreenSize().Height);
2391 g_profiler->clear();
2394 addProfilerGraphs(stats, draw_times, dtime);
2398 void Game::addProfilerGraphs(const RunStats &stats,
2399 const FpsControl &draw_times, f32 dtime)
2401 g_profiler->graphAdd("mainloop_other",
2402 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2404 if (draw_times.sleep_time != 0)
2405 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2406 g_profiler->graphAdd("mainloop_dtime", dtime);
2408 g_profiler->add("Elapsed time", dtime);
2409 g_profiler->avg("FPS", 1. / dtime);
2413 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2420 /* Time average and jitter calculation
2422 jp = &stats->dtime_jitter;
2423 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2425 jitter = dtime - jp->avg;
2427 if (jitter > jp->max)
2430 jp->counter += dtime;
2432 if (jp->counter > 0.0) {
2434 jp->max_sample = jp->max;
2435 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2439 /* Busytime average and jitter calculation
2441 jp = &stats->busy_time_jitter;
2442 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2444 jitter = draw_times.busy_time - jp->avg;
2446 if (jitter > jp->max)
2448 if (jitter < jp->min)
2451 jp->counter += dtime;
2453 if (jp->counter > 0.0) {
2455 jp->max_sample = jp->max;
2456 jp->min_sample = jp->min;
2464 /****************************************************************************
2466 ****************************************************************************/
2468 void Game::processUserInput(VolatileRunFlags *flags,
2469 GameRunData *interact_args, f32 dtime)
2471 // Reset input if window not active or some menu is active
2472 if (device->isWindowActive() == false
2473 || noMenuActive() == false
2474 || guienv->hasFocus(gui_chat_console)) {
2478 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2479 gui_chat_console->closeConsoleAtOnce();
2482 // Input handler step() (used by the random input generator)
2485 #ifdef HAVE_TOUCHSCREENGUI
2487 if (g_touchscreengui) {
2488 g_touchscreengui->step(dtime);
2494 if (current_formspec != 0)
2495 current_formspec->getAndroidUIInput();
2499 // Increase timer for double tap of "keymap_jump"
2500 if (m_cache_doubletap_jump && interact_args->jump_timer <= 0.2)
2501 interact_args->jump_timer += dtime;
2503 processKeyboardInput(
2505 &interact_args->statustext_time,
2506 &interact_args->jump_timer,
2507 &interact_args->reset_jump_timer,
2508 &interact_args->profiler_current_page,
2509 interact_args->profiler_max_page);
2511 processItemSelection(&interact_args->new_playeritem);
2515 void Game::processKeyboardInput(VolatileRunFlags *flags,
2516 float *statustext_time,
2518 bool *reset_jump_timer,
2519 u32 *profiler_current_page,
2520 u32 profiler_max_page)
2523 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2525 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2527 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2529 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2530 show_pause_menu(¤t_formspec, client, gamedef, texture_src, device,
2531 simple_singleplayer_mode);
2532 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2533 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2535 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2536 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2538 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2540 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2541 toggleFreeMove(statustext_time);
2542 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2543 toggleFreeMoveAlt(statustext_time, jump_timer);
2544 *reset_jump_timer = true;
2545 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2546 toggleFast(statustext_time);
2547 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2548 toggleNoClip(statustext_time);
2549 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2550 client->makeScreenshot(device);
2551 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2552 toggleHud(statustext_time, &flags->show_hud);
2553 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2554 toggleChat(statustext_time, &flags->show_chat);
2555 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2556 toggleFog(statustext_time, &flags->force_fog_off);
2557 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2558 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2559 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2560 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2561 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2562 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2563 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2564 increaseViewRange(statustext_time);
2565 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2566 decreaseViewRange(statustext_time);
2567 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2568 toggleFullViewRange(statustext_time);
2569 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
2571 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
2573 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
2575 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
2577 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2578 // Print debug stacks
2579 dstream << "-----------------------------------------"
2581 dstream << DTIME << "Printing debug stacks:" << std::endl;
2582 dstream << "-----------------------------------------"
2584 debug_stacks_print();
2587 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2588 *reset_jump_timer = false;
2594 if (quicktune->hasMessage()) {
2595 std::string msg = quicktune->getMessage();
2596 statustext = narrow_to_wide(msg);
2597 *statustext_time = 0;
2602 void Game::processItemSelection(u16 *new_playeritem)
2604 LocalPlayer *player = client->getEnv().getLocalPlayer();
2606 /* Item selection using mouse wheel
2608 *new_playeritem = client->getPlayerItem();
2610 s32 wheel = input->getMouseWheel();
2611 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2612 player->hud_hotbar_itemcount - 1);
2615 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2617 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2621 /* Item selection using keyboard
2623 for (u16 i = 0; i < 10; i++) {
2624 static const KeyPress *item_keys[10] = {
2625 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2626 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2627 NumberKey + 9, NumberKey + 0,
2630 if (input->wasKeyDown(*item_keys[i])) {
2631 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2632 *new_playeritem = i;
2633 infostream << "Selected item: " << new_playeritem << std::endl;
2641 void Game::dropSelectedItem()
2643 IDropAction *a = new IDropAction();
2645 a->from_inv.setCurrentPlayer();
2646 a->from_list = "main";
2647 a->from_i = client->getPlayerItem();
2648 client->inventoryAction(a);
2652 void Game::openInventory()
2654 infostream << "the_game: " << "Launching inventory" << std::endl;
2656 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2657 TextDest *txt_dst = new TextDestPlayerInventory(client);
2659 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2660 device, fs_src, txt_dst, client);
2662 InventoryLocation inventoryloc;
2663 inventoryloc.setCurrentPlayer();
2664 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2668 void Game::openConsole()
2670 if (!gui_chat_console->isOpenInhibited()) {
2671 // Open up to over half of the screen
2672 gui_chat_console->openConsole(0.6);
2673 guienv->setFocus(gui_chat_console);
2678 void Game::toggleFreeMove(float *statustext_time)
2680 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2682 bool free_move = !g_settings->getBool("free_move");
2683 g_settings->set("free_move", bool_to_cstr(free_move));
2685 *statustext_time = 0;
2686 statustext = msg[free_move];
2687 if (free_move && !client->checkPrivilege("fly"))
2688 statustext += L" (note: no 'fly' privilege)";
2692 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2694 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2695 toggleFreeMove(statustext_time);
2699 void Game::toggleFast(float *statustext_time)
2701 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2702 bool fast_move = !g_settings->getBool("fast_move");
2703 g_settings->set("fast_move", bool_to_cstr(fast_move));
2705 *statustext_time = 0;
2706 statustext = msg[fast_move];
2708 if (fast_move && !client->checkPrivilege("fast"))
2709 statustext += L" (note: no 'fast' privilege)";
2713 void Game::toggleNoClip(float *statustext_time)
2715 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2716 bool noclip = !g_settings->getBool("noclip");
2717 g_settings->set("noclip", bool_to_cstr(noclip));
2719 *statustext_time = 0;
2720 statustext = msg[noclip];
2722 if (noclip && !client->checkPrivilege("noclip"))
2723 statustext += L" (note: no 'noclip' privilege)";
2727 void Game::toggleChat(float *statustext_time, bool *flag)
2729 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2732 *statustext_time = 0;
2733 statustext = msg[*flag];
2737 void Game::toggleHud(float *statustext_time, bool *flag)
2739 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2742 *statustext_time = 0;
2743 statustext = msg[*flag];
2744 if (g_settings->getBool("enable_node_highlighting"))
2745 client->setHighlighted(client->getHighlighted(), *flag);
2749 void Game::toggleFog(float *statustext_time, bool *flag)
2751 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2754 *statustext_time = 0;
2755 statustext = msg[*flag];
2759 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2760 bool *show_profiler_graph)
2762 // Initial / 3x toggle: Chat only
2763 // 1x toggle: Debug text with chat
2764 // 2x toggle: Debug text with profiler graph
2767 *show_profiler_graph = false;
2768 statustext = L"Debug info shown";
2769 } else if (*show_profiler_graph) {
2770 *show_debug = false;
2771 *show_profiler_graph = false;
2772 statustext = L"Debug info and profiler graph hidden";
2774 *show_profiler_graph = true;
2775 statustext = L"Profiler graph shown";
2777 *statustext_time = 0;
2781 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
2783 static const wchar_t *msg[] = {
2784 L"Camera update enabled",
2785 L"Camera update disabled"
2789 *statustext_time = 0;
2790 statustext = msg[*flag];
2794 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
2795 u32 profiler_max_page)
2797 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
2799 // FIXME: This updates the profiler with incomplete values
2800 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
2801 profiler_max_page, driver->getScreenSize().Height);
2803 if (*profiler_current_page != 0) {
2804 std::wstringstream sstr;
2805 sstr << "Profiler shown (page " << *profiler_current_page
2806 << " of " << profiler_max_page << ")";
2807 statustext = sstr.str();
2809 statustext = L"Profiler hidden";
2811 *statustext_time = 0;
2815 void Game::increaseViewRange(float *statustext_time)
2817 s16 range = g_settings->getS16("viewing_range_nodes_min");
2818 s16 range_new = range + 10;
2819 g_settings->set("viewing_range_nodes_min", itos(range_new));
2820 statustext = narrow_to_wide("Minimum viewing range changed to "
2822 *statustext_time = 0;
2826 void Game::decreaseViewRange(float *statustext_time)
2828 s16 range = g_settings->getS16("viewing_range_nodes_min");
2829 s16 range_new = range - 10;
2834 g_settings->set("viewing_range_nodes_min", itos(range_new));
2835 statustext = narrow_to_wide("Minimum viewing range changed to "
2837 *statustext_time = 0;
2841 void Game::toggleFullViewRange(float *statustext_time)
2843 static const wchar_t *msg[] = {
2844 L"Disabled full viewing range",
2845 L"Enabled full viewing range"
2848 draw_control->range_all = !draw_control->range_all;
2849 infostream << msg[draw_control->range_all] << std::endl;
2850 statustext = msg[draw_control->range_all];
2851 *statustext_time = 0;
2855 void Game::updateCameraDirection(CameraOrientation *cam,
2856 VolatileRunFlags *flags)
2858 if ((device->isWindowActive() && noMenuActive()) || random_input) {
2861 if (!random_input) {
2862 // Mac OSX gets upset if this is set every frame
2863 if (device->getCursorControl()->isVisible())
2864 device->getCursorControl()->setVisible(false);
2868 if (flags->first_loop_after_window_activation)
2869 flags->first_loop_after_window_activation = false;
2871 updateCameraOrientation(cam, *flags);
2873 input->setMousePos((driver->getScreenSize().Width / 2),
2874 (driver->getScreenSize().Height / 2));
2878 // Mac OSX gets upset if this is set every frame
2879 if (device->getCursorControl()->isVisible() == false)
2880 device->getCursorControl()->setVisible(true);
2883 if (!flags->first_loop_after_window_activation)
2884 flags->first_loop_after_window_activation = true;
2890 void Game::updateCameraOrientation(CameraOrientation *cam,
2891 const VolatileRunFlags &flags)
2893 #ifdef HAVE_TOUCHSCREENGUI
2894 if (g_touchscreengui) {
2895 cam->camera_yaw = g_touchscreengui->getYaw();
2896 cam->camera_pitch = g_touchscreengui->getPitch();
2899 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
2900 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
2902 if (flags.invert_mouse
2903 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2907 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
2908 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
2910 #ifdef HAVE_TOUCHSCREENGUI
2914 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2918 void Game::updatePlayerControl(const CameraOrientation &cam)
2920 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2922 PlayerControl control(
2923 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
2924 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
2925 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
2926 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
2927 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
2928 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
2929 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
2930 input->getLeftState(),
2931 input->getRightState(),
2935 client->setPlayerControl(control);
2936 LocalPlayer *player = client->getEnv().getLocalPlayer();
2937 player->keyPressed =
2938 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
2939 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
2940 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
2941 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
2942 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
2943 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
2944 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
2945 ( (u32)(input->getLeftState() & 0x1) << 7) |
2946 ( (u32)(input->getRightState() & 0x1) << 8
2953 inline void Game::step(f32 *dtime)
2955 bool can_be_and_is_paused =
2956 (simple_singleplayer_mode && g_menumgr.pausesGame());
2958 if (can_be_and_is_paused) { // This is for a singleplayer server
2959 *dtime = 0; // No time passes
2961 if (server != NULL) {
2962 //TimeTaker timer("server->step(dtime)");
2963 server->step(*dtime);
2966 //TimeTaker timer("client.step(dtime)");
2967 client->step(*dtime);
2972 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
2974 ClientEvent event = client->getClientEvent();
2976 LocalPlayer *player = client->getEnv().getLocalPlayer();
2978 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
2980 if (event.type == CE_PLAYER_DAMAGE &&
2981 client->getHP() != 0) {
2982 //u16 damage = event.player_damage.amount;
2983 //infostream<<"Player damage: "<<damage<<std::endl;
2985 *damage_flash += 100.0;
2986 *damage_flash += 8.0 * event.player_damage.amount;
2988 player->hurt_tilt_timer = 1.5;
2989 player->hurt_tilt_strength = event.player_damage.amount / 4;
2990 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
2992 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2993 gamedef->event()->put(e);
2994 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
2995 cam->camera_yaw = event.player_force_move.yaw;
2996 cam->camera_pitch = event.player_force_move.pitch;
2997 } else if (event.type == CE_DEATHSCREEN) {
2998 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3001 chat_backend->addMessage(L"", L"You died.");
3003 /* Handle visualization */
3005 player->hurt_tilt_timer = 0;
3006 player->hurt_tilt_strength = 0;
3008 } else if (event.type == CE_SHOW_FORMSPEC) {
3009 FormspecFormSource *fs_src =
3010 new FormspecFormSource(*(event.show_formspec.formspec));
3011 TextDestPlayerInventory *txt_dst =
3012 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3014 create_formspec_menu(¤t_formspec, client, gamedef,
3015 texture_src, device, fs_src, txt_dst, client);
3017 delete(event.show_formspec.formspec);
3018 delete(event.show_formspec.formname);
3019 } else if (event.type == CE_SPAWN_PARTICLE) {
3020 video::ITexture *texture =
3021 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
3023 new Particle(gamedef, smgr, player, client->getEnv(),
3024 *event.spawn_particle.pos,
3025 *event.spawn_particle.vel,
3026 *event.spawn_particle.acc,
3027 event.spawn_particle.expirationtime,
3028 event.spawn_particle.size,
3029 event.spawn_particle.collisiondetection,
3030 event.spawn_particle.vertical,
3034 } else if (event.type == CE_ADD_PARTICLESPAWNER) {
3035 video::ITexture *texture =
3036 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
3038 new ParticleSpawner(gamedef, smgr, player,
3039 event.add_particlespawner.amount,
3040 event.add_particlespawner.spawntime,
3041 *event.add_particlespawner.minpos,
3042 *event.add_particlespawner.maxpos,
3043 *event.add_particlespawner.minvel,
3044 *event.add_particlespawner.maxvel,
3045 *event.add_particlespawner.minacc,
3046 *event.add_particlespawner.maxacc,
3047 event.add_particlespawner.minexptime,
3048 event.add_particlespawner.maxexptime,
3049 event.add_particlespawner.minsize,
3050 event.add_particlespawner.maxsize,
3051 event.add_particlespawner.collisiondetection,
3052 event.add_particlespawner.vertical,
3054 event.add_particlespawner.id);
3055 } else if (event.type == CE_DELETE_PARTICLESPAWNER) {
3056 delete_particlespawner(event.delete_particlespawner.id);
3057 } else if (event.type == CE_HUDADD) {
3058 u32 id = event.hudadd.id;
3060 LocalPlayer *player = client->getEnv().getLocalPlayer();
3061 HudElement *e = player->getHud(id);
3064 delete event.hudadd.pos;
3065 delete event.hudadd.name;
3066 delete event.hudadd.scale;
3067 delete event.hudadd.text;
3068 delete event.hudadd.align;
3069 delete event.hudadd.offset;
3070 delete event.hudadd.world_pos;
3071 delete event.hudadd.size;
3076 e->type = (HudElementType)event.hudadd.type;
3077 e->pos = *event.hudadd.pos;
3078 e->name = *event.hudadd.name;
3079 e->scale = *event.hudadd.scale;
3080 e->text = *event.hudadd.text;
3081 e->number = event.hudadd.number;
3082 e->item = event.hudadd.item;
3083 e->dir = event.hudadd.dir;
3084 e->align = *event.hudadd.align;
3085 e->offset = *event.hudadd.offset;
3086 e->world_pos = *event.hudadd.world_pos;
3087 e->size = *event.hudadd.size;
3089 u32 new_id = player->addHud(e);
3090 //if this isn't true our huds aren't consistent
3091 assert(new_id == id);
3093 delete event.hudadd.pos;
3094 delete event.hudadd.name;
3095 delete event.hudadd.scale;
3096 delete event.hudadd.text;
3097 delete event.hudadd.align;
3098 delete event.hudadd.offset;
3099 delete event.hudadd.world_pos;
3100 delete event.hudadd.size;
3101 } else if (event.type == CE_HUDRM) {
3102 HudElement *e = player->removeHud(event.hudrm.id);
3106 } else if (event.type == CE_HUDCHANGE) {
3107 u32 id = event.hudchange.id;
3108 HudElement *e = player->getHud(id);
3111 delete event.hudchange.v3fdata;
3112 delete event.hudchange.v2fdata;
3113 delete event.hudchange.sdata;
3114 delete event.hudchange.v2s32data;
3118 switch (event.hudchange.stat) {
3120 e->pos = *event.hudchange.v2fdata;
3124 e->name = *event.hudchange.sdata;
3127 case HUD_STAT_SCALE:
3128 e->scale = *event.hudchange.v2fdata;
3132 e->text = *event.hudchange.sdata;
3135 case HUD_STAT_NUMBER:
3136 e->number = event.hudchange.data;
3140 e->item = event.hudchange.data;
3144 e->dir = event.hudchange.data;
3147 case HUD_STAT_ALIGN:
3148 e->align = *event.hudchange.v2fdata;
3151 case HUD_STAT_OFFSET:
3152 e->offset = *event.hudchange.v2fdata;
3155 case HUD_STAT_WORLD_POS:
3156 e->world_pos = *event.hudchange.v3fdata;
3160 e->size = *event.hudchange.v2s32data;
3164 delete event.hudchange.v3fdata;
3165 delete event.hudchange.v2fdata;
3166 delete event.hudchange.sdata;
3167 delete event.hudchange.v2s32data;
3168 } else if (event.type == CE_SET_SKY) {
3169 sky->setVisible(false);
3176 // Handle according to type
3177 if (*event.set_sky.type == "regular") {
3178 sky->setVisible(true);
3179 } else if (*event.set_sky.type == "skybox" &&
3180 event.set_sky.params->size() == 6) {
3181 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3182 skybox = smgr->addSkyBoxSceneNode(
3183 texture_src->getTexture((*event.set_sky.params)[0]),
3184 texture_src->getTexture((*event.set_sky.params)[1]),
3185 texture_src->getTexture((*event.set_sky.params)[2]),
3186 texture_src->getTexture((*event.set_sky.params)[3]),
3187 texture_src->getTexture((*event.set_sky.params)[4]),
3188 texture_src->getTexture((*event.set_sky.params)[5]));
3190 // Handle everything else as plain color
3192 if (*event.set_sky.type != "plain")
3193 infostream << "Unknown sky type: "
3194 << (*event.set_sky.type) << std::endl;
3196 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3199 delete event.set_sky.bgcolor;
3200 delete event.set_sky.type;
3201 delete event.set_sky.params;
3202 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3203 bool enable = event.override_day_night_ratio.do_override;
3204 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3205 client->getEnv().setDayNightRatioOverride(enable, value);
3211 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3212 f32 dtime, float time_from_last_punch)
3214 LocalPlayer *player = client->getEnv().getLocalPlayer();
3217 For interaction purposes, get info about the held item
3219 - Is it a usable item?
3220 - Can it point to liquids?
3222 ItemStack playeritem;
3224 InventoryList *mlist = local_inventory->getList("main");
3226 if (mlist && client->getPlayerItem() < mlist->getSize())
3227 playeritem = mlist->getItem(client->getPlayerItem());
3230 ToolCapabilities playeritem_toolcap =
3231 playeritem.getToolCapabilities(itemdef_manager);
3233 v3s16 old_camera_offset = camera->getOffset();
3235 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3236 camera->toggleCameraMode();
3237 GenericCAO *playercao = player->getCAO();
3239 assert(playercao != NULL);
3241 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3244 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3245 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3247 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3248 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3250 camera->step(dtime);
3252 v3f camera_position = camera->getPosition();
3253 v3f camera_direction = camera->getDirection();
3254 f32 camera_fov = camera->getFovMax();
3255 v3s16 camera_offset = camera->getOffset();
3257 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3259 if (!flags->disable_camera_update) {
3260 client->getEnv().getClientMap().updateCamera(camera_position,
3261 camera_direction, camera_fov, camera_offset);
3263 if (flags->camera_offset_changed) {
3264 client->updateCameraOffset(camera_offset);
3265 client->getEnv().updateCameraOffset(camera_offset);
3268 clouds->updateCameraOffset(camera_offset);
3274 void Game::updateSound(f32 dtime)
3276 // Update sound listener
3277 v3s16 camera_offset = camera->getOffset();
3278 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3279 v3f(0, 0, 0), // velocity
3280 camera->getDirection(),
3281 camera->getCameraNode()->getUpVector());
3282 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3285 // Update sound maker
3286 soundmaker->step(dtime);
3288 LocalPlayer *player = client->getEnv().getLocalPlayer();
3290 ClientMap &map = client->getEnv().getClientMap();
3291 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3292 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3296 void Game::processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
3297 GameRunData *runData, f32 dtime, bool show_hud, bool show_debug)
3299 LocalPlayer *player = client->getEnv().getLocalPlayer();
3301 ItemStack playeritem;
3303 InventoryList *mlist = local_inventory->getList("main");
3305 if (mlist && client->getPlayerItem() < mlist->getSize())
3306 playeritem = mlist->getItem(client->getPlayerItem());
3309 const ItemDefinition &playeritem_def =
3310 playeritem.getDefinition(itemdef_manager);
3312 v3f player_position = player->getPosition();
3313 v3f camera_position = camera->getPosition();
3314 v3f camera_direction = camera->getDirection();
3315 v3s16 camera_offset = camera->getOffset();
3319 Calculate what block is the crosshair pointing to
3322 f32 d = playeritem_def.range; // max. distance
3323 f32 d_hand = itemdef_manager->get("").range;
3325 if (d < 0 && d_hand >= 0)
3330 core::line3d<f32> shootline;
3332 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3334 shootline = core::line3d<f32>(camera_position,
3335 camera_position + camera_direction * BS * (d + 1));
3338 // prevent player pointing anything in front-view
3339 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3340 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3343 #ifdef HAVE_TOUCHSCREENGUI
3345 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3346 shootline = g_touchscreengui->getShootline();
3347 shootline.start += intToFloat(camera_offset, BS);
3348 shootline.end += intToFloat(camera_offset, BS);
3353 PointedThing pointed = getPointedThing(
3355 client, player_position, camera_direction,
3356 camera_position, shootline, d,
3357 playeritem_def.liquids_pointable,
3358 !runData->ldown_for_dig,
3362 runData->selected_object);
3364 if (pointed != runData->pointed_old) {
3365 infostream << "Pointing at " << pointed.dump() << std::endl;
3367 if (m_cache_enable_node_highlighting) {
3368 if (pointed.type == POINTEDTHING_NODE) {
3369 client->setHighlighted(pointed.node_undersurface, show_hud);
3371 client->setHighlighted(pointed.node_undersurface, false);
3378 - releasing left mouse button
3379 - pointing away from node
3381 if (runData->digging) {
3382 if (input->getLeftReleased()) {
3383 infostream << "Left button released"
3384 << " (stopped digging)" << std::endl;
3385 runData->digging = false;
3386 } else if (pointed != runData->pointed_old) {
3387 if (pointed.type == POINTEDTHING_NODE
3388 && runData->pointed_old.type == POINTEDTHING_NODE
3389 && pointed.node_undersurface
3390 == runData->pointed_old.node_undersurface) {
3391 // Still pointing to the same node, but a different face.
3394 infostream << "Pointing away from node"
3395 << " (stopped digging)" << std::endl;
3396 runData->digging = false;
3400 if (!runData->digging) {
3401 client->interact(1, runData->pointed_old);
3402 client->setCrack(-1, v3s16(0, 0, 0));
3403 runData->dig_time = 0.0;
3407 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3408 runData->ldown_for_dig = false;
3411 runData->left_punch = false;
3413 soundmaker->m_player_leftpunch_sound.name = "";
3415 if (input->getRightState())
3416 runData->repeat_rightclick_timer += dtime;
3418 runData->repeat_rightclick_timer = 0;
3420 if (playeritem_def.usable && input->getLeftState()) {
3421 if (input->getLeftClicked())
3422 client->interact(4, pointed);
3423 } else if (pointed.type == POINTEDTHING_NODE) {
3424 ToolCapabilities playeritem_toolcap =
3425 playeritem.getToolCapabilities(itemdef_manager);
3426 handlePointingAtNode(runData, pointed, playeritem_def,
3427 playeritem_toolcap, dtime);
3428 } else if (pointed.type == POINTEDTHING_OBJECT) {
3429 handlePointingAtObject(runData, pointed, playeritem,
3430 player_position, show_debug);
3431 } else if (input->getLeftState()) {
3432 // When button is held down in air, show continuous animation
3433 runData->left_punch = true;
3436 runData->pointed_old = pointed;
3438 if (runData->left_punch || input->getLeftClicked())
3439 camera->setDigging(0); // left click animation
3441 input->resetLeftClicked();
3442 input->resetRightClicked();
3444 input->resetLeftReleased();
3445 input->resetRightReleased();
3449 void Game::handlePointingAtNode(GameRunData *runData,
3450 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3451 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3453 v3s16 nodepos = pointed.node_undersurface;
3454 v3s16 neighbourpos = pointed.node_abovesurface;
3457 Check information text of node
3460 ClientMap &map = client->getEnv().getClientMap();
3461 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3464 infotext = narrow_to_wide(meta->getString("infotext"));
3466 MapNode n = map.getNodeNoEx(nodepos);
3468 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3469 infotext = L"Unknown node: ";
3470 infotext += narrow_to_wide(nodedef_manager->get(n).name);
3474 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3475 && client->checkPrivilege("interact")) {
3476 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3479 if ((input->getRightClicked() ||
3480 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3481 client->checkPrivilege("interact")) {
3482 runData->repeat_rightclick_timer = 0;
3483 infostream << "Ground right-clicked" << std::endl;
3485 if (meta && meta->getString("formspec") != "" && !random_input
3486 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3487 infostream << "Launching custom inventory view" << std::endl;
3489 InventoryLocation inventoryloc;
3490 inventoryloc.setNodeMeta(nodepos);
3492 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3493 &client->getEnv().getClientMap(), nodepos);
3494 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3496 create_formspec_menu(¤t_formspec, client, gamedef,
3497 texture_src, device, fs_src, txt_dst, client);
3499 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3501 // Report right click to server
3503 camera->setDigging(1); // right click animation (always shown for feedback)
3505 // If the wielded item has node placement prediction,
3507 bool placed = nodePlacementPrediction(*client,
3509 nodepos, neighbourpos);
3513 client->interact(3, pointed);
3515 soundmaker->m_player_rightpunch_sound =
3516 playeritem_def.sound_place;
3518 soundmaker->m_player_rightpunch_sound =
3522 if (playeritem_def.node_placement_prediction == "" ||
3523 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable)
3524 client->interact(3, pointed); // Report to server
3530 void Game::handlePointingAtObject(GameRunData *runData,
3531 const PointedThing &pointed,
3532 const ItemStack &playeritem,
3533 const v3f &player_position,
3536 infotext = narrow_to_wide(runData->selected_object->infoText());
3538 if (infotext == L"" && show_debug) {
3539 infotext = narrow_to_wide(runData->selected_object->debugInfoText());
3542 if (input->getLeftState()) {
3543 bool do_punch = false;
3544 bool do_punch_damage = false;
3546 if (runData->object_hit_delay_timer <= 0.0) {
3548 do_punch_damage = true;
3549 runData->object_hit_delay_timer = object_hit_delay;
3552 if (input->getLeftClicked())
3556 infostream << "Left-clicked object" << std::endl;
3557 runData->left_punch = true;
3560 if (do_punch_damage) {
3561 // Report direct punch
3562 v3f objpos = runData->selected_object->getPosition();
3563 v3f dir = (objpos - player_position).normalize();
3565 bool disable_send = runData->selected_object->directReportPunch(
3566 dir, &playeritem, runData->time_from_last_punch);
3567 runData->time_from_last_punch = 0;
3570 client->interact(0, pointed);
3572 } else if (input->getRightClicked()) {
3573 infostream << "Right-clicked object" << std::endl;
3574 client->interact(3, pointed); // place
3579 void Game::handleDigging(GameRunData *runData,
3580 const PointedThing &pointed, const v3s16 &nodepos,
3581 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3583 if (!runData->digging) {
3584 infostream << "Started digging" << std::endl;
3585 client->interact(0, pointed);
3586 runData->digging = true;
3587 runData->ldown_for_dig = true;
3590 LocalPlayer *player = client->getEnv().getLocalPlayer();
3591 ClientMap &map = client->getEnv().getClientMap();
3592 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3594 // NOTE: Similar piece of code exists on the server side for
3596 // Get digging parameters
3597 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3598 &playeritem_toolcap);
3600 // If can't dig, try hand
3601 if (!params.diggable) {
3602 const ItemDefinition &hand = itemdef_manager->get("");
3603 const ToolCapabilities *tp = hand.tool_capabilities;
3606 params = getDigParams(nodedef_manager->get(n).groups, tp);
3609 if (params.diggable == false) {
3610 // I guess nobody will wait for this long
3611 runData->dig_time_complete = 10000000.0;
3613 runData->dig_time_complete = params.time;
3615 if (m_cache_enable_particles) {
3616 const ContentFeatures &features =
3617 client->getNodeDefManager()->get(n);
3618 addPunchingParticles(gamedef, smgr, player,
3619 client->getEnv(), nodepos, features.tiles);
3623 if (runData->dig_time_complete >= 0.001) {
3624 runData->dig_index = (float)crack_animation_length
3626 / runData->dig_time_complete;
3628 // This is for torches
3629 runData->dig_index = crack_animation_length;
3632 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3634 if (sound_dig.exists() && params.diggable) {
3635 if (sound_dig.name == "__group") {
3636 if (params.main_group != "") {
3637 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3638 soundmaker->m_player_leftpunch_sound.name =
3639 std::string("default_dig_") +
3643 soundmaker->m_player_leftpunch_sound = sound_dig;
3647 // Don't show cracks if not diggable
3648 if (runData->dig_time_complete >= 100000.0) {
3649 } else if (runData->dig_index < crack_animation_length) {
3650 //TimeTaker timer("client.setTempMod");
3651 //infostream<<"dig_index="<<dig_index<<std::endl;
3652 client->setCrack(runData->dig_index, nodepos);
3654 infostream << "Digging completed" << std::endl;
3655 client->interact(2, pointed);
3656 client->setCrack(-1, v3s16(0, 0, 0));
3657 bool is_valid_position;
3658 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3659 if (is_valid_position)
3660 client->removeNode(nodepos);
3662 if (m_cache_enable_particles) {
3663 const ContentFeatures &features =
3664 client->getNodeDefManager()->get(wasnode);
3666 (gamedef, smgr, player, client->getEnv(),
3667 nodepos, features.tiles);
3670 runData->dig_time = 0;
3671 runData->digging = false;
3673 runData->nodig_delay_timer =
3674 runData->dig_time_complete / (float)crack_animation_length;
3676 // We don't want a corresponding delay to
3677 // very time consuming nodes
3678 if (runData->nodig_delay_timer > 0.3)
3679 runData->nodig_delay_timer = 0.3;
3681 // We want a slight delay to very little
3682 // time consuming nodes
3683 const float mindelay = 0.15;
3685 if (runData->nodig_delay_timer < mindelay)
3686 runData->nodig_delay_timer = mindelay;
3688 // Send event to trigger sound
3689 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3690 gamedef->event()->put(e);
3693 if (runData->dig_time_complete < 100000.0) {
3694 runData->dig_time += dtime;
3696 runData->dig_time = 0;
3697 client->setCrack(-1, nodepos);
3700 camera->setDigging(0); // left click animation
3704 void Game::updateFrame(std::vector<aabb3f> &highlight_boxes,
3705 ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
3706 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam)
3708 LocalPlayer *player = client->getEnv().getLocalPlayer();
3714 if (draw_control->range_all) {
3715 runData->fog_range = 100000 * BS;
3717 runData->fog_range = draw_control->wanted_range * BS
3718 + 0.0 * MAP_BLOCKSIZE * BS;
3719 runData->fog_range = MYMIN(
3721 (draw_control->farthest_drawn + 20) * BS);
3722 runData->fog_range *= 0.9;
3726 Calculate general brightness
3728 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3729 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3730 float direct_brightness;
3733 if (g_settings->getBool("free_move")) {
3734 direct_brightness = time_brightness;
3735 sunlight_seen = true;
3737 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3738 float old_brightness = sky->getBrightness();
3739 direct_brightness = client->getEnv().getClientMap()
3740 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3741 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3745 float time_of_day = runData->time_of_day;
3746 float time_of_day_smooth = runData->time_of_day_smooth;
3748 time_of_day = client->getEnv().getTimeOfDayF();
3750 const float maxsm = 0.05;
3751 const float todsm = 0.05;
3753 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3754 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3755 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3756 time_of_day_smooth = time_of_day;
3758 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3759 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3760 + (time_of_day + 1.0) * todsm;
3762 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3763 + time_of_day * todsm;
3765 runData->time_of_day = time_of_day;
3766 runData->time_of_day_smooth = time_of_day_smooth;
3768 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3769 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3770 player->getPitch());
3776 v3f player_position = player->getPosition();
3777 if (sky->getCloudsVisible()) {
3778 clouds->setVisible(true);
3779 clouds->step(dtime);
3780 clouds->update(v2f(player_position.X, player_position.Z),
3781 sky->getCloudColor());
3783 clouds->setVisible(false);
3791 allparticles_step(dtime);
3792 allparticlespawners_step(dtime, client->getEnv());
3798 if (m_cache_enable_fog && !flags.force_fog_off) {
3801 video::EFT_FOG_LINEAR,
3802 runData->fog_range * 0.4,
3803 runData->fog_range * 1.0,
3811 video::EFT_FOG_LINEAR,
3821 Get chat messages from client
3824 v2u32 screensize = driver->getScreenSize();
3826 updateChat(*client, dtime, flags.show_debug, screensize,
3827 flags.show_chat, runData->profiler_current_page,
3828 *chat_backend, guitext_chat);
3834 if (client->getPlayerItem() != runData->new_playeritem)
3835 client->selectPlayerItem(runData->new_playeritem);
3837 // Update local inventory if it has changed
3838 if (client->getLocalInventoryUpdated()) {
3839 //infostream<<"Updating local inventory"<<std::endl;
3840 client->getLocalInventory(*local_inventory);
3841 runData->update_wielded_item_trigger = true;
3844 if (runData->update_wielded_item_trigger) {
3845 // Update wielded tool
3846 InventoryList *mlist = local_inventory->getList("main");
3848 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
3849 ItemStack item = mlist->getItem(client->getPlayerItem());
3850 camera->wield(item);
3852 runData->update_wielded_item_trigger = false;
3856 Update block draw list every 200ms or when camera direction has
3859 runData->update_draw_list_timer += dtime;
3861 v3f camera_direction = camera->getDirection();
3862 if (runData->update_draw_list_timer >= 0.2
3863 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3864 || flags.camera_offset_changed) {
3865 runData->update_draw_list_timer = 0;
3866 client->getEnv().getClientMap().updateDrawList(driver);
3867 runData->update_draw_list_last_cam_dir = camera_direction;
3870 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
3873 make sure menu is on top
3874 1. Delete formspec menu reference if menu was removed
3875 2. Else, make sure formspec menu is on top
3877 if (current_formspec) {
3878 if (current_formspec->getReferenceCount() == 1) {
3879 current_formspec->drop();
3880 current_formspec = NULL;
3881 } else if (!noMenuActive()) {
3882 guiroot->bringToFront(current_formspec);
3890 video::SColor skycolor = sky->getSkyColor();
3892 TimeTaker tt_draw("mainloop: draw");
3894 TimeTaker timer("beginScene");
3895 driver->beginScene(true, true, skycolor);
3896 stats->beginscenetime = timer.stop(true);
3899 draw_scene(driver, smgr, *camera, *client, player, *hud, guienv,
3900 highlight_boxes, screensize, skycolor, flags.show_hud);
3905 if (flags.show_profiler_graph)
3906 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3911 if (runData->damage_flash > 0.0) {
3912 video::SColor color(std::min(runData->damage_flash, 180.0f),
3916 driver->draw2DRectangle(color,
3917 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3920 runData->damage_flash -= 100.0 * dtime;
3926 if (player->hurt_tilt_timer > 0.0) {
3927 player->hurt_tilt_timer -= dtime * 5;
3929 if (player->hurt_tilt_timer < 0)
3930 player->hurt_tilt_strength = 0;
3937 TimeTaker timer("endScene");
3939 stats->endscenetime = timer.stop(true);
3942 stats->drawtime = tt_draw.stop(true);
3943 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
3947 void Game::updateGui(float *statustext_time, const RunStats &stats,
3948 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
3949 const CameraOrientation &cam)
3951 v2u32 screensize = driver->getScreenSize();
3952 LocalPlayer *player = client->getEnv().getLocalPlayer();
3953 v3f player_position = player->getPosition();
3955 if (flags.show_debug) {
3956 static float drawtime_avg = 0;
3957 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
3959 u16 fps = 1.0 / stats.dtime_jitter.avg;
3960 //s32 fps = driver->getFPS();
3962 std::ostringstream os(std::ios_base::binary);
3964 << "Minetest " << minetest_version_hash
3966 << " (R: range_all=" << draw_control->range_all << ")"
3967 << std::setprecision(0)
3968 << " drawtime = " << drawtime_avg
3969 << std::setprecision(1)
3970 << ", dtime_jitter = "
3971 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
3972 << std::setprecision(1)
3973 << ", v_range = " << draw_control->wanted_range
3974 << std::setprecision(3)
3975 << ", RTT = " << client->getRTT();
3976 guitext->setText(narrow_to_wide(os.str()).c_str());
3977 guitext->setVisible(true);
3978 } else if (flags.show_hud || flags.show_chat) {
3979 std::ostringstream os(std::ios_base::binary);
3980 os << "Minetest " << minetest_version_hash;
3981 guitext->setText(narrow_to_wide(os.str()).c_str());
3982 guitext->setVisible(true);
3984 guitext->setVisible(false);
3987 if (guitext->isVisible()) {
3988 core::rect<s32> rect(
3990 screensize.X, 5 + g_fontengine->getTextHeight()
3992 guitext->setRelativePosition(rect);
3995 if (flags.show_debug) {
3996 std::ostringstream os(std::ios_base::binary);
3997 os << std::setprecision(1) << std::fixed
3998 << "(" << (player_position.X / BS)
3999 << ", " << (player_position.Y / BS)
4000 << ", " << (player_position.Z / BS)
4001 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4002 << ") (seed = " << ((u64)client->getMapSeed())
4005 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4006 ClientMap &map = client->getEnv().getClientMap();
4007 const INodeDefManager *nodedef = client->getNodeDefManager();
4008 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4009 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4010 const ContentFeatures &features = nodedef->get(n);
4011 os << " (pointing_at = " << nodedef->get(n).name
4012 << " - " << features.tiledef[0].name.c_str()
4017 guitext2->setText(narrow_to_wide(os.str()).c_str());
4018 guitext2->setVisible(true);
4020 core::rect<s32> rect(
4021 5, 5 + g_fontengine->getTextHeight(),
4022 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4024 guitext2->setRelativePosition(rect);
4026 guitext2->setVisible(false);
4029 guitext_info->setText(infotext.c_str());
4030 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4032 float statustext_time_max = 1.5;
4034 if (!statustext.empty()) {
4035 *statustext_time += dtime;
4037 if (*statustext_time >= statustext_time_max) {
4039 *statustext_time = 0;
4043 guitext_status->setText(statustext.c_str());
4044 guitext_status->setVisible(!statustext.empty());
4046 if (!statustext.empty()) {
4047 s32 status_width = guitext_status->getTextWidth();
4048 s32 status_height = guitext_status->getTextHeight();
4049 s32 status_y = screensize.Y - 150;
4050 s32 status_x = (screensize.X - status_width) / 2;
4051 core::rect<s32> rect(
4052 status_x , status_y - status_height,
4053 status_x + status_width, status_y
4055 guitext_status->setRelativePosition(rect);
4058 video::SColor initial_color(255, 0, 0, 0);
4060 if (guienv->getSkin())
4061 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4063 video::SColor final_color = initial_color;
4064 final_color.setAlpha(0);
4065 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4066 initial_color, final_color,
4067 pow(*statustext_time / statustext_time_max, 2.0f));
4068 guitext_status->setOverrideColor(fade_color);
4069 guitext_status->enableOverrideColor(true);
4074 /* Log times and stuff for visualization */
4075 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4077 Profiler::GraphValues values;
4078 g_profiler->graphGet(values);
4084 /****************************************************************************
4086 ****************************************************************************/
4088 /* On some computers framerate doesn't seem to be automatically limited
4090 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4092 // not using getRealTime is necessary for wine
4093 device->getTimer()->tick(); // Maker sure device time is up-to-date
4094 u32 time = device->getTimer()->getTime();
4096 u32 last_time = fps_timings->last_time;
4098 if (time > last_time) // Make sure time hasn't overflowed
4099 fps_timings->busy_time = time - last_time;
4101 fps_timings->busy_time = 0;
4103 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4104 ? g_settings->getFloat("pause_fps_max")
4105 : g_settings->getFloat("fps_max"));
4107 if (fps_timings->busy_time < frametime_min) {
4108 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4109 device->sleep(fps_timings->sleep_time);
4111 fps_timings->sleep_time = 0;
4114 /* Get the new value of the device timer. Note that device->sleep() may
4115 * not sleep for the entire requested time as sleep may be interrupted and
4116 * therefore it is arguably more accurate to get the new time from the
4117 * device rather than calculating it by adding sleep_time to time.
4120 device->getTimer()->tick(); // Update device timer
4121 time = device->getTimer()->getTime();
4123 if (time > last_time) // Make sure last_time hasn't overflowed
4124 *dtime = (time - last_time) / 1000.0;
4128 fps_timings->last_time = time;
4132 void Game::showOverlayMessage(const char *msg, float dtime,
4133 int percent, bool draw_clouds)
4135 wchar_t *text = wgettext(msg);
4136 draw_load_screen(text, device, guienv, dtime, percent, draw_clouds);
4141 /****************************************************************************
4143 ****************************************************************************/
4145 void Game::extendedResourceCleanup()
4147 // Extended resource accounting
4148 infostream << "Irrlicht resources after cleanup:" << std::endl;
4149 infostream << "\tRemaining meshes : "
4150 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4151 infostream << "\tRemaining textures : "
4152 << driver->getTextureCount() << std::endl;
4154 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4155 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4156 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4160 clearTextureNameCache();
4161 infostream << "\tRemaining materials: "
4162 << driver-> getMaterialRendererCount()
4163 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4168 /****************************************************************************
4169 extern function for launching the game
4170 ****************************************************************************/
4172 void the_game(bool *kill,
4174 InputHandler *input,
4175 IrrlichtDevice *device,
4177 const std::string &map_dir,
4178 const std::string &playername,
4179 const std::string &password,
4180 const std::string &address, // If empty local server is created
4183 std::wstring &error_message,
4184 ChatBackend &chat_backend,
4185 const SubgameSpec &gamespec, // Used for local game
4186 bool simple_singleplayer_mode)
4190 /* Make a copy of the server address because if a local singleplayer server
4191 * is created then this is updated and we don't want to change the value
4192 * passed to us by the calling function
4194 std::string server_address = address;
4198 if (game.startup(kill, random_input, input, device, map_dir,
4199 playername, password, &server_address, port,
4200 &error_message, &chat_backend, gamespec,
4201 simple_singleplayer_mode)) {
4207 } catch (SerializationError &e) {
4208 error_message = L"A serialization error occurred:\n"
4209 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
4210 L" running a different version of Minetest.";
4211 errorstream << wide_to_narrow(error_message) << std::endl;
4212 } catch (ServerError &e) {
4213 error_message = narrow_to_wide(e.what());
4214 errorstream << "ServerError: " << e.what() << std::endl;
4215 } catch (ModError &e) {
4216 errorstream << "ModError: " << e.what() << std::endl;
4217 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");