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;
815 void onSettingsChange(const std::string &name)
817 if (name == "enable_fog")
818 m_fogEnabled = g_settings->getBool("enable_fog");
821 static void SettingsCallback(const std::string name, void *userdata)
823 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
826 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
827 f32 *fog_range, Client *client) :
829 m_force_fog_off(force_fog_off),
830 m_fog_range(fog_range),
833 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
834 m_fogEnabled = g_settings->getBool("enable_fog");
837 ~GameGlobalShaderConstantSetter()
839 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
842 virtual void onSetConstants(video::IMaterialRendererServices *services,
849 video::SColor bgcolor = m_sky->getBgColor();
850 video::SColorf bgcolorf(bgcolor);
851 float bgcolorfa[4] = {
857 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
860 float fog_distance = 10000 * BS;
862 if (m_fogEnabled && !*m_force_fog_off)
863 fog_distance = *m_fog_range;
865 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
868 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
869 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
870 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
872 u32 animation_timer = porting::getTimeMs() % 100000;
873 float animation_timer_f = (float)animation_timer / 100000.0;
874 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
875 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
877 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
878 v3f eye_position = player->getEyePosition();
879 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
880 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
882 // Uniform sampler layers
886 // before 1.8 there isn't a "integer interface", only float
887 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
888 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
889 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
890 services->setPixelShaderConstant("useNormalmap" , (irr::f32 *)&layer2, 1);
892 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
893 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
894 services->setPixelShaderConstant("useNormalmap" , (irr::s32 *)&layer2, 1);
899 bool nodePlacementPrediction(Client &client,
900 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
902 std::string prediction = playeritem_def.node_placement_prediction;
903 INodeDefManager *nodedef = client.ndef();
904 ClientMap &map = client.getEnv().getClientMap();
906 bool is_valid_position;
908 node = map.getNodeNoEx(nodepos, &is_valid_position);
909 if (!is_valid_position)
912 if (prediction != "" && !nodedef->get(node).rightclickable) {
913 verbosestream << "Node placement prediction for "
914 << playeritem_def.name << " is "
915 << prediction << std::endl;
916 v3s16 p = neighbourpos;
918 // Place inside node itself if buildable_to
919 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
920 if (is_valid_position)
922 if (nodedef->get(n_under).buildable_to)
925 node = map.getNodeNoEx(p, &is_valid_position);
926 if (is_valid_position &&!nodedef->get(node).buildable_to)
931 // Find id of predicted node
933 bool found = nodedef->getId(prediction, id);
936 errorstream << "Node placement prediction failed for "
937 << playeritem_def.name << " (places "
939 << ") - Name not known" << std::endl;
943 // Predict param2 for facedir and wallmounted nodes
946 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
947 v3s16 dir = nodepos - neighbourpos;
949 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
950 param2 = dir.Y < 0 ? 1 : 0;
951 } else if (abs(dir.X) > abs(dir.Z)) {
952 param2 = dir.X < 0 ? 3 : 2;
954 param2 = dir.Z < 0 ? 5 : 4;
958 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
959 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
961 if (abs(dir.X) > abs(dir.Z)) {
962 param2 = dir.X < 0 ? 3 : 1;
964 param2 = dir.Z < 0 ? 2 : 0;
970 //Check attachment if node is in group attached_node
971 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
972 static v3s16 wallmounted_dirs[8] = {
982 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
983 pp = p + wallmounted_dirs[param2];
985 pp = p + v3s16(0, -1, 0);
987 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
991 // Add node to client map
992 MapNode n(id, 0, param2);
995 LocalPlayer *player = client.getEnv().getLocalPlayer();
997 // Dont place node when player would be inside new node
998 // NOTE: This is to be eventually implemented by a mod as client-side Lua
999 if (!nodedef->get(n).walkable ||
1000 g_settings->getBool("enable_build_where_you_stand") ||
1001 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
1002 (nodedef->get(n).walkable &&
1003 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
1004 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
1006 // This triggers the required mesh update too
1007 client.addNode(p, n);
1010 } catch (InvalidPositionException &e) {
1011 errorstream << "Node placement prediction failed for "
1012 << playeritem_def.name << " (places "
1014 << ") - Position not loaded" << std::endl;
1021 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1022 InventoryManager *invmgr, IGameDef *gamedef,
1023 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1024 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1027 if (*cur_formspec == 0) {
1028 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1029 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1030 (*cur_formspec)->doPause = false;
1033 Caution: do not call (*cur_formspec)->drop() here --
1034 the reference might outlive the menu, so we will
1035 periodically check if *cur_formspec is the only
1036 remaining reference (i.e. the menu was removed)
1037 and delete it in that case.
1041 (*cur_formspec)->setFormSource(fs_src);
1042 (*cur_formspec)->setTextDest(txt_dest);
1046 #define SIZE_TAG "size[11,5.5]"
1048 static void show_chat_menu(GUIFormSpecMenu **cur_formspec,
1049 InventoryManager *invmgr, IGameDef *gamedef,
1050 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1051 Client *client, std::string text)
1053 std::string formspec =
1054 FORMSPEC_VERSION_STRING
1056 "field[3,2.35;6,0.5;f_text;;" + text + "]"
1057 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
1061 /* Note: FormspecFormSource and LocalFormspecHandler
1062 * are deleted by guiFormSpecMenu */
1063 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1064 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
1066 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1069 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1070 InventoryManager *invmgr, IGameDef *gamedef,
1071 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1073 std::string formspec =
1074 std::string(FORMSPEC_VERSION_STRING) +
1076 "bgcolor[#320000b4;true]"
1077 "label[4.85,1.35;" + gettext("You died.") + "]"
1078 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1082 /* Note: FormspecFormSource and LocalFormspecHandler
1083 * are deleted by guiFormSpecMenu */
1084 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1085 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1087 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1090 /******************************************************************************/
1091 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1092 InventoryManager *invmgr, IGameDef *gamedef,
1093 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1094 bool singleplayermode)
1097 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1098 "No menu visible:\n"
1099 "- single tap: button activate\n"
1100 "- double tap: place/use\n"
1101 "- slide finger: look around\n"
1102 "Menu/Inventory visible:\n"
1103 "- double tap (outside):\n"
1105 "- touch stack, touch slot:\n"
1107 "- touch&drag, tap 2nd finger\n"
1108 " --> place single item to slot\n"
1111 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1113 "- Space: jump/climb\n"
1114 "- Shift: sneak/go down\n"
1117 "- Mouse: turn/look\n"
1118 "- Mouse left: dig/punch\n"
1119 "- Mouse right: place/use\n"
1120 "- Mouse wheel: select item\n"
1125 float ypos = singleplayermode ? 0.5 : 0.1;
1126 std::ostringstream os;
1128 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1129 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1130 << wide_to_narrow(wstrgettext("Continue")) << "]";
1132 if (!singleplayermode) {
1133 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1134 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1138 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1139 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1140 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1141 << wide_to_narrow(wstrgettext("Change Keys")) << "]";
1143 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1144 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1145 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1146 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1147 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1148 << "textarea[0.4,0.25;3.5,6;;" << "Minetest\n"
1149 << minetest_build_info << "\n"
1150 << "path_user = " << wrap_rows(porting::path_user, 20)
1154 /* Note: FormspecFormSource and LocalFormspecHandler *
1155 * are deleted by guiFormSpecMenu */
1156 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1157 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1159 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1160 (*cur_formspec)->setFocus(L"btn_continue");
1161 (*cur_formspec)->doPause = true;
1164 /******************************************************************************/
1165 static void updateChat(Client &client, f32 dtime, bool show_debug,
1166 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1167 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1169 // Add chat log output for errors to be shown in chat
1170 static LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1172 // Get new messages from error log buffer
1173 while (!chat_log_error_buf.empty()) {
1174 chat_backend.addMessage(L"", narrow_to_wide(chat_log_error_buf.get()));
1177 // Get new messages from client
1178 std::wstring message;
1180 while (client.getChatMessage(message)) {
1181 chat_backend.addUnparsedMessage(message);
1184 // Remove old messages
1185 chat_backend.step(dtime);
1187 // Display all messages in a static text element
1188 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1189 std::wstring recent_chat = chat_backend.getRecentChat();
1190 unsigned int line_height = g_fontengine->getLineHeight();
1192 guitext_chat->setText(recent_chat.c_str());
1194 // Update gui element size and position
1195 s32 chat_y = 5 + line_height;
1198 chat_y += line_height;
1200 // first pass to calculate height of text to be set
1201 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1202 porting::getWindowSize().X - 20);
1203 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1204 guitext_chat->setRelativePosition(rect);
1206 //now use real height of text and adjust rect according to this size
1207 rect = core::rect<s32>(10, chat_y, width,
1208 chat_y + guitext_chat->getTextHeight());
1211 guitext_chat->setRelativePosition(rect);
1212 // Don't show chat if disabled or empty or profiler is enabled
1213 guitext_chat->setVisible(
1214 show_chat && recent_chat_count != 0 && !show_profiler);
1218 /****************************************************************************
1219 Fast key cache for main game loop
1220 ****************************************************************************/
1222 /* This is faster than using getKeySetting with the tradeoff that functions
1223 * using it must make sure that it's initialised before using it and there is
1224 * no error handling (for example bounds checking). This is really intended for
1225 * use only in the main running loop of the client (the_game()) where the faster
1226 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1227 * (e.g. formspecs) should continue using getKeySetting().
1231 KeyCache() { populate(); }
1245 KEYMAP_ID_INVENTORY,
1252 KEYMAP_ID_SCREENSHOT,
1253 KEYMAP_ID_TOGGLE_HUD,
1254 KEYMAP_ID_TOGGLE_CHAT,
1255 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1256 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1257 KEYMAP_ID_TOGGLE_DEBUG,
1258 KEYMAP_ID_TOGGLE_PROFILER,
1259 KEYMAP_ID_CAMERA_MODE,
1260 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1261 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1262 KEYMAP_ID_RANGESELECT,
1264 KEYMAP_ID_QUICKTUNE_NEXT,
1265 KEYMAP_ID_QUICKTUNE_PREV,
1266 KEYMAP_ID_QUICKTUNE_INC,
1267 KEYMAP_ID_QUICKTUNE_DEC,
1269 KEYMAP_ID_DEBUG_STACKS,
1271 // Fake keycode for array size and internal checks
1272 KEYMAP_INTERNAL_ENUM_COUNT
1279 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1282 void KeyCache::populate()
1284 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1285 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1286 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1287 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1288 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1289 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1290 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1292 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1293 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1294 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1295 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1296 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1297 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1298 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1299 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1300 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1301 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1302 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1303 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1304 = getKeySetting("keymap_toggle_force_fog_off");
1305 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1306 = getKeySetting("keymap_toggle_update_camera");
1307 key[KEYMAP_ID_TOGGLE_DEBUG]
1308 = getKeySetting("keymap_toggle_debug");
1309 key[KEYMAP_ID_TOGGLE_PROFILER]
1310 = getKeySetting("keymap_toggle_profiler");
1311 key[KEYMAP_ID_CAMERA_MODE]
1312 = getKeySetting("keymap_camera_mode");
1313 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1314 = getKeySetting("keymap_increase_viewing_range_min");
1315 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1316 = getKeySetting("keymap_decrease_viewing_range_min");
1317 key[KEYMAP_ID_RANGESELECT]
1318 = getKeySetting("keymap_rangeselect");
1320 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1321 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1322 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1323 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1325 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1329 /****************************************************************************
1331 ****************************************************************************/
1333 const float object_hit_delay = 0.2;
1336 u32 last_time, busy_time, sleep_time;
1340 /* The reason the following structs are not anonymous structs within the
1341 * class is that they are not used by the majority of member functions and
1342 * many functions that do require objects of thse types do not modify them
1343 * (so they can be passed as a const qualified parameter)
1345 struct CameraOrientation {
1346 f32 camera_yaw; // "right/left"
1347 f32 camera_pitch; // "up/down"
1350 struct GameRunData {
1353 PointedThing pointed_old;
1357 bool update_wielded_item_trigger;
1358 bool reset_jump_timer;
1359 float nodig_delay_timer;
1361 float dig_time_complete;
1362 float repeat_rightclick_timer;
1363 float object_hit_delay_timer;
1364 float time_from_last_punch;
1365 ClientActiveObject *selected_object;
1369 float update_draw_list_timer;
1370 float statustext_time;
1374 v3f update_draw_list_last_cam_dir;
1376 u32 profiler_current_page;
1377 u32 profiler_max_page; // Number of pages
1380 float time_of_day_smooth;
1384 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1392 Jitter dtime_jitter, busy_time_jitter;
1395 /* Flags that can, or may, change during main game loop
1397 struct VolatileRunFlags {
1403 bool show_profiler_graph;
1404 bool disable_camera_update;
1405 bool first_loop_after_window_activation;
1406 bool camera_offset_changed;
1410 /****************************************************************************
1412 ****************************************************************************/
1414 /* This is not intended to be a public class. If a public class becomes
1415 * desirable then it may be better to create another 'wrapper' class that
1416 * hides most of the stuff in this class (nothing in this class is required
1417 * by any other file) but exposes the public methods/data only.
1425 bool startup(bool *kill,
1427 InputHandler *input,
1428 IrrlichtDevice *device,
1429 const std::string &map_dir,
1430 const std::string &playername,
1431 const std::string &password,
1432 // If address is "", local server is used and address is updated
1433 std::string *address,
1435 std::wstring *error_message,
1436 ChatBackend *chat_backend,
1437 const SubgameSpec &gamespec, // Used for local game
1438 bool simple_singleplayer_mode);
1445 void extendedResourceCleanup();
1447 // Basic initialisation
1448 bool init(const std::string &map_dir, std::string *address,
1450 const SubgameSpec &gamespec);
1452 bool createSingleplayerServer(const std::string map_dir,
1453 const SubgameSpec &gamespec, u16 port, std::string *address);
1456 bool createClient(const std::string &playername,
1457 const std::string &password, std::string *address, u16 port,
1458 std::wstring *error_message);
1459 bool initGui(std::wstring *error_message);
1461 // Client connection
1462 bool connectToServer(const std::string &playername,
1463 const std::string &password, std::string *address, u16 port,
1464 bool *connect_ok, bool *aborted);
1465 bool getServerContent(bool *aborted);
1469 void updateInteractTimers(GameRunData *args, f32 dtime);
1470 bool checkConnection();
1471 bool handleCallbacks();
1472 void processQueues();
1473 void updateProfilers(const GameRunData &run_data, const RunStats &stats,
1474 const FpsControl &draw_times, f32 dtime);
1475 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1477 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1479 void processUserInput(VolatileRunFlags *flags, GameRunData *interact_args,
1481 void processKeyboardInput(VolatileRunFlags *flags,
1482 float *statustext_time,
1484 bool *reset_jump_timer,
1485 u32 *profiler_current_page,
1486 u32 profiler_max_page);
1487 void processItemSelection(u16 *new_playeritem);
1489 void dropSelectedItem();
1490 void openInventory();
1492 void toggleFreeMove(float *statustext_time);
1493 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1494 void toggleFast(float *statustext_time);
1495 void toggleNoClip(float *statustext_time);
1497 void toggleChat(float *statustext_time, bool *flag);
1498 void toggleHud(float *statustext_time, bool *flag);
1499 void toggleFog(float *statustext_time, bool *flag);
1500 void toggleDebug(float *statustext_time, bool *show_debug,
1501 bool *show_profiler_graph);
1502 void toggleUpdateCamera(float *statustext_time, bool *flag);
1503 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1504 u32 profiler_max_page);
1506 void increaseViewRange(float *statustext_time);
1507 void decreaseViewRange(float *statustext_time);
1508 void toggleFullViewRange(float *statustext_time);
1510 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1511 void updateCameraOrientation(CameraOrientation *cam,
1512 const VolatileRunFlags &flags);
1513 void updatePlayerControl(const CameraOrientation &cam);
1514 void step(f32 *dtime);
1515 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1516 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1517 float time_from_last_punch);
1518 void updateSound(f32 dtime);
1519 void processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
1520 GameRunData *runData, f32 dtime, bool show_hud,
1522 void handlePointingAtNode(GameRunData *runData,
1523 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1524 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1525 void handlePointingAtObject(GameRunData *runData,
1526 const PointedThing &pointed, const ItemStack &playeritem,
1527 const v3f &player_position, bool show_debug);
1528 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1529 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1531 void updateFrame(std::vector<aabb3f> &highlight_boxes, ProfilerGraph *graph,
1532 RunStats *stats, GameRunData *runData,
1533 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1534 void updateGui(float *statustext_time, const RunStats &stats,
1535 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1536 const CameraOrientation &cam);
1537 void updateProfilerGraphs(ProfilerGraph *graph);
1540 void limitFps(FpsControl *fps_timings, f32 *dtime);
1542 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1543 bool draw_clouds = true);
1546 InputHandler *input;
1551 IWritableTextureSource *texture_src;
1552 IWritableShaderSource *shader_src;
1554 // When created, these will be filled with data received from the server
1555 IWritableItemDefManager *itemdef_manager;
1556 IWritableNodeDefManager *nodedef_manager;
1558 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1559 ISoundManager *sound;
1560 bool sound_is_dummy;
1561 SoundMaker *soundmaker;
1563 ChatBackend *chat_backend;
1565 GUIFormSpecMenu *current_formspec;
1567 EventManager *eventmgr;
1568 QuicktuneShortcutter *quicktune;
1570 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1571 MapDrawControl *draw_control;
1573 Clouds *clouds; // Free using ->Drop()
1574 Sky *sky; // Free using ->Drop()
1575 Inventory *local_inventory;
1579 This class does take ownership/responsibily for cleaning up etc of any of
1580 these items (e.g. device)
1582 IrrlichtDevice *device;
1583 video::IVideoDriver *driver;
1584 scene::ISceneManager *smgr;
1586 std::wstring *error_message;
1587 IGameDef *gamedef; // Convenience (same as *client)
1588 scene::ISceneNode *skybox;
1591 bool simple_singleplayer_mode;
1594 /* Pre-calculated values
1596 int crack_animation_length;
1600 gui::IGUIStaticText *guitext; // First line of debug text
1601 gui::IGUIStaticText *guitext2; // Second line of debug text
1602 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1603 gui::IGUIStaticText *guitext_status;
1604 gui::IGUIStaticText *guitext_chat; // Chat text
1605 gui::IGUIStaticText *guitext_profiler; // Profiler text
1607 std::wstring infotext;
1608 std::wstring statustext;
1612 IntervalLimiter profiler_interval;
1614 /* TODO: Add a callback function so these can be updated when a setting
1615 * changes. At this point in time it doesn't matter (e.g. /set
1616 * is documented to change server settings only)
1618 * TODO: Local caching of settings is not optimal and should at some stage
1619 * be updated to use a global settings object for getting thse values
1620 * (as opposed to the this local caching). This can be addressed in
1623 bool m_cache_doubletap_jump;
1624 bool m_cache_enable_node_highlighting;
1625 bool m_cache_enable_clouds;
1626 bool m_cache_enable_particles;
1627 bool m_cache_enable_fog;
1628 f32 m_cache_mouse_sensitivity;
1629 f32 m_repeat_right_click_time;
1637 itemdef_manager(NULL),
1638 nodedef_manager(NULL),
1640 sound_is_dummy(false),
1643 current_formspec(NULL),
1646 gui_chat_console(NULL),
1651 local_inventory(NULL),
1654 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
1655 m_cache_enable_node_highlighting = g_settings->getBool("enable_node_highlighting");
1656 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
1657 m_cache_enable_particles = g_settings->getBool("enable_particles");
1658 m_cache_enable_fog = g_settings->getBool("enable_fog");
1659 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
1660 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
1662 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
1667 /****************************************************************************
1669 ****************************************************************************/
1675 if (!sound_is_dummy)
1678 delete server; // deleted first to stop all server threads
1681 delete local_inventory;
1687 delete nodedef_manager;
1688 delete itemdef_manager;
1689 delete draw_control;
1691 extendedResourceCleanup();
1694 bool Game::startup(bool *kill,
1696 InputHandler *input,
1697 IrrlichtDevice *device,
1698 const std::string &map_dir,
1699 const std::string &playername,
1700 const std::string &password,
1701 std::string *address, // can change if simple_singleplayer_mode
1703 std::wstring *error_message,
1704 ChatBackend *chat_backend,
1705 const SubgameSpec &gamespec,
1706 bool simple_singleplayer_mode)
1709 this->device = device;
1711 this->error_message = error_message;
1712 this->random_input = random_input;
1713 this->input = input;
1714 this->chat_backend = chat_backend;
1715 this->simple_singleplayer_mode = simple_singleplayer_mode;
1717 driver = device->getVideoDriver();
1718 smgr = device->getSceneManager();
1720 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1722 if (!init(map_dir, address, port, gamespec))
1725 if (!createClient(playername, password, address, port, error_message))
1734 ProfilerGraph graph;
1735 RunStats stats = { 0 };
1736 CameraOrientation cam_view = { 0 };
1737 GameRunData runData = { 0 };
1738 FpsControl draw_times = { 0 };
1739 VolatileRunFlags flags = { 0 };
1740 f32 dtime; // in seconds
1742 runData.time_from_last_punch = 10.0;
1743 runData.profiler_max_page = 3;
1744 runData.update_wielded_item_trigger = true;
1746 flags.show_chat = true;
1747 flags.show_hud = true;
1748 flags.show_debug = g_settings->getBool("show_debug");
1749 flags.invert_mouse = g_settings->getBool("invert_mouse");
1750 flags.first_loop_after_window_activation = true;
1752 /* Clear the profiler */
1753 Profiler::GraphValues dummyvalues;
1754 g_profiler->graphGet(dummyvalues);
1756 draw_times.last_time = device->getTimer()->getTime();
1758 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1760 &flags.force_fog_off,
1764 std::vector<aabb3f> highlight_boxes;
1766 set_light_table(g_settings->getFloat("display_gamma"));
1768 while (device->run() && !(*kill || g_gamecallback->shutdown_requested)) {
1770 /* Must be called immediately after a device->run() call because it
1771 * uses device->getTimer()->getTime()
1773 limitFps(&draw_times, &dtime);
1775 updateStats(&stats, draw_times, dtime);
1776 updateInteractTimers(&runData, dtime);
1778 if (!checkConnection())
1780 if (!handleCallbacks())
1786 hud->resizeHotbar();
1788 updateProfilers(runData, stats, draw_times, dtime);
1789 processUserInput(&flags, &runData, dtime);
1790 // Update camera before player movement to avoid camera lag of one frame
1791 updateCameraDirection(&cam_view, &flags);
1792 updatePlayerControl(cam_view);
1794 processClientEvents(&cam_view, &runData.damage_flash);
1795 updateCamera(&flags, draw_times.busy_time, dtime,
1796 runData.time_from_last_punch);
1798 processPlayerInteraction(highlight_boxes, &runData, dtime,
1799 flags.show_hud, flags.show_debug);
1800 updateFrame(highlight_boxes, &graph, &stats, &runData, dtime,
1802 updateProfilerGraphs(&graph);
1807 void Game::shutdown()
1809 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1814 if (gui_chat_console)
1815 gui_chat_console->drop();
1821 while (g_menumgr.menuCount() > 0) {
1822 g_menumgr.m_stack.front()->setVisible(false);
1823 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1826 if (current_formspec) {
1827 current_formspec->drop();
1828 current_formspec = NULL;
1831 chat_backend->addMessage(L"", L"# Disconnected.");
1832 chat_backend->addMessage(L"", L"");
1836 while (!client->isShutdown()) {
1837 assert(texture_src != NULL);
1838 assert(shader_src != NULL);
1839 texture_src->processQueue();
1840 shader_src->processQueue();
1848 /****************************************************************************
1850 ****************************************************************************/
1853 const std::string &map_dir,
1854 std::string *address,
1856 const SubgameSpec &gamespec)
1858 showOverlayMessage(wgettext("Loading..."), 0, 0);
1860 texture_src = createTextureSource(device);
1861 shader_src = createShaderSource(device);
1863 itemdef_manager = createItemDefManager();
1864 nodedef_manager = createNodeDefManager();
1866 eventmgr = new EventManager();
1867 quicktune = new QuicktuneShortcutter();
1869 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1870 && eventmgr && quicktune))
1876 // Create a server if not connecting to an existing one
1877 if (*address == "") {
1878 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1885 bool Game::initSound()
1888 if (g_settings->getBool("enable_sound")) {
1889 infostream << "Attempting to use OpenAL audio" << std::endl;
1890 sound = createOpenALSoundManager(&soundfetcher);
1892 infostream << "Failed to initialize OpenAL audio" << std::endl;
1894 infostream << "Sound disabled." << std::endl;
1898 infostream << "Using dummy audio." << std::endl;
1899 sound = &dummySoundManager;
1900 sound_is_dummy = true;
1903 soundmaker = new SoundMaker(sound, nodedef_manager);
1907 soundmaker->registerReceiver(eventmgr);
1912 bool Game::createSingleplayerServer(const std::string map_dir,
1913 const SubgameSpec &gamespec, u16 port, std::string *address)
1915 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1917 std::string bind_str = g_settings->get("bind_address");
1918 Address bind_addr(0, 0, 0, 0, port);
1920 if (g_settings->getBool("ipv6_server")) {
1921 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1925 bind_addr.Resolve(bind_str.c_str());
1926 } catch (ResolveError &e) {
1927 infostream << "Resolving bind address \"" << bind_str
1928 << "\" failed: " << e.what()
1929 << " -- Listening on all addresses." << std::endl;
1932 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1933 *error_message = L"Unable to listen on " +
1934 narrow_to_wide(bind_addr.serializeString()) +
1935 L" because IPv6 is disabled";
1936 errorstream << wide_to_narrow(*error_message) << std::endl;
1940 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1941 bind_addr.isIPv6());
1943 server->start(bind_addr);
1948 bool Game::createClient(const std::string &playername,
1949 const std::string &password, std::string *address, u16 port,
1950 std::wstring *error_message)
1952 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1954 draw_control = new MapDrawControl;
1958 bool could_connect, connect_aborted;
1960 if (!connectToServer(playername, password, address, port,
1961 &could_connect, &connect_aborted))
1964 if (!could_connect) {
1965 if (*error_message == L"" && !connect_aborted) {
1966 // Should not happen if error messages are set properly
1967 *error_message = L"Connection failed for unknown reason";
1968 errorstream << wide_to_narrow(*error_message) << std::endl;
1973 if (!getServerContent(&connect_aborted)) {
1974 if (*error_message == L"" && !connect_aborted) {
1975 // Should not happen if error messages are set properly
1976 *error_message = L"Connection failed for unknown reason";
1977 errorstream << wide_to_narrow(*error_message) << std::endl;
1982 // Update cached textures, meshes and materials
1983 client->afterContentReceived(device, g_fontengine->getFont());
1987 camera = new Camera(smgr, *draw_control, gamedef);
1988 if (!camera || !camera->successfullyCreated(*error_message))
1993 if (m_cache_enable_clouds) {
1994 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1996 *error_message = L"Memory allocation error";
1997 *error_message += narrow_to_wide(" (clouds)");
1998 errorstream << wide_to_narrow(*error_message) << std::endl;
2005 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2006 skybox = NULL; // This is used/set later on in the main run loop
2008 local_inventory = new Inventory(itemdef_manager);
2010 if (!(sky && local_inventory)) {
2011 *error_message = L"Memory allocation error";
2012 *error_message += narrow_to_wide(" (sky or local inventory)");
2013 errorstream << wide_to_narrow(*error_message) << std::endl;
2017 /* Pre-calculated values
2019 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2021 v2u32 size = t->getOriginalSize();
2022 crack_animation_length = size.Y / size.X;
2024 crack_animation_length = 5;
2027 if (!initGui(error_message))
2030 /* Set window caption
2032 core::stringw str = L"Minetest [";
2033 str += driver->getName();
2035 device->setWindowCaption(str.c_str());
2037 LocalPlayer *player = client->getEnv().getLocalPlayer();
2038 player->hurt_tilt_timer = 0;
2039 player->hurt_tilt_strength = 0;
2041 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2044 *error_message = L"Memory error: could not create HUD";
2045 errorstream << wide_to_narrow(*error_message) << std::endl;
2052 bool Game::initGui(std::wstring *error_message)
2054 // First line of debug text
2055 guitext = guienv->addStaticText(
2057 core::rect<s32>(0, 0, 0, 0),
2058 false, false, guiroot);
2060 // Second line of debug text
2061 guitext2 = guienv->addStaticText(
2063 core::rect<s32>(0, 0, 0, 0),
2064 false, false, guiroot);
2066 // At the middle of the screen
2067 // Object infos are shown in this
2068 guitext_info = guienv->addStaticText(
2070 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2071 false, true, guiroot);
2073 // Status text (displays info when showing and hiding GUI stuff, etc.)
2074 guitext_status = guienv->addStaticText(
2076 core::rect<s32>(0, 0, 0, 0),
2077 false, false, guiroot);
2078 guitext_status->setVisible(false);
2081 guitext_chat = guienv->addStaticText(
2083 core::rect<s32>(0, 0, 0, 0),
2084 //false, false); // Disable word wrap as of now
2085 false, true, guiroot);
2086 // Remove stale "recent" chat messages from previous connections
2087 chat_backend->clearRecentChat();
2089 // Chat backend and console
2090 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2091 -1, chat_backend, client);
2092 if (!gui_chat_console) {
2093 *error_message = L"Could not allocate memory for chat console";
2094 errorstream << wide_to_narrow(*error_message) << std::endl;
2098 // Profiler text (size is updated when text is updated)
2099 guitext_profiler = guienv->addStaticText(
2101 core::rect<s32>(0, 0, 0, 0),
2102 false, false, guiroot);
2103 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2104 guitext_profiler->setVisible(false);
2105 guitext_profiler->setWordWrap(true);
2107 #ifdef HAVE_TOUCHSCREENGUI
2109 if (g_touchscreengui)
2110 g_touchscreengui->init(texture_src, porting::getDisplayDensity());
2117 bool Game::connectToServer(const std::string &playername,
2118 const std::string &password, std::string *address, u16 port,
2119 bool *connect_ok, bool *aborted)
2121 *connect_ok = false; // Let's not be overly optimistic
2123 bool local_server_mode = false;
2125 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2127 Address connect_address(0, 0, 0, 0, port);
2130 connect_address.Resolve(address->c_str());
2132 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2133 //connect_address.Resolve("localhost");
2134 if (connect_address.isIPv6()) {
2135 IPv6AddressBytes addr_bytes;
2136 addr_bytes.bytes[15] = 1;
2137 connect_address.setAddress(&addr_bytes);
2139 connect_address.setAddress(127, 0, 0, 1);
2141 local_server_mode = true;
2143 } catch (ResolveError &e) {
2144 *error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
2145 errorstream << wide_to_narrow(*error_message) << std::endl;
2149 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2150 *error_message = L"Unable to connect to " +
2151 narrow_to_wide(connect_address.serializeString()) +
2152 L" because IPv6 is disabled";
2153 errorstream << wide_to_narrow(*error_message) << std::endl;
2157 client = new Client(device,
2158 playername.c_str(), password,
2159 *draw_control, texture_src, shader_src,
2160 itemdef_manager, nodedef_manager, sound, eventmgr,
2161 connect_address.isIPv6());
2166 gamedef = client; // Client acts as our GameDef
2168 infostream << "Connecting to server at ";
2169 connect_address.print(&infostream);
2170 infostream << std::endl;
2172 client->connect(connect_address, *address,
2173 simple_singleplayer_mode || local_server_mode);
2176 Wait for server to accept connection
2182 FpsControl fps_control = { 0 };
2183 f32 dtime; // in seconds
2185 while (device->run()) {
2187 limitFps(&fps_control, &dtime);
2189 // Update client and server
2190 client->step(dtime);
2193 server->step(dtime);
2196 if (client->getState() == LC_Init) {
2202 if (client->accessDenied()) {
2203 *error_message = L"Access denied. Reason: "
2204 + client->accessDeniedReason();
2205 errorstream << wide_to_narrow(*error_message) << std::endl;
2209 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2211 infostream << "Connect aborted [Escape]" << std::endl;
2216 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2218 } catch (con::PeerNotFoundException &e) {
2219 // TODO: Should something be done here? At least an info/error
2227 bool Game::getServerContent(bool *aborted)
2231 FpsControl fps_control = { 0 };
2232 f32 dtime; // in seconds
2234 while (device->run()) {
2236 limitFps(&fps_control, &dtime);
2238 // Update client and server
2239 client->step(dtime);
2242 server->step(dtime);
2245 if (client->mediaReceived() && client->itemdefReceived() &&
2246 client->nodedefReceived()) {
2251 if (client->accessDenied()) {
2252 *error_message = L"Access denied. Reason: "
2253 + client->accessDeniedReason();
2254 errorstream << wide_to_narrow(*error_message) << std::endl;
2258 if (client->getState() < LC_Init) {
2259 *error_message = L"Client disconnected";
2260 errorstream << wide_to_narrow(*error_message) << std::endl;
2264 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2266 infostream << "Connect aborted [Escape]" << std::endl;
2273 if (!client->itemdefReceived()) {
2274 const wchar_t *text = wgettext("Item definitions...");
2276 draw_load_screen(text, device, guienv, dtime, progress);
2278 } else if (!client->nodedefReceived()) {
2279 const wchar_t *text = wgettext("Node definitions...");
2281 draw_load_screen(text, device, guienv, dtime, progress);
2284 std::stringstream message;
2285 message.precision(3);
2286 message << gettext("Media...");
2288 if ((USE_CURL == 0) ||
2289 (!g_settings->getBool("enable_remote_media_server"))) {
2290 float cur = client->getCurRate();
2291 std::string cur_unit = gettext(" KB/s");
2295 cur_unit = gettext(" MB/s");
2298 message << " ( " << cur << cur_unit << " )";
2301 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2302 draw_load_screen(narrow_to_wide(message.str()), device,
2303 guienv, dtime, progress);
2312 /****************************************************************************
2314 ****************************************************************************/
2316 inline void Game::updateInteractTimers(GameRunData *args, f32 dtime)
2318 if (args->nodig_delay_timer >= 0)
2319 args->nodig_delay_timer -= dtime;
2321 if (args->object_hit_delay_timer >= 0)
2322 args->object_hit_delay_timer -= dtime;
2324 args->time_from_last_punch += dtime;
2328 /* returns false if game should exit, otherwise true
2330 inline bool Game::checkConnection()
2332 if (client->accessDenied()) {
2333 *error_message = L"Access denied. Reason: "
2334 + client->accessDeniedReason();
2335 errorstream << wide_to_narrow(*error_message) << std::endl;
2343 /* returns false if game should exit, otherwise true
2345 inline bool Game::handleCallbacks()
2347 if (g_gamecallback->disconnect_requested) {
2348 g_gamecallback->disconnect_requested = false;
2352 if (g_gamecallback->changepassword_requested) {
2353 (new GUIPasswordChange(guienv, guiroot, -1,
2354 &g_menumgr, client))->drop();
2355 g_gamecallback->changepassword_requested = false;
2358 if (g_gamecallback->changevolume_requested) {
2359 (new GUIVolumeChange(guienv, guiroot, -1,
2360 &g_menumgr, client))->drop();
2361 g_gamecallback->changevolume_requested = false;
2364 if (g_gamecallback->keyconfig_requested) {
2365 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2366 &g_menumgr))->drop();
2367 g_gamecallback->keyconfig_requested = false;
2370 if (g_gamecallback->keyconfig_changed) {
2371 keycache.populate(); // update the cache with new settings
2372 g_gamecallback->keyconfig_changed = false;
2379 void Game::processQueues()
2381 texture_src->processQueue();
2382 itemdef_manager->processQueue(gamedef);
2383 shader_src->processQueue();
2387 void Game::updateProfilers(const GameRunData &run_data, const RunStats &stats,
2388 const FpsControl &draw_times, f32 dtime)
2390 float profiler_print_interval =
2391 g_settings->getFloat("profiler_print_interval");
2392 bool print_to_log = true;
2394 if (profiler_print_interval == 0) {
2395 print_to_log = false;
2396 profiler_print_interval = 5;
2399 if (profiler_interval.step(dtime, profiler_print_interval)) {
2401 infostream << "Profiler:" << std::endl;
2402 g_profiler->print(infostream);
2405 update_profiler_gui(guitext_profiler, g_fontengine,
2406 run_data.profiler_current_page, run_data.profiler_max_page,
2407 driver->getScreenSize().Height);
2409 g_profiler->clear();
2412 addProfilerGraphs(stats, draw_times, dtime);
2416 void Game::addProfilerGraphs(const RunStats &stats,
2417 const FpsControl &draw_times, f32 dtime)
2419 g_profiler->graphAdd("mainloop_other",
2420 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2422 if (draw_times.sleep_time != 0)
2423 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2424 g_profiler->graphAdd("mainloop_dtime", dtime);
2426 g_profiler->add("Elapsed time", dtime);
2427 g_profiler->avg("FPS", 1. / dtime);
2431 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2438 /* Time average and jitter calculation
2440 jp = &stats->dtime_jitter;
2441 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2443 jitter = dtime - jp->avg;
2445 if (jitter > jp->max)
2448 jp->counter += dtime;
2450 if (jp->counter > 0.0) {
2452 jp->max_sample = jp->max;
2453 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2457 /* Busytime average and jitter calculation
2459 jp = &stats->busy_time_jitter;
2460 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2462 jitter = draw_times.busy_time - jp->avg;
2464 if (jitter > jp->max)
2466 if (jitter < jp->min)
2469 jp->counter += dtime;
2471 if (jp->counter > 0.0) {
2473 jp->max_sample = jp->max;
2474 jp->min_sample = jp->min;
2482 /****************************************************************************
2484 ****************************************************************************/
2486 void Game::processUserInput(VolatileRunFlags *flags,
2487 GameRunData *interact_args, f32 dtime)
2489 // Reset input if window not active or some menu is active
2490 if (device->isWindowActive() == false
2491 || noMenuActive() == false
2492 || guienv->hasFocus(gui_chat_console)) {
2496 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2497 gui_chat_console->closeConsoleAtOnce();
2500 // Input handler step() (used by the random input generator)
2503 #ifdef HAVE_TOUCHSCREENGUI
2505 if (g_touchscreengui) {
2506 g_touchscreengui->step(dtime);
2512 if (current_formspec != 0)
2513 current_formspec->getAndroidUIInput();
2517 // Increase timer for double tap of "keymap_jump"
2518 if (m_cache_doubletap_jump && interact_args->jump_timer <= 0.2)
2519 interact_args->jump_timer += dtime;
2521 processKeyboardInput(
2523 &interact_args->statustext_time,
2524 &interact_args->jump_timer,
2525 &interact_args->reset_jump_timer,
2526 &interact_args->profiler_current_page,
2527 interact_args->profiler_max_page);
2529 processItemSelection(&interact_args->new_playeritem);
2533 void Game::processKeyboardInput(VolatileRunFlags *flags,
2534 float *statustext_time,
2536 bool *reset_jump_timer,
2537 u32 *profiler_current_page,
2538 u32 profiler_max_page)
2541 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2543 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2545 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2547 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2548 show_pause_menu(¤t_formspec, client, gamedef, texture_src, device,
2549 simple_singleplayer_mode);
2550 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2551 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2553 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2554 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2556 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2558 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2559 toggleFreeMove(statustext_time);
2560 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2561 toggleFreeMoveAlt(statustext_time, jump_timer);
2562 *reset_jump_timer = true;
2563 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2564 toggleFast(statustext_time);
2565 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2566 toggleNoClip(statustext_time);
2567 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2568 client->makeScreenshot(device);
2569 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2570 toggleHud(statustext_time, &flags->show_hud);
2571 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2572 toggleChat(statustext_time, &flags->show_chat);
2573 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2574 toggleFog(statustext_time, &flags->force_fog_off);
2575 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2576 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2577 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2578 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2579 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2580 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2581 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2582 increaseViewRange(statustext_time);
2583 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2584 decreaseViewRange(statustext_time);
2585 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2586 toggleFullViewRange(statustext_time);
2587 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
2589 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
2591 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
2593 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
2595 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2596 // Print debug stacks
2597 dstream << "-----------------------------------------"
2599 dstream << DTIME << "Printing debug stacks:" << std::endl;
2600 dstream << "-----------------------------------------"
2602 debug_stacks_print();
2605 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2606 *reset_jump_timer = false;
2612 if (quicktune->hasMessage()) {
2613 std::string msg = quicktune->getMessage();
2614 statustext = narrow_to_wide(msg);
2615 *statustext_time = 0;
2620 void Game::processItemSelection(u16 *new_playeritem)
2622 LocalPlayer *player = client->getEnv().getLocalPlayer();
2624 /* Item selection using mouse wheel
2626 *new_playeritem = client->getPlayerItem();
2628 s32 wheel = input->getMouseWheel();
2629 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2630 player->hud_hotbar_itemcount - 1);
2633 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2635 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2639 /* Item selection using keyboard
2641 for (u16 i = 0; i < 10; i++) {
2642 static const KeyPress *item_keys[10] = {
2643 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2644 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2645 NumberKey + 9, NumberKey + 0,
2648 if (input->wasKeyDown(*item_keys[i])) {
2649 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2650 *new_playeritem = i;
2651 infostream << "Selected item: " << new_playeritem << std::endl;
2659 void Game::dropSelectedItem()
2661 IDropAction *a = new IDropAction();
2663 a->from_inv.setCurrentPlayer();
2664 a->from_list = "main";
2665 a->from_i = client->getPlayerItem();
2666 client->inventoryAction(a);
2670 void Game::openInventory()
2673 * Don't permit to open inventory is CAO or player doesn't exists.
2674 * This prevent showing an empty inventory at player load
2677 LocalPlayer *player = client->getEnv().getLocalPlayer();
2678 if (player == NULL || player->getCAO() == NULL)
2681 infostream << "the_game: " << "Launching inventory" << std::endl;
2683 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2684 TextDest *txt_dst = new TextDestPlayerInventory(client);
2686 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2687 device, fs_src, txt_dst, client);
2689 InventoryLocation inventoryloc;
2690 inventoryloc.setCurrentPlayer();
2691 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2695 void Game::openConsole()
2697 if (!gui_chat_console->isOpenInhibited()) {
2698 // Open up to over half of the screen
2699 gui_chat_console->openConsole(0.6);
2700 guienv->setFocus(gui_chat_console);
2705 void Game::toggleFreeMove(float *statustext_time)
2707 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2709 bool free_move = !g_settings->getBool("free_move");
2710 g_settings->set("free_move", bool_to_cstr(free_move));
2712 *statustext_time = 0;
2713 statustext = msg[free_move];
2714 if (free_move && !client->checkPrivilege("fly"))
2715 statustext += L" (note: no 'fly' privilege)";
2719 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2721 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2722 toggleFreeMove(statustext_time);
2726 void Game::toggleFast(float *statustext_time)
2728 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2729 bool fast_move = !g_settings->getBool("fast_move");
2730 g_settings->set("fast_move", bool_to_cstr(fast_move));
2732 *statustext_time = 0;
2733 statustext = msg[fast_move];
2735 if (fast_move && !client->checkPrivilege("fast"))
2736 statustext += L" (note: no 'fast' privilege)";
2740 void Game::toggleNoClip(float *statustext_time)
2742 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2743 bool noclip = !g_settings->getBool("noclip");
2744 g_settings->set("noclip", bool_to_cstr(noclip));
2746 *statustext_time = 0;
2747 statustext = msg[noclip];
2749 if (noclip && !client->checkPrivilege("noclip"))
2750 statustext += L" (note: no 'noclip' privilege)";
2754 void Game::toggleChat(float *statustext_time, bool *flag)
2756 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2759 *statustext_time = 0;
2760 statustext = msg[*flag];
2764 void Game::toggleHud(float *statustext_time, bool *flag)
2766 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2769 *statustext_time = 0;
2770 statustext = msg[*flag];
2771 if (g_settings->getBool("enable_node_highlighting"))
2772 client->setHighlighted(client->getHighlighted(), *flag);
2776 void Game::toggleFog(float *statustext_time, bool *flag)
2778 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2781 *statustext_time = 0;
2782 statustext = msg[*flag];
2786 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2787 bool *show_profiler_graph)
2789 // Initial / 3x toggle: Chat only
2790 // 1x toggle: Debug text with chat
2791 // 2x toggle: Debug text with profiler graph
2794 *show_profiler_graph = false;
2795 statustext = L"Debug info shown";
2796 } else if (*show_profiler_graph) {
2797 *show_debug = false;
2798 *show_profiler_graph = false;
2799 statustext = L"Debug info and profiler graph hidden";
2801 *show_profiler_graph = true;
2802 statustext = L"Profiler graph shown";
2804 *statustext_time = 0;
2808 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
2810 static const wchar_t *msg[] = {
2811 L"Camera update enabled",
2812 L"Camera update disabled"
2816 *statustext_time = 0;
2817 statustext = msg[*flag];
2821 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
2822 u32 profiler_max_page)
2824 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
2826 // FIXME: This updates the profiler with incomplete values
2827 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
2828 profiler_max_page, driver->getScreenSize().Height);
2830 if (*profiler_current_page != 0) {
2831 std::wstringstream sstr;
2832 sstr << "Profiler shown (page " << *profiler_current_page
2833 << " of " << profiler_max_page << ")";
2834 statustext = sstr.str();
2836 statustext = L"Profiler hidden";
2838 *statustext_time = 0;
2842 void Game::increaseViewRange(float *statustext_time)
2844 s16 range = g_settings->getS16("viewing_range_nodes_min");
2845 s16 range_new = range + 10;
2846 g_settings->set("viewing_range_nodes_min", itos(range_new));
2847 statustext = narrow_to_wide("Minimum viewing range changed to "
2849 *statustext_time = 0;
2853 void Game::decreaseViewRange(float *statustext_time)
2855 s16 range = g_settings->getS16("viewing_range_nodes_min");
2856 s16 range_new = range - 10;
2861 g_settings->set("viewing_range_nodes_min", itos(range_new));
2862 statustext = narrow_to_wide("Minimum viewing range changed to "
2864 *statustext_time = 0;
2868 void Game::toggleFullViewRange(float *statustext_time)
2870 static const wchar_t *msg[] = {
2871 L"Disabled full viewing range",
2872 L"Enabled full viewing range"
2875 draw_control->range_all = !draw_control->range_all;
2876 infostream << msg[draw_control->range_all] << std::endl;
2877 statustext = msg[draw_control->range_all];
2878 *statustext_time = 0;
2882 void Game::updateCameraDirection(CameraOrientation *cam,
2883 VolatileRunFlags *flags)
2885 if ((device->isWindowActive() && noMenuActive()) || random_input) {
2888 if (!random_input) {
2889 // Mac OSX gets upset if this is set every frame
2890 if (device->getCursorControl()->isVisible())
2891 device->getCursorControl()->setVisible(false);
2895 if (flags->first_loop_after_window_activation)
2896 flags->first_loop_after_window_activation = false;
2898 updateCameraOrientation(cam, *flags);
2900 input->setMousePos((driver->getScreenSize().Width / 2),
2901 (driver->getScreenSize().Height / 2));
2905 // Mac OSX gets upset if this is set every frame
2906 if (device->getCursorControl()->isVisible() == false)
2907 device->getCursorControl()->setVisible(true);
2910 if (!flags->first_loop_after_window_activation)
2911 flags->first_loop_after_window_activation = true;
2917 void Game::updateCameraOrientation(CameraOrientation *cam,
2918 const VolatileRunFlags &flags)
2920 #ifdef HAVE_TOUCHSCREENGUI
2921 if (g_touchscreengui) {
2922 cam->camera_yaw = g_touchscreengui->getYaw();
2923 cam->camera_pitch = g_touchscreengui->getPitch();
2926 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
2927 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
2929 if (flags.invert_mouse
2930 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2934 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
2935 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
2937 #ifdef HAVE_TOUCHSCREENGUI
2941 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2945 void Game::updatePlayerControl(const CameraOrientation &cam)
2947 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2949 PlayerControl control(
2950 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
2951 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
2952 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
2953 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
2954 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
2955 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
2956 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
2957 input->getLeftState(),
2958 input->getRightState(),
2962 client->setPlayerControl(control);
2963 LocalPlayer *player = client->getEnv().getLocalPlayer();
2964 player->keyPressed =
2965 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
2966 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
2967 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
2968 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
2969 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
2970 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
2971 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
2972 ( (u32)(input->getLeftState() & 0x1) << 7) |
2973 ( (u32)(input->getRightState() & 0x1) << 8
2980 inline void Game::step(f32 *dtime)
2982 bool can_be_and_is_paused =
2983 (simple_singleplayer_mode && g_menumgr.pausesGame());
2985 if (can_be_and_is_paused) { // This is for a singleplayer server
2986 *dtime = 0; // No time passes
2988 if (server != NULL) {
2989 //TimeTaker timer("server->step(dtime)");
2990 server->step(*dtime);
2993 //TimeTaker timer("client.step(dtime)");
2994 client->step(*dtime);
2999 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3001 ClientEvent event = client->getClientEvent();
3003 LocalPlayer *player = client->getEnv().getLocalPlayer();
3005 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3007 if (event.type == CE_PLAYER_DAMAGE &&
3008 client->getHP() != 0) {
3009 //u16 damage = event.player_damage.amount;
3010 //infostream<<"Player damage: "<<damage<<std::endl;
3012 *damage_flash += 100.0;
3013 *damage_flash += 8.0 * event.player_damage.amount;
3015 player->hurt_tilt_timer = 1.5;
3016 player->hurt_tilt_strength = event.player_damage.amount / 4;
3017 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3019 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3020 gamedef->event()->put(e);
3021 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3022 cam->camera_yaw = event.player_force_move.yaw;
3023 cam->camera_pitch = event.player_force_move.pitch;
3024 } else if (event.type == CE_DEATHSCREEN) {
3025 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3028 chat_backend->addMessage(L"", L"You died.");
3030 /* Handle visualization */
3032 player->hurt_tilt_timer = 0;
3033 player->hurt_tilt_strength = 0;
3035 } else if (event.type == CE_SHOW_FORMSPEC) {
3036 FormspecFormSource *fs_src =
3037 new FormspecFormSource(*(event.show_formspec.formspec));
3038 TextDestPlayerInventory *txt_dst =
3039 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3041 create_formspec_menu(¤t_formspec, client, gamedef,
3042 texture_src, device, fs_src, txt_dst, client);
3044 delete(event.show_formspec.formspec);
3045 delete(event.show_formspec.formname);
3046 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3047 (event.type == CE_ADD_PARTICLESPAWNER) ||
3048 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3049 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3051 } else if (event.type == CE_HUDADD) {
3052 u32 id = event.hudadd.id;
3054 LocalPlayer *player = client->getEnv().getLocalPlayer();
3055 HudElement *e = player->getHud(id);
3058 delete event.hudadd.pos;
3059 delete event.hudadd.name;
3060 delete event.hudadd.scale;
3061 delete event.hudadd.text;
3062 delete event.hudadd.align;
3063 delete event.hudadd.offset;
3064 delete event.hudadd.world_pos;
3065 delete event.hudadd.size;
3070 e->type = (HudElementType)event.hudadd.type;
3071 e->pos = *event.hudadd.pos;
3072 e->name = *event.hudadd.name;
3073 e->scale = *event.hudadd.scale;
3074 e->text = *event.hudadd.text;
3075 e->number = event.hudadd.number;
3076 e->item = event.hudadd.item;
3077 e->dir = event.hudadd.dir;
3078 e->align = *event.hudadd.align;
3079 e->offset = *event.hudadd.offset;
3080 e->world_pos = *event.hudadd.world_pos;
3081 e->size = *event.hudadd.size;
3083 u32 new_id = player->addHud(e);
3084 //if this isn't true our huds aren't consistent
3085 assert(new_id == id);
3087 delete event.hudadd.pos;
3088 delete event.hudadd.name;
3089 delete event.hudadd.scale;
3090 delete event.hudadd.text;
3091 delete event.hudadd.align;
3092 delete event.hudadd.offset;
3093 delete event.hudadd.world_pos;
3094 delete event.hudadd.size;
3095 } else if (event.type == CE_HUDRM) {
3096 HudElement *e = player->removeHud(event.hudrm.id);
3100 } else if (event.type == CE_HUDCHANGE) {
3101 u32 id = event.hudchange.id;
3102 HudElement *e = player->getHud(id);
3105 delete event.hudchange.v3fdata;
3106 delete event.hudchange.v2fdata;
3107 delete event.hudchange.sdata;
3108 delete event.hudchange.v2s32data;
3112 switch (event.hudchange.stat) {
3114 e->pos = *event.hudchange.v2fdata;
3118 e->name = *event.hudchange.sdata;
3121 case HUD_STAT_SCALE:
3122 e->scale = *event.hudchange.v2fdata;
3126 e->text = *event.hudchange.sdata;
3129 case HUD_STAT_NUMBER:
3130 e->number = event.hudchange.data;
3134 e->item = event.hudchange.data;
3138 e->dir = event.hudchange.data;
3141 case HUD_STAT_ALIGN:
3142 e->align = *event.hudchange.v2fdata;
3145 case HUD_STAT_OFFSET:
3146 e->offset = *event.hudchange.v2fdata;
3149 case HUD_STAT_WORLD_POS:
3150 e->world_pos = *event.hudchange.v3fdata;
3154 e->size = *event.hudchange.v2s32data;
3158 delete event.hudchange.v3fdata;
3159 delete event.hudchange.v2fdata;
3160 delete event.hudchange.sdata;
3161 delete event.hudchange.v2s32data;
3162 } else if (event.type == CE_SET_SKY) {
3163 sky->setVisible(false);
3170 // Handle according to type
3171 if (*event.set_sky.type == "regular") {
3172 sky->setVisible(true);
3173 } else if (*event.set_sky.type == "skybox" &&
3174 event.set_sky.params->size() == 6) {
3175 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3176 skybox = smgr->addSkyBoxSceneNode(
3177 texture_src->getTexture((*event.set_sky.params)[0]),
3178 texture_src->getTexture((*event.set_sky.params)[1]),
3179 texture_src->getTexture((*event.set_sky.params)[2]),
3180 texture_src->getTexture((*event.set_sky.params)[3]),
3181 texture_src->getTexture((*event.set_sky.params)[4]),
3182 texture_src->getTexture((*event.set_sky.params)[5]));
3184 // Handle everything else as plain color
3186 if (*event.set_sky.type != "plain")
3187 infostream << "Unknown sky type: "
3188 << (*event.set_sky.type) << std::endl;
3190 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3193 delete event.set_sky.bgcolor;
3194 delete event.set_sky.type;
3195 delete event.set_sky.params;
3196 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3197 bool enable = event.override_day_night_ratio.do_override;
3198 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3199 client->getEnv().setDayNightRatioOverride(enable, value);
3205 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3206 f32 dtime, float time_from_last_punch)
3208 LocalPlayer *player = client->getEnv().getLocalPlayer();
3211 For interaction purposes, get info about the held item
3213 - Is it a usable item?
3214 - Can it point to liquids?
3216 ItemStack playeritem;
3218 InventoryList *mlist = local_inventory->getList("main");
3220 if (mlist && client->getPlayerItem() < mlist->getSize())
3221 playeritem = mlist->getItem(client->getPlayerItem());
3224 ToolCapabilities playeritem_toolcap =
3225 playeritem.getToolCapabilities(itemdef_manager);
3227 v3s16 old_camera_offset = camera->getOffset();
3229 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3230 GenericCAO *playercao = player->getCAO();
3232 // If playercao not loaded, don't change camera
3233 if (playercao == NULL)
3236 camera->toggleCameraMode();
3238 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3241 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3242 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3244 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3245 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3247 camera->step(dtime);
3249 v3f camera_position = camera->getPosition();
3250 v3f camera_direction = camera->getDirection();
3251 f32 camera_fov = camera->getFovMax();
3252 v3s16 camera_offset = camera->getOffset();
3254 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3256 if (!flags->disable_camera_update) {
3257 client->getEnv().getClientMap().updateCamera(camera_position,
3258 camera_direction, camera_fov, camera_offset);
3260 if (flags->camera_offset_changed) {
3261 client->updateCameraOffset(camera_offset);
3262 client->getEnv().updateCameraOffset(camera_offset);
3265 clouds->updateCameraOffset(camera_offset);
3271 void Game::updateSound(f32 dtime)
3273 // Update sound listener
3274 v3s16 camera_offset = camera->getOffset();
3275 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3276 v3f(0, 0, 0), // velocity
3277 camera->getDirection(),
3278 camera->getCameraNode()->getUpVector());
3279 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3282 // Update sound maker
3283 soundmaker->step(dtime);
3285 LocalPlayer *player = client->getEnv().getLocalPlayer();
3287 ClientMap &map = client->getEnv().getClientMap();
3288 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3289 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3293 void Game::processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
3294 GameRunData *runData, f32 dtime, bool show_hud, bool show_debug)
3296 LocalPlayer *player = client->getEnv().getLocalPlayer();
3298 ItemStack playeritem;
3300 InventoryList *mlist = local_inventory->getList("main");
3302 if (mlist && client->getPlayerItem() < mlist->getSize())
3303 playeritem = mlist->getItem(client->getPlayerItem());
3306 const ItemDefinition &playeritem_def =
3307 playeritem.getDefinition(itemdef_manager);
3309 v3f player_position = player->getPosition();
3310 v3f camera_position = camera->getPosition();
3311 v3f camera_direction = camera->getDirection();
3312 v3s16 camera_offset = camera->getOffset();
3316 Calculate what block is the crosshair pointing to
3319 f32 d = playeritem_def.range; // max. distance
3320 f32 d_hand = itemdef_manager->get("").range;
3322 if (d < 0 && d_hand >= 0)
3327 core::line3d<f32> shootline;
3329 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3331 shootline = core::line3d<f32>(camera_position,
3332 camera_position + camera_direction * BS * (d + 1));
3335 // prevent player pointing anything in front-view
3336 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3337 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3340 #ifdef HAVE_TOUCHSCREENGUI
3342 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3343 shootline = g_touchscreengui->getShootline();
3344 shootline.start += intToFloat(camera_offset, BS);
3345 shootline.end += intToFloat(camera_offset, BS);
3350 PointedThing pointed = getPointedThing(
3352 client, player_position, camera_direction,
3353 camera_position, shootline, d,
3354 playeritem_def.liquids_pointable,
3355 !runData->ldown_for_dig,
3359 runData->selected_object);
3361 if (pointed != runData->pointed_old) {
3362 infostream << "Pointing at " << pointed.dump() << std::endl;
3364 if (m_cache_enable_node_highlighting) {
3365 if (pointed.type == POINTEDTHING_NODE) {
3366 client->setHighlighted(pointed.node_undersurface, show_hud);
3368 client->setHighlighted(pointed.node_undersurface, false);
3375 - releasing left mouse button
3376 - pointing away from node
3378 if (runData->digging) {
3379 if (input->getLeftReleased()) {
3380 infostream << "Left button released"
3381 << " (stopped digging)" << std::endl;
3382 runData->digging = false;
3383 } else if (pointed != runData->pointed_old) {
3384 if (pointed.type == POINTEDTHING_NODE
3385 && runData->pointed_old.type == POINTEDTHING_NODE
3386 && pointed.node_undersurface
3387 == runData->pointed_old.node_undersurface) {
3388 // Still pointing to the same node, but a different face.
3391 infostream << "Pointing away from node"
3392 << " (stopped digging)" << std::endl;
3393 runData->digging = false;
3397 if (!runData->digging) {
3398 client->interact(1, runData->pointed_old);
3399 client->setCrack(-1, v3s16(0, 0, 0));
3400 runData->dig_time = 0.0;
3404 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3405 runData->ldown_for_dig = false;
3408 runData->left_punch = false;
3410 soundmaker->m_player_leftpunch_sound.name = "";
3412 if (input->getRightState())
3413 runData->repeat_rightclick_timer += dtime;
3415 runData->repeat_rightclick_timer = 0;
3417 if (playeritem_def.usable && input->getLeftState()) {
3418 if (input->getLeftClicked())
3419 client->interact(4, pointed);
3420 } else if (pointed.type == POINTEDTHING_NODE) {
3421 ToolCapabilities playeritem_toolcap =
3422 playeritem.getToolCapabilities(itemdef_manager);
3423 handlePointingAtNode(runData, pointed, playeritem_def,
3424 playeritem_toolcap, dtime);
3425 } else if (pointed.type == POINTEDTHING_OBJECT) {
3426 handlePointingAtObject(runData, pointed, playeritem,
3427 player_position, show_debug);
3428 } else if (input->getLeftState()) {
3429 // When button is held down in air, show continuous animation
3430 runData->left_punch = true;
3433 runData->pointed_old = pointed;
3435 if (runData->left_punch || input->getLeftClicked())
3436 camera->setDigging(0); // left click animation
3438 input->resetLeftClicked();
3439 input->resetRightClicked();
3441 input->resetLeftReleased();
3442 input->resetRightReleased();
3446 void Game::handlePointingAtNode(GameRunData *runData,
3447 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3448 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3450 v3s16 nodepos = pointed.node_undersurface;
3451 v3s16 neighbourpos = pointed.node_abovesurface;
3454 Check information text of node
3457 ClientMap &map = client->getEnv().getClientMap();
3458 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3461 infotext = narrow_to_wide(meta->getString("infotext"));
3463 MapNode n = map.getNodeNoEx(nodepos);
3465 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3466 infotext = L"Unknown node: ";
3467 infotext += narrow_to_wide(nodedef_manager->get(n).name);
3471 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3472 && client->checkPrivilege("interact")) {
3473 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3476 if ((input->getRightClicked() ||
3477 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3478 client->checkPrivilege("interact")) {
3479 runData->repeat_rightclick_timer = 0;
3480 infostream << "Ground right-clicked" << std::endl;
3482 if (meta && meta->getString("formspec") != "" && !random_input
3483 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3484 infostream << "Launching custom inventory view" << std::endl;
3486 InventoryLocation inventoryloc;
3487 inventoryloc.setNodeMeta(nodepos);
3489 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3490 &client->getEnv().getClientMap(), nodepos);
3491 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3493 create_formspec_menu(¤t_formspec, client, gamedef,
3494 texture_src, device, fs_src, txt_dst, client);
3496 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3498 // Report right click to server
3500 camera->setDigging(1); // right click animation (always shown for feedback)
3502 // If the wielded item has node placement prediction,
3504 bool placed = nodePlacementPrediction(*client,
3506 nodepos, neighbourpos);
3510 client->interact(3, pointed);
3512 soundmaker->m_player_rightpunch_sound =
3513 playeritem_def.sound_place;
3515 soundmaker->m_player_rightpunch_sound =
3519 if (playeritem_def.node_placement_prediction == "" ||
3520 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable)
3521 client->interact(3, pointed); // Report to server
3527 void Game::handlePointingAtObject(GameRunData *runData,
3528 const PointedThing &pointed,
3529 const ItemStack &playeritem,
3530 const v3f &player_position,
3533 infotext = narrow_to_wide(runData->selected_object->infoText());
3535 if (infotext == L"" && show_debug) {
3536 infotext = narrow_to_wide(runData->selected_object->debugInfoText());
3539 if (input->getLeftState()) {
3540 bool do_punch = false;
3541 bool do_punch_damage = false;
3543 if (runData->object_hit_delay_timer <= 0.0) {
3545 do_punch_damage = true;
3546 runData->object_hit_delay_timer = object_hit_delay;
3549 if (input->getLeftClicked())
3553 infostream << "Left-clicked object" << std::endl;
3554 runData->left_punch = true;
3557 if (do_punch_damage) {
3558 // Report direct punch
3559 v3f objpos = runData->selected_object->getPosition();
3560 v3f dir = (objpos - player_position).normalize();
3562 bool disable_send = runData->selected_object->directReportPunch(
3563 dir, &playeritem, runData->time_from_last_punch);
3564 runData->time_from_last_punch = 0;
3567 client->interact(0, pointed);
3569 } else if (input->getRightClicked()) {
3570 infostream << "Right-clicked object" << std::endl;
3571 client->interact(3, pointed); // place
3576 void Game::handleDigging(GameRunData *runData,
3577 const PointedThing &pointed, const v3s16 &nodepos,
3578 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3580 if (!runData->digging) {
3581 infostream << "Started digging" << std::endl;
3582 client->interact(0, pointed);
3583 runData->digging = true;
3584 runData->ldown_for_dig = true;
3587 LocalPlayer *player = client->getEnv().getLocalPlayer();
3588 ClientMap &map = client->getEnv().getClientMap();
3589 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3591 // NOTE: Similar piece of code exists on the server side for
3593 // Get digging parameters
3594 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3595 &playeritem_toolcap);
3597 // If can't dig, try hand
3598 if (!params.diggable) {
3599 const ItemDefinition &hand = itemdef_manager->get("");
3600 const ToolCapabilities *tp = hand.tool_capabilities;
3603 params = getDigParams(nodedef_manager->get(n).groups, tp);
3606 if (params.diggable == false) {
3607 // I guess nobody will wait for this long
3608 runData->dig_time_complete = 10000000.0;
3610 runData->dig_time_complete = params.time;
3612 if (m_cache_enable_particles) {
3613 const ContentFeatures &features =
3614 client->getNodeDefManager()->get(n);
3615 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3616 player, nodepos, features.tiles);
3620 if (runData->dig_time_complete >= 0.001) {
3621 runData->dig_index = (float)crack_animation_length
3623 / runData->dig_time_complete;
3625 // This is for torches
3626 runData->dig_index = crack_animation_length;
3629 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3631 if (sound_dig.exists() && params.diggable) {
3632 if (sound_dig.name == "__group") {
3633 if (params.main_group != "") {
3634 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3635 soundmaker->m_player_leftpunch_sound.name =
3636 std::string("default_dig_") +
3640 soundmaker->m_player_leftpunch_sound = sound_dig;
3644 // Don't show cracks if not diggable
3645 if (runData->dig_time_complete >= 100000.0) {
3646 } else if (runData->dig_index < crack_animation_length) {
3647 //TimeTaker timer("client.setTempMod");
3648 //infostream<<"dig_index="<<dig_index<<std::endl;
3649 client->setCrack(runData->dig_index, nodepos);
3651 infostream << "Digging completed" << std::endl;
3652 client->interact(2, pointed);
3653 client->setCrack(-1, v3s16(0, 0, 0));
3654 bool is_valid_position;
3655 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3656 if (is_valid_position)
3657 client->removeNode(nodepos);
3659 if (m_cache_enable_particles) {
3660 const ContentFeatures &features =
3661 client->getNodeDefManager()->get(wasnode);
3662 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3663 player, nodepos, features.tiles);
3666 runData->dig_time = 0;
3667 runData->digging = false;
3669 runData->nodig_delay_timer =
3670 runData->dig_time_complete / (float)crack_animation_length;
3672 // We don't want a corresponding delay to
3673 // very time consuming nodes
3674 if (runData->nodig_delay_timer > 0.3)
3675 runData->nodig_delay_timer = 0.3;
3677 // We want a slight delay to very little
3678 // time consuming nodes
3679 const float mindelay = 0.15;
3681 if (runData->nodig_delay_timer < mindelay)
3682 runData->nodig_delay_timer = mindelay;
3684 // Send event to trigger sound
3685 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3686 gamedef->event()->put(e);
3689 if (runData->dig_time_complete < 100000.0) {
3690 runData->dig_time += dtime;
3692 runData->dig_time = 0;
3693 client->setCrack(-1, nodepos);
3696 camera->setDigging(0); // left click animation
3700 void Game::updateFrame(std::vector<aabb3f> &highlight_boxes,
3701 ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
3702 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam)
3704 LocalPlayer *player = client->getEnv().getLocalPlayer();
3710 if (draw_control->range_all) {
3711 runData->fog_range = 100000 * BS;
3713 runData->fog_range = draw_control->wanted_range * BS
3714 + 0.0 * MAP_BLOCKSIZE * BS;
3715 runData->fog_range = MYMIN(
3717 (draw_control->farthest_drawn + 20) * BS);
3718 runData->fog_range *= 0.9;
3722 Calculate general brightness
3724 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3725 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3726 float direct_brightness;
3729 if (g_settings->getBool("free_move")) {
3730 direct_brightness = time_brightness;
3731 sunlight_seen = true;
3733 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3734 float old_brightness = sky->getBrightness();
3735 direct_brightness = client->getEnv().getClientMap()
3736 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3737 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3741 float time_of_day = runData->time_of_day;
3742 float time_of_day_smooth = runData->time_of_day_smooth;
3744 time_of_day = client->getEnv().getTimeOfDayF();
3746 const float maxsm = 0.05;
3747 const float todsm = 0.05;
3749 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3750 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3751 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3752 time_of_day_smooth = time_of_day;
3754 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3755 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3756 + (time_of_day + 1.0) * todsm;
3758 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3759 + time_of_day * todsm;
3761 runData->time_of_day = time_of_day;
3762 runData->time_of_day_smooth = time_of_day_smooth;
3764 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3765 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3766 player->getPitch());
3772 v3f player_position = player->getPosition();
3773 if (sky->getCloudsVisible()) {
3774 clouds->setVisible(true);
3775 clouds->step(dtime);
3776 clouds->update(v2f(player_position.X, player_position.Z),
3777 sky->getCloudColor());
3779 clouds->setVisible(false);
3786 client->getParticleManager()->step(dtime);
3792 if (m_cache_enable_fog && !flags.force_fog_off) {
3795 video::EFT_FOG_LINEAR,
3796 runData->fog_range * 0.4,
3797 runData->fog_range * 1.0,
3805 video::EFT_FOG_LINEAR,
3815 Get chat messages from client
3818 v2u32 screensize = driver->getScreenSize();
3820 updateChat(*client, dtime, flags.show_debug, screensize,
3821 flags.show_chat, runData->profiler_current_page,
3822 *chat_backend, guitext_chat);
3828 if (client->getPlayerItem() != runData->new_playeritem)
3829 client->selectPlayerItem(runData->new_playeritem);
3831 // Update local inventory if it has changed
3832 if (client->getLocalInventoryUpdated()) {
3833 //infostream<<"Updating local inventory"<<std::endl;
3834 client->getLocalInventory(*local_inventory);
3835 runData->update_wielded_item_trigger = true;
3838 if (runData->update_wielded_item_trigger) {
3839 // Update wielded tool
3840 InventoryList *mlist = local_inventory->getList("main");
3842 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
3843 ItemStack item = mlist->getItem(client->getPlayerItem());
3844 camera->wield(item);
3846 runData->update_wielded_item_trigger = false;
3850 Update block draw list every 200ms or when camera direction has
3853 runData->update_draw_list_timer += dtime;
3855 v3f camera_direction = camera->getDirection();
3856 if (runData->update_draw_list_timer >= 0.2
3857 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3858 || flags.camera_offset_changed) {
3859 runData->update_draw_list_timer = 0;
3860 client->getEnv().getClientMap().updateDrawList(driver);
3861 runData->update_draw_list_last_cam_dir = camera_direction;
3864 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
3867 make sure menu is on top
3868 1. Delete formspec menu reference if menu was removed
3869 2. Else, make sure formspec menu is on top
3871 if (current_formspec) {
3872 if (current_formspec->getReferenceCount() == 1) {
3873 current_formspec->drop();
3874 current_formspec = NULL;
3875 } else if (!noMenuActive()) {
3876 guiroot->bringToFront(current_formspec);
3884 video::SColor skycolor = sky->getSkyColor();
3886 TimeTaker tt_draw("mainloop: draw");
3888 TimeTaker timer("beginScene");
3889 driver->beginScene(true, true, skycolor);
3890 stats->beginscenetime = timer.stop(true);
3893 draw_scene(driver, smgr, *camera, *client, player, *hud, guienv,
3894 highlight_boxes, screensize, skycolor, flags.show_hud);
3899 if (flags.show_profiler_graph)
3900 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3905 if (runData->damage_flash > 0.0) {
3906 video::SColor color(std::min(runData->damage_flash, 180.0f),
3910 driver->draw2DRectangle(color,
3911 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3914 runData->damage_flash -= 100.0 * dtime;
3920 if (player->hurt_tilt_timer > 0.0) {
3921 player->hurt_tilt_timer -= dtime * 5;
3923 if (player->hurt_tilt_timer < 0)
3924 player->hurt_tilt_strength = 0;
3931 TimeTaker timer("endScene");
3933 stats->endscenetime = timer.stop(true);
3936 stats->drawtime = tt_draw.stop(true);
3937 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
3941 void Game::updateGui(float *statustext_time, const RunStats &stats,
3942 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
3943 const CameraOrientation &cam)
3945 v2u32 screensize = driver->getScreenSize();
3946 LocalPlayer *player = client->getEnv().getLocalPlayer();
3947 v3f player_position = player->getPosition();
3949 if (flags.show_debug) {
3950 static float drawtime_avg = 0;
3951 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
3953 u16 fps = 1.0 / stats.dtime_jitter.avg;
3954 //s32 fps = driver->getFPS();
3956 std::ostringstream os(std::ios_base::binary);
3958 << "Minetest " << minetest_version_hash
3960 << " (R: range_all=" << draw_control->range_all << ")"
3961 << std::setprecision(0)
3962 << " drawtime = " << drawtime_avg
3963 << std::setprecision(1)
3964 << ", dtime_jitter = "
3965 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
3966 << std::setprecision(1)
3967 << ", v_range = " << draw_control->wanted_range
3968 << std::setprecision(3)
3969 << ", RTT = " << client->getRTT();
3970 guitext->setText(narrow_to_wide(os.str()).c_str());
3971 guitext->setVisible(true);
3972 } else if (flags.show_hud || flags.show_chat) {
3973 std::ostringstream os(std::ios_base::binary);
3974 os << "Minetest " << minetest_version_hash;
3975 guitext->setText(narrow_to_wide(os.str()).c_str());
3976 guitext->setVisible(true);
3978 guitext->setVisible(false);
3981 if (guitext->isVisible()) {
3982 core::rect<s32> rect(
3984 screensize.X, 5 + g_fontengine->getTextHeight()
3986 guitext->setRelativePosition(rect);
3989 if (flags.show_debug) {
3990 std::ostringstream os(std::ios_base::binary);
3991 os << std::setprecision(1) << std::fixed
3992 << "(" << (player_position.X / BS)
3993 << ", " << (player_position.Y / BS)
3994 << ", " << (player_position.Z / BS)
3995 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
3996 << ") (seed = " << ((u64)client->getMapSeed())
3999 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4000 ClientMap &map = client->getEnv().getClientMap();
4001 const INodeDefManager *nodedef = client->getNodeDefManager();
4002 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4003 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4004 const ContentFeatures &features = nodedef->get(n);
4005 os << " (pointing_at = " << nodedef->get(n).name
4006 << " - " << features.tiledef[0].name.c_str()
4011 guitext2->setText(narrow_to_wide(os.str()).c_str());
4012 guitext2->setVisible(true);
4014 core::rect<s32> rect(
4015 5, 5 + g_fontengine->getTextHeight(),
4016 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4018 guitext2->setRelativePosition(rect);
4020 guitext2->setVisible(false);
4023 guitext_info->setText(infotext.c_str());
4024 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4026 float statustext_time_max = 1.5;
4028 if (!statustext.empty()) {
4029 *statustext_time += dtime;
4031 if (*statustext_time >= statustext_time_max) {
4033 *statustext_time = 0;
4037 guitext_status->setText(statustext.c_str());
4038 guitext_status->setVisible(!statustext.empty());
4040 if (!statustext.empty()) {
4041 s32 status_width = guitext_status->getTextWidth();
4042 s32 status_height = guitext_status->getTextHeight();
4043 s32 status_y = screensize.Y - 150;
4044 s32 status_x = (screensize.X - status_width) / 2;
4045 core::rect<s32> rect(
4046 status_x , status_y - status_height,
4047 status_x + status_width, status_y
4049 guitext_status->setRelativePosition(rect);
4052 video::SColor initial_color(255, 0, 0, 0);
4054 if (guienv->getSkin())
4055 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4057 video::SColor final_color = initial_color;
4058 final_color.setAlpha(0);
4059 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4060 initial_color, final_color,
4061 pow(*statustext_time / statustext_time_max, 2.0f));
4062 guitext_status->setOverrideColor(fade_color);
4063 guitext_status->enableOverrideColor(true);
4068 /* Log times and stuff for visualization */
4069 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4071 Profiler::GraphValues values;
4072 g_profiler->graphGet(values);
4078 /****************************************************************************
4080 ****************************************************************************/
4082 /* On some computers framerate doesn't seem to be automatically limited
4084 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4086 // not using getRealTime is necessary for wine
4087 device->getTimer()->tick(); // Maker sure device time is up-to-date
4088 u32 time = device->getTimer()->getTime();
4090 u32 last_time = fps_timings->last_time;
4092 if (time > last_time) // Make sure time hasn't overflowed
4093 fps_timings->busy_time = time - last_time;
4095 fps_timings->busy_time = 0;
4097 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4098 ? g_settings->getFloat("pause_fps_max")
4099 : g_settings->getFloat("fps_max"));
4101 if (fps_timings->busy_time < frametime_min) {
4102 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4103 device->sleep(fps_timings->sleep_time);
4105 fps_timings->sleep_time = 0;
4108 /* Get the new value of the device timer. Note that device->sleep() may
4109 * not sleep for the entire requested time as sleep may be interrupted and
4110 * therefore it is arguably more accurate to get the new time from the
4111 * device rather than calculating it by adding sleep_time to time.
4114 device->getTimer()->tick(); // Update device timer
4115 time = device->getTimer()->getTime();
4117 if (time > last_time) // Make sure last_time hasn't overflowed
4118 *dtime = (time - last_time) / 1000.0;
4122 fps_timings->last_time = time;
4126 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4127 int percent, bool draw_clouds)
4129 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4134 /****************************************************************************
4136 ****************************************************************************/
4138 void Game::extendedResourceCleanup()
4140 // Extended resource accounting
4141 infostream << "Irrlicht resources after cleanup:" << std::endl;
4142 infostream << "\tRemaining meshes : "
4143 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4144 infostream << "\tRemaining textures : "
4145 << driver->getTextureCount() << std::endl;
4147 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4148 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4149 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4153 clearTextureNameCache();
4154 infostream << "\tRemaining materials: "
4155 << driver-> getMaterialRendererCount()
4156 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4161 /****************************************************************************
4162 extern function for launching the game
4163 ****************************************************************************/
4165 void the_game(bool *kill,
4167 InputHandler *input,
4168 IrrlichtDevice *device,
4170 const std::string &map_dir,
4171 const std::string &playername,
4172 const std::string &password,
4173 const std::string &address, // If empty local server is created
4176 std::wstring &error_message,
4177 ChatBackend &chat_backend,
4178 const SubgameSpec &gamespec, // Used for local game
4179 bool simple_singleplayer_mode)
4183 /* Make a copy of the server address because if a local singleplayer server
4184 * is created then this is updated and we don't want to change the value
4185 * passed to us by the calling function
4187 std::string server_address = address;
4191 if (game.startup(kill, random_input, input, device, map_dir,
4192 playername, password, &server_address, port,
4193 &error_message, &chat_backend, gamespec,
4194 simple_singleplayer_mode)) {
4200 } catch (SerializationError &e) {
4201 error_message = L"A serialization error occurred:\n"
4202 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
4203 L" running a different version of Minetest.";
4204 errorstream << wide_to_narrow(error_message) << std::endl;
4205 } catch (ServerError &e) {
4206 error_message = narrow_to_wide(e.what());
4207 errorstream << "ServerError: " << e.what() << std::endl;
4208 } catch (ModError &e) {
4209 errorstream << "ModError: " << e.what() << std::endl;
4210 error_message = narrow_to_wide(e.what()) + wstrgettext("\nCheck debug.txt for details.");