3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include "irrlichttypes_extrabloated.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
27 #include <IMaterialRendererServices.h>
28 #include "IMeshCache.h"
31 #include "guiPasswordChange.h"
32 #include "guiVolumeChange.h"
33 #include "guiKeyChangeMenu.h"
34 #include "guiFormSpecMenu.h"
36 #include "guiChatConsole.h"
40 #include "particles.h"
45 #include "mainmenumanager.h"
49 // Needed for determining pointing to nodes
51 #include "nodemetadata.h"
52 #include "main.h" // For g_settings
54 #include "tile.h" // For TextureSource
55 #include "shader.h" // For ShaderSource
56 #include "logoutputbuffer.h"
58 #include "quicktune_shortcutter.h"
59 #include "clientmap.h"
64 #include "sound_openal.h"
66 #include "event_manager.h"
69 #include "util/directiontables.h"
70 #include "util/pointedthing.h"
71 #include "drawscene.h"
72 #include "content_cao.h"
73 #include "fontengine.h"
75 #ifdef HAVE_TOUCHSCREENGUI
76 #include "touchscreengui.h"
83 struct TextDestNodeMetadata : public TextDest {
84 TextDestNodeMetadata(v3s16 p, Client *client)
89 // This is deprecated I guess? -celeron55
90 void gotText(std::wstring text)
92 std::string ntext = wide_to_narrow(text);
93 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
94 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
95 std::map<std::string, std::string> fields;
96 fields["text"] = ntext;
97 m_client->sendNodemetaFields(m_p, "", fields);
99 void gotText(std::map<std::string, std::string> fields)
101 m_client->sendNodemetaFields(m_p, "", fields);
108 struct TextDestPlayerInventory : public TextDest {
109 TextDestPlayerInventory(Client *client)
114 TextDestPlayerInventory(Client *client, std::string formname)
117 m_formname = formname;
119 void gotText(std::map<std::string, std::string> fields)
121 m_client->sendInventoryFields(m_formname, fields);
127 struct LocalFormspecHandler : public TextDest {
128 LocalFormspecHandler();
129 LocalFormspecHandler(std::string formname) :
132 m_formname = formname;
135 LocalFormspecHandler(std::string formname, Client *client) :
138 m_formname = formname;
141 void gotText(std::wstring message)
143 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
146 void gotText(std::map<std::string, std::string> fields)
148 if (m_formname == "MT_PAUSE_MENU") {
149 if (fields.find("btn_sound") != fields.end()) {
150 g_gamecallback->changeVolume();
154 if (fields.find("btn_key_config") != fields.end()) {
155 g_gamecallback->keyConfig();
159 if (fields.find("btn_exit_menu") != fields.end()) {
160 g_gamecallback->disconnect();
164 if (fields.find("btn_exit_os") != fields.end()) {
165 g_gamecallback->exitToOS();
169 if (fields.find("btn_change_password") != fields.end()) {
170 g_gamecallback->changePassword();
174 if (fields.find("quit") != fields.end()) {
178 if (fields.find("btn_continue") != fields.end()) {
183 if (m_formname == "MT_CHAT_MENU") {
184 assert(m_client != 0);
186 if ((fields.find("btn_send") != fields.end()) ||
187 (fields.find("quit") != fields.end())) {
188 if (fields.find("f_text") != fields.end()) {
189 m_client->typeChatMessage(narrow_to_wide(fields["f_text"]));
196 if (m_formname == "MT_DEATH_SCREEN") {
197 assert(m_client != 0);
199 if ((fields.find("btn_respawn") != fields.end())) {
200 m_client->sendRespawn();
204 if (fields.find("quit") != fields.end()) {
205 m_client->sendRespawn();
210 // don't show error message for unhandled cursor keys
211 if ((fields.find("key_up") != fields.end()) ||
212 (fields.find("key_down") != fields.end()) ||
213 (fields.find("key_left") != fields.end()) ||
214 (fields.find("key_right") != fields.end())) {
218 errorstream << "LocalFormspecHandler::gotText unhandled >" << m_formname << "< event" << std::endl;
221 for (std::map<std::string, std::string>::iterator iter = fields.begin();
222 iter != fields.end(); iter++) {
223 errorstream << "\t" << i << ": " << iter->first << "=" << iter->second << std::endl;
231 /* Form update callback */
233 class NodeMetadataFormSource: public IFormSource
236 NodeMetadataFormSource(ClientMap *map, v3s16 p):
241 std::string getForm()
243 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
248 return meta->getString("formspec");
250 std::string resolveText(std::string str)
252 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
257 return meta->resolveString(str);
264 class PlayerInventoryFormSource: public IFormSource
267 PlayerInventoryFormSource(Client *client):
271 std::string getForm()
273 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
274 return player->inventory_formspec;
281 Check if a node is pointable
283 inline bool isPointableNode(const MapNode &n,
284 Client *client, bool liquids_pointable)
286 const ContentFeatures &features = client->getNodeDefManager()->get(n);
287 return features.pointable ||
288 (liquids_pointable && features.isLiquid());
292 Find what the player is pointing at
294 PointedThing getPointedThing(Client *client, v3f player_position,
295 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
296 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
297 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
301 hilightboxes.clear();
302 selected_object = NULL;
304 INodeDefManager *nodedef = client->getNodeDefManager();
305 ClientMap &map = client->getEnv().getClientMap();
307 f32 mindistance = BS * 1001;
309 // First try to find a pointed at active object
310 if (look_for_object) {
311 selected_object = client->getSelectedActiveObject(d * BS,
312 camera_position, shootline);
314 if (selected_object != NULL) {
315 if (selected_object->doShowSelectionBox()) {
316 aabb3f *selection_box = selected_object->getSelectionBox();
317 // Box should exist because object was
318 // returned in the first place
319 assert(selection_box);
321 v3f pos = selected_object->getPosition();
322 hilightboxes.push_back(aabb3f(
323 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
324 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
327 mindistance = (selected_object->getPosition() - camera_position).getLength();
329 result.type = POINTEDTHING_OBJECT;
330 result.object_id = selected_object->getId();
334 // That didn't work, try to find a pointed at node
337 v3s16 pos_i = floatToInt(player_position, BS);
339 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
343 s16 ystart = pos_i.Y + 0 - (camera_direction.Y < 0 ? a : 1);
344 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
345 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
346 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
347 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
348 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
350 // Prevent signed number overflow
360 for (s16 y = ystart; y <= yend; y++)
361 for (s16 z = zstart; z <= zend; z++)
362 for (s16 x = xstart; x <= xend; x++) {
364 bool is_valid_position;
366 n = map.getNodeNoEx(v3s16(x, y, z), &is_valid_position);
367 if (!is_valid_position)
370 if (!isPointableNode(n, client, liquids_pointable))
373 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
376 v3f npf = intToFloat(np, BS);
378 for (std::vector<aabb3f>::const_iterator
380 i != boxes.end(); i++) {
385 for (u16 j = 0; j < 6; j++) {
386 v3s16 facedir = g_6dirs[j];
387 aabb3f facebox = box;
392 facebox.MinEdge.X = facebox.MaxEdge.X - d;
393 else if (facedir.X < 0)
394 facebox.MaxEdge.X = facebox.MinEdge.X + d;
395 else if (facedir.Y > 0)
396 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
397 else if (facedir.Y < 0)
398 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
399 else if (facedir.Z > 0)
400 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
401 else if (facedir.Z < 0)
402 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
404 v3f centerpoint = facebox.getCenter();
405 f32 distance = (centerpoint - camera_position).getLength();
407 if (distance >= mindistance)
410 if (!facebox.intersectsWithLine(shootline))
413 v3s16 np_above = np + facedir;
415 result.type = POINTEDTHING_NODE;
416 result.node_undersurface = np;
417 result.node_abovesurface = np_above;
418 mindistance = distance;
420 hilightboxes.clear();
422 if (!g_settings->getBool("enable_node_highlighting")) {
423 for (std::vector<aabb3f>::const_iterator
425 i2 != boxes.end(); i2++) {
427 box.MinEdge += npf + v3f(-d, -d, -d) - intToFloat(camera_offset, BS);
428 box.MaxEdge += npf + v3f(d, d, d) - intToFloat(camera_offset, BS);
429 hilightboxes.push_back(box);
439 /* Profiler display */
441 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
442 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
444 if (show_profiler == 0) {
445 guitext_profiler->setVisible(false);
448 std::ostringstream os(std::ios_base::binary);
449 g_profiler->printPage(os, show_profiler, show_profiler_max);
450 std::wstring text = narrow_to_wide(os.str());
451 guitext_profiler->setText(text.c_str());
452 guitext_profiler->setVisible(true);
454 s32 w = fe->getTextWidth(text.c_str());
459 unsigned text_height = fe->getTextHeight();
461 core::position2di upper_left, lower_right;
464 upper_left.Y = (text_height + 5) * 2;
465 lower_right.X = 12 + w;
466 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
468 if (lower_right.Y > screen_height * 2 / 3)
469 lower_right.Y = screen_height * 2 / 3;
471 core::rect<s32> rect(upper_left, lower_right);
473 guitext_profiler->setRelativePosition(rect);
474 guitext_profiler->setVisible(true);
482 Profiler::GraphValues values;
488 Meta(float initial = 0,
489 video::SColor color = video::SColor(255, 255, 255, 255)):
495 std::list<Piece> m_log;
503 void put(const Profiler::GraphValues &values)
506 piece.values = values;
507 m_log.push_back(piece);
509 while (m_log.size() > m_log_max_size)
510 m_log.erase(m_log.begin());
513 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
514 gui::IGUIFont *font) const
516 std::map<std::string, Meta> m_meta;
518 for (std::list<Piece>::const_iterator k = m_log.begin();
519 k != m_log.end(); k++) {
520 const Piece &piece = *k;
522 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
523 i != piece.values.end(); i++) {
524 const std::string &id = i->first;
525 const float &value = i->second;
526 std::map<std::string, Meta>::iterator j =
529 if (j == m_meta.end()) {
530 m_meta[id] = Meta(value);
534 if (value < j->second.min)
535 j->second.min = value;
537 if (value > j->second.max)
538 j->second.max = value;
543 static const video::SColor usable_colors[] = {
544 video::SColor(255, 255, 100, 100),
545 video::SColor(255, 90, 225, 90),
546 video::SColor(255, 100, 100, 255),
547 video::SColor(255, 255, 150, 50),
548 video::SColor(255, 220, 220, 100)
550 static const u32 usable_colors_count =
551 sizeof(usable_colors) / sizeof(*usable_colors);
552 u32 next_color_i = 0;
554 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
555 i != m_meta.end(); i++) {
556 Meta &meta = i->second;
557 video::SColor color(255, 200, 200, 200);
559 if (next_color_i < usable_colors_count)
560 color = usable_colors[next_color_i++];
566 s32 textx = x_left + m_log_max_size + 15;
567 s32 textx2 = textx + 200 - 15;
571 u32 num_graphs = m_meta.size();
572 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
574 video::SColor bgcolor(120,0,0,0);
575 driver->draw2DRectangle(bgcolor, rect, NULL);
580 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
581 i != m_meta.end(); i++) {
582 const std::string &id = i->first;
583 const Meta &meta = i->second;
585 s32 y = y_bottom - meta_i * 50;
586 float show_min = meta.min;
587 float show_max = meta.max;
589 if (show_min >= -0.0001 && show_max >= -0.0001) {
590 if (show_min <= show_max * 0.5)
596 snprintf(buf, 10, "%.3g", show_max);
597 font->draw(narrow_to_wide(buf).c_str(),
598 core::rect<s32>(textx, y - graphh,
599 textx2, y - graphh + texth),
601 snprintf(buf, 10, "%.3g", show_min);
602 font->draw(narrow_to_wide(buf).c_str(),
603 core::rect<s32>(textx, y - texth,
606 font->draw(narrow_to_wide(id).c_str(),
607 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
608 textx2, y - graphh / 2 + texth / 2),
611 s32 graph1h = graphh;
612 bool relativegraph = (show_min != 0 && show_min != show_max);
613 float lastscaledvalue = 0.0;
614 bool lastscaledvalue_exists = false;
616 for (std::list<Piece>::const_iterator j = m_log.begin();
617 j != m_log.end(); j++) {
618 const Piece &piece = *j;
620 bool value_exists = false;
621 Profiler::GraphValues::const_iterator k =
622 piece.values.find(id);
624 if (k != piece.values.end()) {
631 lastscaledvalue_exists = false;
635 float scaledvalue = 1.0;
637 if (show_max != show_min)
638 scaledvalue = (value - show_min) / (show_max - show_min);
640 if (scaledvalue == 1.0 && value == 0) {
642 lastscaledvalue_exists = false;
647 if (lastscaledvalue_exists) {
648 s32 ivalue1 = lastscaledvalue * graph1h;
649 s32 ivalue2 = scaledvalue * graph1h;
650 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
651 v2s32(x, graph1y - ivalue2), meta.color);
654 lastscaledvalue = scaledvalue;
655 lastscaledvalue_exists = true;
657 s32 ivalue = scaledvalue * graph1h;
658 driver->draw2DLine(v2s32(x, graph1y),
659 v2s32(x, graph1y - ivalue), meta.color);
670 class NodeDugEvent: public MtEvent
676 NodeDugEvent(v3s16 p, MapNode n):
680 const char *getType() const
688 ISoundManager *m_sound;
689 INodeDefManager *m_ndef;
691 float m_player_step_timer;
693 SimpleSoundSpec m_player_step_sound;
694 SimpleSoundSpec m_player_leftpunch_sound;
695 SimpleSoundSpec m_player_rightpunch_sound;
697 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
700 m_player_step_timer(0)
704 void playPlayerStep()
706 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
707 m_player_step_timer = 0.03;
708 m_sound->playSound(m_player_step_sound, false);
712 static void viewBobbingStep(MtEvent *e, void *data)
714 SoundMaker *sm = (SoundMaker *)data;
715 sm->playPlayerStep();
718 static void playerRegainGround(MtEvent *e, void *data)
720 SoundMaker *sm = (SoundMaker *)data;
721 sm->playPlayerStep();
724 static void playerJump(MtEvent *e, void *data)
726 //SoundMaker *sm = (SoundMaker*)data;
729 static void cameraPunchLeft(MtEvent *e, void *data)
731 SoundMaker *sm = (SoundMaker *)data;
732 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
735 static void cameraPunchRight(MtEvent *e, void *data)
737 SoundMaker *sm = (SoundMaker *)data;
738 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
741 static void nodeDug(MtEvent *e, void *data)
743 SoundMaker *sm = (SoundMaker *)data;
744 NodeDugEvent *nde = (NodeDugEvent *)e;
745 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
748 static void playerDamage(MtEvent *e, void *data)
750 SoundMaker *sm = (SoundMaker *)data;
751 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
754 static void playerFallingDamage(MtEvent *e, void *data)
756 SoundMaker *sm = (SoundMaker *)data;
757 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
760 void registerReceiver(MtEventManager *mgr)
762 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
763 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
764 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
765 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
766 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
767 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
768 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
769 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
772 void step(float dtime)
774 m_player_step_timer -= dtime;
778 // Locally stored sounds don't need to be preloaded because of this
779 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
781 std::set<std::string> m_fetched;
783 void fetchSounds(const std::string &name,
784 std::set<std::string> &dst_paths,
785 std::set<std::string> &dst_datas)
787 if (m_fetched.count(name))
790 m_fetched.insert(name);
791 std::string base = porting::path_share + DIR_DELIM + "testsounds";
792 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
793 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
794 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
795 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
796 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
797 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
798 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
799 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
800 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
801 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
802 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
806 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
809 bool *m_force_fog_off;
814 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
815 f32 *fog_range, Client *client) :
817 m_force_fog_off(force_fog_off),
818 m_fog_range(fog_range),
821 ~GameGlobalShaderConstantSetter() {}
823 virtual void onSetConstants(video::IMaterialRendererServices *services,
830 video::SColor bgcolor = m_sky->getBgColor();
831 video::SColorf bgcolorf(bgcolor);
832 float bgcolorfa[4] = {
838 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
841 float fog_distance = 10000 * BS;
843 if (g_settings->getBool("enable_fog") && !*m_force_fog_off)
844 fog_distance = *m_fog_range;
846 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
849 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
850 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
851 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
853 u32 animation_timer = porting::getTimeMs() % 100000;
854 float animation_timer_f = (float)animation_timer / 100000.0;
855 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
856 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
858 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
859 v3f eye_position = player->getEyePosition();
860 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
861 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
863 // Uniform sampler layers
867 // before 1.8 there isn't a "integer interface", only float
868 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
869 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
870 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
871 services->setPixelShaderConstant("useNormalmap" , (irr::f32 *)&layer2, 1);
873 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
874 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
875 services->setPixelShaderConstant("useNormalmap" , (irr::s32 *)&layer2, 1);
880 bool nodePlacementPrediction(Client &client,
881 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
883 std::string prediction = playeritem_def.node_placement_prediction;
884 INodeDefManager *nodedef = client.ndef();
885 ClientMap &map = client.getEnv().getClientMap();
887 bool is_valid_position;
889 node = map.getNodeNoEx(nodepos, &is_valid_position);
890 if (!is_valid_position)
893 if (prediction != "" && !nodedef->get(node).rightclickable) {
894 verbosestream << "Node placement prediction for "
895 << playeritem_def.name << " is "
896 << prediction << std::endl;
897 v3s16 p = neighbourpos;
899 // Place inside node itself if buildable_to
900 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
901 if (is_valid_position)
903 if (nodedef->get(n_under).buildable_to)
906 node = map.getNodeNoEx(p, &is_valid_position);
907 if (is_valid_position &&!nodedef->get(node).buildable_to)
912 // Find id of predicted node
914 bool found = nodedef->getId(prediction, id);
917 errorstream << "Node placement prediction failed for "
918 << playeritem_def.name << " (places "
920 << ") - Name not known" << std::endl;
924 // Predict param2 for facedir and wallmounted nodes
927 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
928 v3s16 dir = nodepos - neighbourpos;
930 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
931 param2 = dir.Y < 0 ? 1 : 0;
932 } else if (abs(dir.X) > abs(dir.Z)) {
933 param2 = dir.X < 0 ? 3 : 2;
935 param2 = dir.Z < 0 ? 5 : 4;
939 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
940 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
942 if (abs(dir.X) > abs(dir.Z)) {
943 param2 = dir.X < 0 ? 3 : 1;
945 param2 = dir.Z < 0 ? 2 : 0;
951 //Check attachment if node is in group attached_node
952 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
953 static v3s16 wallmounted_dirs[8] = {
963 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
964 pp = p + wallmounted_dirs[param2];
966 pp = p + v3s16(0, -1, 0);
968 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
972 // Add node to client map
973 MapNode n(id, 0, param2);
976 LocalPlayer *player = client.getEnv().getLocalPlayer();
978 // Dont place node when player would be inside new node
979 // NOTE: This is to be eventually implemented by a mod as client-side Lua
980 if (!nodedef->get(n).walkable ||
981 g_settings->getBool("enable_build_where_you_stand") ||
982 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
983 (nodedef->get(n).walkable &&
984 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
985 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
987 // This triggers the required mesh update too
988 client.addNode(p, n);
991 } catch (InvalidPositionException &e) {
992 errorstream << "Node placement prediction failed for "
993 << playeritem_def.name << " (places "
995 << ") - Position not loaded" << std::endl;
1002 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1003 InventoryManager *invmgr, IGameDef *gamedef,
1004 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1005 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1008 if (*cur_formspec == 0) {
1009 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1010 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1011 (*cur_formspec)->doPause = false;
1014 Caution: do not call (*cur_formspec)->drop() here --
1015 the reference might outlive the menu, so we will
1016 periodically check if *cur_formspec is the only
1017 remaining reference (i.e. the menu was removed)
1018 and delete it in that case.
1022 (*cur_formspec)->setFormSource(fs_src);
1023 (*cur_formspec)->setTextDest(txt_dest);
1027 #define SIZE_TAG "size[11,5.5]"
1029 static void show_chat_menu(GUIFormSpecMenu **cur_formspec,
1030 InventoryManager *invmgr, IGameDef *gamedef,
1031 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1032 Client *client, std::string text)
1034 std::string formspec =
1035 FORMSPEC_VERSION_STRING
1037 "field[3,2.35;6,0.5;f_text;;" + text + "]"
1038 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
1042 /* Note: FormspecFormSource and LocalFormspecHandler
1043 * are deleted by guiFormSpecMenu */
1044 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1045 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
1047 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1050 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1051 InventoryManager *invmgr, IGameDef *gamedef,
1052 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1054 std::string formspec =
1055 std::string(FORMSPEC_VERSION_STRING) +
1057 "bgcolor[#320000b4;true]"
1058 "label[4.85,1.35;You died.]"
1059 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1063 /* Note: FormspecFormSource and LocalFormspecHandler
1064 * are deleted by guiFormSpecMenu */
1065 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1066 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1068 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1071 /******************************************************************************/
1072 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1073 InventoryManager *invmgr, IGameDef *gamedef,
1074 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1075 bool singleplayermode)
1078 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1079 "No menu visible:\n"
1080 "- single tap: button activate\n"
1081 "- double tap: place/use\n"
1082 "- slide finger: look around\n"
1083 "Menu/Inventory visible:\n"
1084 "- double tap (outside):\n"
1086 "- touch stack, touch slot:\n"
1088 "- touch&drag, tap 2nd finger\n"
1089 " --> place single item to slot\n"
1092 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1094 "- Space: jump/climb\n"
1095 "- Shift: sneak/go down\n"
1098 "- Mouse: turn/look\n"
1099 "- Mouse left: dig/punch\n"
1100 "- Mouse right: place/use\n"
1101 "- Mouse wheel: select item\n"
1106 float ypos = singleplayermode ? 0.5 : 0.1;
1107 std::ostringstream os;
1109 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1110 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1111 << wide_to_narrow(wstrgettext("Continue")) << "]";
1113 if (!singleplayermode) {
1114 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1115 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1118 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1119 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1120 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1121 << wide_to_narrow(wstrgettext("Change Keys")) << "]";
1122 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1123 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1124 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1125 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1126 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1127 << "textarea[0.4,0.25;3.5,6;;" << "Minetest\n"
1128 << minetest_build_info << "\n"
1129 << "path_user = " << wrap_rows(porting::path_user, 20)
1133 /* Note: FormspecFormSource and LocalFormspecHandler *
1134 * are deleted by guiFormSpecMenu */
1135 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1136 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1138 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1140 (*cur_formspec)->doPause = true;
1143 /******************************************************************************/
1144 static void updateChat(Client &client, f32 dtime, bool show_debug,
1145 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1146 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1148 // Add chat log output for errors to be shown in chat
1149 static LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1151 // Get new messages from error log buffer
1152 while (!chat_log_error_buf.empty()) {
1153 chat_backend.addMessage(L"", narrow_to_wide(chat_log_error_buf.get()));
1156 // Get new messages from client
1157 std::wstring message;
1159 while (client.getChatMessage(message)) {
1160 chat_backend.addUnparsedMessage(message);
1163 // Remove old messages
1164 chat_backend.step(dtime);
1166 // Display all messages in a static text element
1167 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1168 std::wstring recent_chat = chat_backend.getRecentChat();
1169 unsigned int line_height = g_fontengine->getLineHeight();
1171 guitext_chat->setText(recent_chat.c_str());
1173 // Update gui element size and position
1174 s32 chat_y = 5 + line_height;
1177 chat_y += line_height;
1179 // first pass to calculate height of text to be set
1180 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1181 porting::getWindowSize().X - 20);
1182 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1183 guitext_chat->setRelativePosition(rect);
1185 //now use real height of text and adjust rect according to this size
1186 rect = core::rect<s32>(10, chat_y, width,
1187 chat_y + guitext_chat->getTextHeight());
1190 guitext_chat->setRelativePosition(rect);
1191 // Don't show chat if disabled or empty or profiler is enabled
1192 guitext_chat->setVisible(
1193 show_chat && recent_chat_count != 0 && !show_profiler);
1197 /****************************************************************************
1198 Fast key cache for main game loop
1199 ****************************************************************************/
1201 /* This is faster than using getKeySetting with the tradeoff that functions
1202 * using it must make sure that it's initialised before using it and there is
1203 * no error handling (for example bounds checking). This is really intended for
1204 * use only in the main running loop of the client (the_game()) where the faster
1205 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1206 * (e.g. formspecs) should continue using getKeySetting().
1210 KeyCache() { populate(); }
1224 KEYMAP_ID_INVENTORY,
1231 KEYMAP_ID_SCREENSHOT,
1232 KEYMAP_ID_TOGGLE_HUD,
1233 KEYMAP_ID_TOGGLE_CHAT,
1234 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1235 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1236 KEYMAP_ID_TOGGLE_DEBUG,
1237 KEYMAP_ID_TOGGLE_PROFILER,
1238 KEYMAP_ID_CAMERA_MODE,
1239 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1240 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1241 KEYMAP_ID_RANGESELECT,
1243 KEYMAP_ID_QUICKTUNE_NEXT,
1244 KEYMAP_ID_QUICKTUNE_PREV,
1245 KEYMAP_ID_QUICKTUNE_INC,
1246 KEYMAP_ID_QUICKTUNE_DEC,
1248 KEYMAP_ID_DEBUG_STACKS,
1250 // Fake keycode for array size and internal checks
1251 KEYMAP_INTERNAL_ENUM_COUNT
1258 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1261 void KeyCache::populate()
1263 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1264 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1265 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1266 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1267 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1268 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1269 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1271 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1272 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1273 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1274 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1275 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1276 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1277 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1278 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1279 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1280 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1281 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1282 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1283 = getKeySetting("keymap_toggle_force_fog_off");
1284 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1285 = getKeySetting("keymap_toggle_update_camera");
1286 key[KEYMAP_ID_TOGGLE_DEBUG]
1287 = getKeySetting("keymap_toggle_debug");
1288 key[KEYMAP_ID_TOGGLE_PROFILER]
1289 = getKeySetting("keymap_toggle_profiler");
1290 key[KEYMAP_ID_CAMERA_MODE]
1291 = getKeySetting("keymap_camera_mode");
1292 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1293 = getKeySetting("keymap_increase_viewing_range_min");
1294 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1295 = getKeySetting("keymap_decrease_viewing_range_min");
1296 key[KEYMAP_ID_RANGESELECT]
1297 = getKeySetting("keymap_rangeselect");
1299 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1300 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1301 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1302 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1304 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1308 /****************************************************************************
1310 ****************************************************************************/
1312 const float object_hit_delay = 0.2;
1315 u32 last_time, busy_time, sleep_time;
1319 /* The reason the following structs are not anonymous structs within the
1320 * class is that they are not used by the majority of member functions and
1321 * many functions that do require objects of thse types do not modify them
1322 * (so they can be passed as a const qualified parameter)
1324 struct CameraOrientation {
1325 f32 camera_yaw; // "right/left"
1326 f32 camera_pitch; // "up/down"
1329 struct GameRunData {
1332 PointedThing pointed_old;
1336 bool update_wielded_item_trigger;
1337 bool reset_jump_timer;
1338 float nodig_delay_timer;
1340 float dig_time_complete;
1341 float repeat_rightclick_timer;
1342 float object_hit_delay_timer;
1343 float time_from_last_punch;
1344 ClientActiveObject *selected_object;
1348 float update_draw_list_timer;
1349 float statustext_time;
1353 v3f update_draw_list_last_cam_dir;
1355 u32 profiler_current_page;
1356 u32 profiler_max_page; // Number of pages
1359 float time_of_day_smooth;
1363 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1371 Jitter dtime_jitter, busy_time_jitter;
1374 /* Flags that can, or may, change during main game loop
1376 struct VolatileRunFlags {
1382 bool show_profiler_graph;
1383 bool disable_camera_update;
1384 bool first_loop_after_window_activation;
1385 bool camera_offset_changed;
1389 /****************************************************************************
1391 ****************************************************************************/
1393 /* This is not intended to be a public class. If a public class becomes
1394 * desirable then it may be better to create another 'wrapper' class that
1395 * hides most of the stuff in this class (nothing in this class is required
1396 * by any other file) but exposes the public methods/data only.
1404 bool startup(bool *kill,
1406 InputHandler *input,
1407 IrrlichtDevice *device,
1408 const std::string &map_dir,
1409 const std::string &playername,
1410 const std::string &password,
1411 // If address is "", local server is used and address is updated
1412 std::string *address,
1414 std::wstring *error_message,
1415 ChatBackend *chat_backend,
1416 const SubgameSpec &gamespec, // Used for local game
1417 bool simple_singleplayer_mode);
1424 void extendedResourceCleanup();
1426 // Basic initialisation
1427 bool init(const std::string &map_dir, std::string *address,
1429 const SubgameSpec &gamespec);
1431 bool createSingleplayerServer(const std::string map_dir,
1432 const SubgameSpec &gamespec, u16 port, std::string *address);
1435 bool createClient(const std::string &playername,
1436 const std::string &password, std::string *address, u16 port,
1437 std::wstring *error_message);
1438 bool initGui(std::wstring *error_message);
1440 // Client connection
1441 bool connectToServer(const std::string &playername,
1442 const std::string &password, std::string *address, u16 port,
1443 bool *connect_ok, bool *aborted);
1444 bool getServerContent(bool *aborted);
1448 void updateInteractTimers(GameRunData *args, f32 dtime);
1449 bool checkConnection();
1450 bool handleCallbacks();
1451 void processQueues();
1452 void updateProfilers(const GameRunData &run_data, const RunStats &stats,
1453 const FpsControl &draw_times, f32 dtime);
1454 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1456 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1458 void processUserInput(VolatileRunFlags *flags, GameRunData *interact_args,
1460 void processKeyboardInput(VolatileRunFlags *flags,
1461 float *statustext_time,
1463 bool *reset_jump_timer,
1464 u32 *profiler_current_page,
1465 u32 profiler_max_page);
1466 void processItemSelection(u16 *new_playeritem);
1468 void dropSelectedItem();
1469 void openInventory();
1471 void toggleFreeMove(float *statustext_time);
1472 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1473 void toggleFast(float *statustext_time);
1474 void toggleNoClip(float *statustext_time);
1476 void toggleChat(float *statustext_time, bool *flag);
1477 void toggleHud(float *statustext_time, bool *flag);
1478 void toggleFog(float *statustext_time, bool *flag);
1479 void toggleDebug(float *statustext_time, bool *show_debug,
1480 bool *show_profiler_graph);
1481 void toggleUpdateCamera(float *statustext_time, bool *flag);
1482 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1483 u32 profiler_max_page);
1485 void increaseViewRange(float *statustext_time);
1486 void decreaseViewRange(float *statustext_time);
1487 void toggleFullViewRange(float *statustext_time);
1489 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1490 void updateCameraOrientation(CameraOrientation *cam,
1491 const VolatileRunFlags &flags);
1492 void updatePlayerControl(const CameraOrientation &cam);
1493 void step(f32 *dtime);
1494 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1495 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1496 float time_from_last_punch);
1497 void updateSound(f32 dtime);
1498 void processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
1499 GameRunData *runData, f32 dtime, bool show_hud,
1501 void handlePointingAtNode(GameRunData *runData,
1502 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1503 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1504 void handlePointingAtObject(GameRunData *runData,
1505 const PointedThing &pointed, const ItemStack &playeritem,
1506 const v3f &player_position, bool show_debug);
1507 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1508 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1510 void updateFrame(std::vector<aabb3f> &highlight_boxes, ProfilerGraph *graph,
1511 RunStats *stats, GameRunData *runData,
1512 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1513 void updateGui(float *statustext_time, const RunStats &stats,
1514 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1515 const CameraOrientation &cam);
1516 void updateProfilerGraphs(ProfilerGraph *graph);
1519 void limitFps(FpsControl *fps_timings, f32 *dtime);
1521 void showOverlayMessage(const char *msg, float dtime, int percent,
1522 bool draw_clouds = true);
1525 InputHandler *input;
1530 IWritableTextureSource *texture_src;
1531 IWritableShaderSource *shader_src;
1533 // When created, these will be filled with data received from the server
1534 IWritableItemDefManager *itemdef_manager;
1535 IWritableNodeDefManager *nodedef_manager;
1537 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1538 ISoundManager *sound;
1539 bool sound_is_dummy;
1540 SoundMaker *soundmaker;
1542 ChatBackend *chat_backend;
1544 GUIFormSpecMenu *current_formspec;
1546 EventManager *eventmgr;
1547 QuicktuneShortcutter *quicktune;
1549 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1550 MapDrawControl *draw_control;
1552 Clouds *clouds; // Free using ->Drop()
1553 Sky *sky; // Free using ->Drop()
1554 Inventory *local_inventory;
1558 This class does take ownership/responsibily for cleaning up etc of any of
1559 these items (e.g. device)
1561 IrrlichtDevice *device;
1562 video::IVideoDriver *driver;
1563 scene::ISceneManager *smgr;
1565 std::wstring *error_message;
1566 IGameDef *gamedef; // Convenience (same as *client)
1567 scene::ISceneNode *skybox;
1570 bool simple_singleplayer_mode;
1573 /* Pre-calculated values
1575 int crack_animation_length;
1579 gui::IGUIStaticText *guitext; // First line of debug text
1580 gui::IGUIStaticText *guitext2; // Second line of debug text
1581 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1582 gui::IGUIStaticText *guitext_status;
1583 gui::IGUIStaticText *guitext_chat; // Chat text
1584 gui::IGUIStaticText *guitext_profiler; // Profiler text
1586 std::wstring infotext;
1587 std::wstring statustext;
1591 IntervalLimiter profiler_interval;
1593 /* TODO: Add a callback function so these can be updated when a setting
1594 * changes. At this point in time it doesn't matter (e.g. /set
1595 * is documented to change server settings only)
1597 * TODO: Local caching of settings is not optimal and should at some stage
1598 * be updated to use a global settings object for getting thse values
1599 * (as opposed to the this local caching). This can be addressed in
1602 bool m_cache_doubletap_jump;
1603 bool m_cache_enable_node_highlighting;
1604 bool m_cache_enable_clouds;
1605 bool m_cache_enable_particles;
1606 bool m_cache_enable_fog;
1607 f32 m_cache_mouse_sensitivity;
1608 f32 m_repeat_right_click_time;
1616 itemdef_manager(NULL),
1617 nodedef_manager(NULL),
1619 sound_is_dummy(false),
1622 current_formspec(NULL),
1625 gui_chat_console(NULL),
1630 local_inventory(NULL),
1633 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
1634 m_cache_enable_node_highlighting = g_settings->getBool("enable_node_highlighting");
1635 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
1636 m_cache_enable_particles = g_settings->getBool("enable_particles");
1637 m_cache_enable_fog = g_settings->getBool("enable_fog");
1638 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
1639 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
1641 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
1646 /****************************************************************************
1648 ****************************************************************************/
1654 if (!sound_is_dummy)
1657 delete server; // deleted first to stop all server threads
1660 delete local_inventory;
1666 delete nodedef_manager;
1667 delete itemdef_manager;
1668 delete draw_control;
1670 extendedResourceCleanup();
1673 bool Game::startup(bool *kill,
1675 InputHandler *input,
1676 IrrlichtDevice *device,
1677 const std::string &map_dir,
1678 const std::string &playername,
1679 const std::string &password,
1680 std::string *address, // can change if simple_singleplayer_mode
1682 std::wstring *error_message,
1683 ChatBackend *chat_backend,
1684 const SubgameSpec &gamespec,
1685 bool simple_singleplayer_mode)
1688 this->device = device;
1690 this->error_message = error_message;
1691 this->random_input = random_input;
1692 this->input = input;
1693 this->chat_backend = chat_backend;
1694 this->simple_singleplayer_mode = simple_singleplayer_mode;
1696 driver = device->getVideoDriver();
1697 smgr = device->getSceneManager();
1699 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1701 if (!init(map_dir, address, port, gamespec))
1704 if (!createClient(playername, password, address, port, error_message))
1713 ProfilerGraph graph;
1714 RunStats stats = { 0 };
1715 CameraOrientation cam_view = { 0 };
1716 GameRunData runData = { 0 };
1717 FpsControl draw_times = { 0 };
1718 VolatileRunFlags flags = { 0 };
1719 f32 dtime; // in seconds
1721 runData.time_from_last_punch = 10.0;
1722 runData.profiler_max_page = 3;
1723 runData.update_wielded_item_trigger = true;
1725 flags.show_chat = true;
1726 flags.show_hud = true;
1727 flags.show_debug = g_settings->getBool("show_debug");
1728 flags.invert_mouse = g_settings->getBool("invert_mouse");
1729 flags.first_loop_after_window_activation = true;
1731 /* Clear the profiler */
1732 Profiler::GraphValues dummyvalues;
1733 g_profiler->graphGet(dummyvalues);
1735 draw_times.last_time = device->getTimer()->getTime();
1737 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1739 &flags.force_fog_off,
1743 std::vector<aabb3f> highlight_boxes;
1745 set_light_table(g_settings->getFloat("display_gamma"));
1747 while (device->run() && !(*kill || g_gamecallback->shutdown_requested)) {
1749 /* Must be called immediately after a device->run() call because it
1750 * uses device->getTimer()->getTime()
1752 limitFps(&draw_times, &dtime);
1754 updateStats(&stats, draw_times, dtime);
1755 updateInteractTimers(&runData, dtime);
1757 if (!checkConnection())
1759 if (!handleCallbacks())
1765 hud->resizeHotbar();
1767 updateProfilers(runData, stats, draw_times, dtime);
1768 processUserInput(&flags, &runData, dtime);
1769 // Update camera before player movement to avoid camera lag of one frame
1770 updateCameraDirection(&cam_view, &flags);
1771 updatePlayerControl(cam_view);
1773 processClientEvents(&cam_view, &runData.damage_flash);
1774 updateCamera(&flags, draw_times.busy_time, dtime,
1775 runData.time_from_last_punch);
1777 processPlayerInteraction(highlight_boxes, &runData, dtime,
1778 flags.show_hud, flags.show_debug);
1779 updateFrame(highlight_boxes, &graph, &stats, &runData, dtime,
1781 updateProfilerGraphs(&graph);
1786 void Game::shutdown()
1788 showOverlayMessage("Shutting down...", 0, 0, false);
1793 if (gui_chat_console)
1794 gui_chat_console->drop();
1800 while (g_menumgr.menuCount() > 0) {
1801 g_menumgr.m_stack.front()->setVisible(false);
1802 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1805 if (current_formspec) {
1806 current_formspec->drop();
1807 current_formspec = NULL;
1810 chat_backend->addMessage(L"", L"# Disconnected.");
1811 chat_backend->addMessage(L"", L"");
1815 while (!client->isShutdown()) {
1816 assert(texture_src != NULL);
1817 assert(shader_src != NULL);
1818 texture_src->processQueue();
1819 shader_src->processQueue();
1827 /****************************************************************************
1829 ****************************************************************************/
1832 const std::string &map_dir,
1833 std::string *address,
1835 const SubgameSpec &gamespec)
1837 showOverlayMessage("Loading...", 0, 0);
1839 texture_src = createTextureSource(device);
1840 shader_src = createShaderSource(device);
1842 itemdef_manager = createItemDefManager();
1843 nodedef_manager = createNodeDefManager();
1845 eventmgr = new EventManager();
1846 quicktune = new QuicktuneShortcutter();
1848 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1849 && eventmgr && quicktune))
1855 // Create a server if not connecting to an existing one
1856 if (*address == "") {
1857 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1864 bool Game::initSound()
1867 if (g_settings->getBool("enable_sound")) {
1868 infostream << "Attempting to use OpenAL audio" << std::endl;
1869 sound = createOpenALSoundManager(&soundfetcher);
1871 infostream << "Failed to initialize OpenAL audio" << std::endl;
1873 infostream << "Sound disabled." << std::endl;
1877 infostream << "Using dummy audio." << std::endl;
1878 sound = &dummySoundManager;
1879 sound_is_dummy = true;
1882 soundmaker = new SoundMaker(sound, nodedef_manager);
1886 soundmaker->registerReceiver(eventmgr);
1891 bool Game::createSingleplayerServer(const std::string map_dir,
1892 const SubgameSpec &gamespec, u16 port, std::string *address)
1894 showOverlayMessage("Creating server...", 0, 5);
1896 std::string bind_str = g_settings->get("bind_address");
1897 Address bind_addr(0, 0, 0, 0, port);
1899 if (g_settings->getBool("ipv6_server")) {
1900 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1904 bind_addr.Resolve(bind_str.c_str());
1905 *address = bind_str;
1906 } catch (ResolveError &e) {
1907 infostream << "Resolving bind address \"" << bind_str
1908 << "\" failed: " << e.what()
1909 << " -- Listening on all addresses." << std::endl;
1912 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1913 *error_message = L"Unable to listen on " +
1914 narrow_to_wide(bind_addr.serializeString()) +
1915 L" because IPv6 is disabled";
1916 errorstream << wide_to_narrow(*error_message) << std::endl;
1920 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1921 bind_addr.isIPv6());
1923 server->start(bind_addr);
1928 bool Game::createClient(const std::string &playername,
1929 const std::string &password, std::string *address, u16 port,
1930 std::wstring *error_message)
1932 showOverlayMessage("Creating client...", 0, 10);
1934 draw_control = new MapDrawControl;
1938 bool could_connect, connect_aborted;
1940 if (!connectToServer(playername, password, address, port,
1941 &could_connect, &connect_aborted))
1944 if (!could_connect) {
1945 if (*error_message == L"" && !connect_aborted) {
1946 // Should not happen if error messages are set properly
1947 *error_message = L"Connection failed for unknown reason";
1948 errorstream << wide_to_narrow(*error_message) << std::endl;
1953 if (!getServerContent(&connect_aborted)) {
1954 if (*error_message == L"" && !connect_aborted) {
1955 // Should not happen if error messages are set properly
1956 *error_message = L"Connection failed for unknown reason";
1957 errorstream << wide_to_narrow(*error_message) << std::endl;
1962 // Update cached textures, meshes and materials
1963 client->afterContentReceived(device, g_fontengine->getFont());
1967 camera = new Camera(smgr, *draw_control, gamedef);
1968 if (!camera || !camera->successfullyCreated(*error_message))
1973 if (m_cache_enable_clouds) {
1974 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1976 *error_message = L"Memory allocation error";
1977 *error_message += narrow_to_wide(" (clouds)");
1978 errorstream << wide_to_narrow(*error_message) << std::endl;
1985 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1986 skybox = NULL; // This is used/set later on in the main run loop
1988 local_inventory = new Inventory(itemdef_manager);
1990 if (!(sky && local_inventory)) {
1991 *error_message = L"Memory allocation error";
1992 *error_message += narrow_to_wide(" (sky or local inventory)");
1993 errorstream << wide_to_narrow(*error_message) << std::endl;
1997 /* Pre-calculated values
1999 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2001 v2u32 size = t->getOriginalSize();
2002 crack_animation_length = size.Y / size.X;
2004 crack_animation_length = 5;
2007 if (!initGui(error_message))
2010 /* Set window caption
2012 core::stringw str = L"Minetest [";
2013 str += driver->getName();
2015 device->setWindowCaption(str.c_str());
2017 LocalPlayer *player = client->getEnv().getLocalPlayer();
2018 player->hurt_tilt_timer = 0;
2019 player->hurt_tilt_strength = 0;
2021 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2024 *error_message = L"Memory error: could not create HUD";
2025 errorstream << wide_to_narrow(*error_message) << std::endl;
2032 bool Game::initGui(std::wstring *error_message)
2034 // First line of debug text
2035 guitext = guienv->addStaticText(
2037 core::rect<s32>(0, 0, 0, 0),
2038 false, false, guiroot);
2040 // Second line of debug text
2041 guitext2 = guienv->addStaticText(
2043 core::rect<s32>(0, 0, 0, 0),
2044 false, false, guiroot);
2046 // At the middle of the screen
2047 // Object infos are shown in this
2048 guitext_info = guienv->addStaticText(
2050 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2051 false, true, guiroot);
2053 // Status text (displays info when showing and hiding GUI stuff, etc.)
2054 guitext_status = guienv->addStaticText(
2056 core::rect<s32>(0, 0, 0, 0),
2057 false, false, guiroot);
2058 guitext_status->setVisible(false);
2061 guitext_chat = guienv->addStaticText(
2063 core::rect<s32>(0, 0, 0, 0),
2064 //false, false); // Disable word wrap as of now
2065 false, true, guiroot);
2066 // Remove stale "recent" chat messages from previous connections
2067 chat_backend->clearRecentChat();
2069 // Chat backend and console
2070 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2071 -1, chat_backend, client);
2072 if (!gui_chat_console) {
2073 *error_message = L"Could not allocate memory for chat console";
2074 errorstream << wide_to_narrow(*error_message) << std::endl;
2078 // Profiler text (size is updated when text is updated)
2079 guitext_profiler = guienv->addStaticText(
2081 core::rect<s32>(0, 0, 0, 0),
2082 false, false, guiroot);
2083 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2084 guitext_profiler->setVisible(false);
2085 guitext_profiler->setWordWrap(true);
2087 #ifdef HAVE_TOUCHSCREENGUI
2089 if (g_touchscreengui)
2090 g_touchscreengui->init(texture_src, porting::getDisplayDensity());
2097 bool Game::connectToServer(const std::string &playername,
2098 const std::string &password, std::string *address, u16 port,
2099 bool *connect_ok, bool *aborted)
2101 showOverlayMessage("Resolving address...", 0, 15);
2103 Address connect_address(0, 0, 0, 0, port);
2106 connect_address.Resolve(address->c_str());
2108 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2109 //connect_address.Resolve("localhost");
2110 if (connect_address.isIPv6()) {
2111 IPv6AddressBytes addr_bytes;
2112 addr_bytes.bytes[15] = 1;
2113 connect_address.setAddress(&addr_bytes);
2115 connect_address.setAddress(127, 0, 0, 1);
2118 } catch (ResolveError &e) {
2119 *error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
2120 errorstream << wide_to_narrow(*error_message) << std::endl;
2124 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2125 *error_message = L"Unable to connect to " +
2126 narrow_to_wide(connect_address.serializeString()) +
2127 L" because IPv6 is disabled";
2128 errorstream << wide_to_narrow(*error_message) << std::endl;
2132 client = new Client(device,
2133 playername.c_str(), password, simple_singleplayer_mode,
2134 *draw_control, texture_src, shader_src,
2135 itemdef_manager, nodedef_manager, sound, eventmgr,
2136 connect_address.isIPv6());
2141 gamedef = client; // Client acts as our GameDef
2144 infostream << "Connecting to server at ";
2145 connect_address.print(&infostream);
2146 infostream << std::endl;
2148 client->connect(connect_address);
2152 Wait for server to accept connection
2158 FpsControl fps_control = { 0 };
2159 f32 dtime; // in seconds
2161 while (device->run()) {
2163 limitFps(&fps_control, &dtime);
2165 // Update client and server
2166 client->step(dtime);
2169 server->step(dtime);
2172 if (client->getState() == LC_Init) {
2178 if (client->accessDenied()) {
2179 *error_message = L"Access denied. Reason: "
2180 + client->accessDeniedReason();
2181 errorstream << wide_to_narrow(*error_message) << std::endl;
2185 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2187 infostream << "Connect aborted [Escape]" << std::endl;
2192 showOverlayMessage("Connecting to server...", dtime, 20);
2194 } catch (con::PeerNotFoundException &e) {
2195 // TODO: Should something be done here? At least an info/error
2203 bool Game::getServerContent(bool *aborted)
2207 FpsControl fps_control = { 0 };
2208 f32 dtime; // in seconds
2210 while (device->run()) {
2212 limitFps(&fps_control, &dtime);
2214 // Update client and server
2215 client->step(dtime);
2218 server->step(dtime);
2221 if (client->mediaReceived() && client->itemdefReceived() &&
2222 client->nodedefReceived()) {
2227 if (client->accessDenied()) {
2228 *error_message = L"Access denied. Reason: "
2229 + client->accessDeniedReason();
2230 errorstream << wide_to_narrow(*error_message) << std::endl;
2234 if (client->getState() < LC_Init) {
2235 *error_message = L"Client disconnected";
2236 errorstream << wide_to_narrow(*error_message) << std::endl;
2240 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2242 infostream << "Connect aborted [Escape]" << std::endl;
2249 if (!client->itemdefReceived()) {
2250 wchar_t *text = wgettext("Item definitions...");
2252 draw_load_screen(text, device, guienv, dtime, progress);
2254 } else if (!client->nodedefReceived()) {
2255 wchar_t *text = wgettext("Node definitions...");
2257 draw_load_screen(text, device, guienv, dtime, progress);
2260 std::stringstream message;
2261 message.precision(3);
2262 message << gettext("Media...");
2264 if ((USE_CURL == 0) ||
2265 (!g_settings->getBool("enable_remote_media_server"))) {
2266 float cur = client->getCurRate();
2267 std::string cur_unit = gettext(" KB/s");
2271 cur_unit = gettext(" MB/s");
2274 message << " ( " << cur << cur_unit << " )";
2277 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2278 draw_load_screen(narrow_to_wide(message.str().c_str()), device,
2279 guienv, dtime, progress);
2288 /****************************************************************************
2290 ****************************************************************************/
2292 inline void Game::updateInteractTimers(GameRunData *args, f32 dtime)
2294 if (args->nodig_delay_timer >= 0)
2295 args->nodig_delay_timer -= dtime;
2297 if (args->object_hit_delay_timer >= 0)
2298 args->object_hit_delay_timer -= dtime;
2300 args->time_from_last_punch += dtime;
2304 /* returns false if game should exit, otherwise true
2306 inline bool Game::checkConnection()
2308 if (client->accessDenied()) {
2309 *error_message = L"Access denied. Reason: "
2310 + client->accessDeniedReason();
2311 errorstream << wide_to_narrow(*error_message) << std::endl;
2319 /* returns false if game should exit, otherwise true
2321 inline bool Game::handleCallbacks()
2323 if (g_gamecallback->disconnect_requested) {
2324 g_gamecallback->disconnect_requested = false;
2328 if (g_gamecallback->changepassword_requested) {
2329 (new GUIPasswordChange(guienv, guiroot, -1,
2330 &g_menumgr, client))->drop();
2331 g_gamecallback->changepassword_requested = false;
2334 if (g_gamecallback->changevolume_requested) {
2335 (new GUIVolumeChange(guienv, guiroot, -1,
2336 &g_menumgr, client))->drop();
2337 g_gamecallback->changevolume_requested = false;
2340 if (g_gamecallback->keyconfig_requested) {
2341 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2342 &g_menumgr))->drop();
2343 g_gamecallback->keyconfig_requested = false;
2346 if (g_gamecallback->keyconfig_changed) {
2347 keycache.populate(); // update the cache with new settings
2348 g_gamecallback->keyconfig_changed = false;
2355 void Game::processQueues()
2357 texture_src->processQueue();
2358 itemdef_manager->processQueue(gamedef);
2359 shader_src->processQueue();
2363 void Game::updateProfilers(const GameRunData &run_data, const RunStats &stats,
2364 const FpsControl &draw_times, f32 dtime)
2366 float profiler_print_interval =
2367 g_settings->getFloat("profiler_print_interval");
2368 bool print_to_log = true;
2370 if (profiler_print_interval == 0) {
2371 print_to_log = false;
2372 profiler_print_interval = 5;
2375 if (profiler_interval.step(dtime, profiler_print_interval)) {
2377 infostream << "Profiler:" << std::endl;
2378 g_profiler->print(infostream);
2381 update_profiler_gui(guitext_profiler, g_fontengine,
2382 run_data.profiler_current_page, run_data.profiler_max_page,
2383 driver->getScreenSize().Height);
2385 g_profiler->clear();
2388 addProfilerGraphs(stats, draw_times, dtime);
2392 void Game::addProfilerGraphs(const RunStats &stats,
2393 const FpsControl &draw_times, f32 dtime)
2395 g_profiler->graphAdd("mainloop_other",
2396 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2398 if (draw_times.sleep_time != 0)
2399 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2400 g_profiler->graphAdd("mainloop_dtime", dtime);
2402 g_profiler->add("Elapsed time", dtime);
2403 g_profiler->avg("FPS", 1. / dtime);
2407 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2414 /* Time average and jitter calculation
2416 jp = &stats->dtime_jitter;
2417 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2419 jitter = dtime - jp->avg;
2421 if (jitter > jp->max)
2424 jp->counter += dtime;
2426 if (jp->counter > 0.0) {
2428 jp->max_sample = jp->max;
2429 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2433 /* Busytime average and jitter calculation
2435 jp = &stats->busy_time_jitter;
2436 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2438 jitter = draw_times.busy_time - jp->avg;
2440 if (jitter > jp->max)
2442 if (jitter < jp->min)
2445 jp->counter += dtime;
2447 if (jp->counter > 0.0) {
2449 jp->max_sample = jp->max;
2450 jp->min_sample = jp->min;
2458 /****************************************************************************
2460 ****************************************************************************/
2462 void Game::processUserInput(VolatileRunFlags *flags,
2463 GameRunData *interact_args, f32 dtime)
2465 // Reset input if window not active or some menu is active
2466 if (device->isWindowActive() == false
2467 || noMenuActive() == false
2468 || guienv->hasFocus(gui_chat_console)) {
2472 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2473 gui_chat_console->closeConsoleAtOnce();
2476 // Input handler step() (used by the random input generator)
2479 #ifdef HAVE_TOUCHSCREENGUI
2481 if (g_touchscreengui) {
2482 g_touchscreengui->step(dtime);
2488 if (current_formspec != 0)
2489 current_formspec->getAndroidUIInput();
2493 // Increase timer for double tap of "keymap_jump"
2494 if (m_cache_doubletap_jump && interact_args->jump_timer <= 0.2)
2495 interact_args->jump_timer += dtime;
2497 processKeyboardInput(
2499 &interact_args->statustext_time,
2500 &interact_args->jump_timer,
2501 &interact_args->reset_jump_timer,
2502 &interact_args->profiler_current_page,
2503 interact_args->profiler_max_page);
2505 processItemSelection(&interact_args->new_playeritem);
2509 void Game::processKeyboardInput(VolatileRunFlags *flags,
2510 float *statustext_time,
2512 bool *reset_jump_timer,
2513 u32 *profiler_current_page,
2514 u32 profiler_max_page)
2517 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2519 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2521 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2523 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2524 show_pause_menu(¤t_formspec, client, gamedef, texture_src, device,
2525 simple_singleplayer_mode);
2526 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2527 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2529 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2530 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2532 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2534 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2535 toggleFreeMove(statustext_time);
2536 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2537 toggleFreeMoveAlt(statustext_time, jump_timer);
2538 *reset_jump_timer = true;
2539 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2540 toggleFast(statustext_time);
2541 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2542 toggleNoClip(statustext_time);
2543 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2544 client->makeScreenshot(device);
2545 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2546 toggleHud(statustext_time, &flags->show_hud);
2547 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2548 toggleChat(statustext_time, &flags->show_chat);
2549 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2550 toggleFog(statustext_time, &flags->force_fog_off);
2551 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2552 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2553 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2554 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2555 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2556 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2557 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2558 increaseViewRange(statustext_time);
2559 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2560 decreaseViewRange(statustext_time);
2561 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2562 toggleFullViewRange(statustext_time);
2563 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
2565 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
2567 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
2569 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
2571 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2572 // Print debug stacks
2573 dstream << "-----------------------------------------"
2575 dstream << DTIME << "Printing debug stacks:" << std::endl;
2576 dstream << "-----------------------------------------"
2578 debug_stacks_print();
2581 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2582 *reset_jump_timer = false;
2588 if (quicktune->hasMessage()) {
2589 std::string msg = quicktune->getMessage();
2590 statustext = narrow_to_wide(msg);
2591 *statustext_time = 0;
2596 void Game::processItemSelection(u16 *new_playeritem)
2598 LocalPlayer *player = client->getEnv().getLocalPlayer();
2600 /* Item selection using mouse wheel
2602 *new_playeritem = client->getPlayerItem();
2604 s32 wheel = input->getMouseWheel();
2605 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2606 player->hud_hotbar_itemcount - 1);
2609 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2611 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2615 /* Item selection using keyboard
2617 for (u16 i = 0; i < 10; i++) {
2618 static const KeyPress *item_keys[10] = {
2619 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2620 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2621 NumberKey + 9, NumberKey + 0,
2624 if (input->wasKeyDown(*item_keys[i])) {
2625 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2626 *new_playeritem = i;
2627 infostream << "Selected item: " << new_playeritem << std::endl;
2635 void Game::dropSelectedItem()
2637 IDropAction *a = new IDropAction();
2639 a->from_inv.setCurrentPlayer();
2640 a->from_list = "main";
2641 a->from_i = client->getPlayerItem();
2642 client->inventoryAction(a);
2646 void Game::openInventory()
2648 infostream << "the_game: " << "Launching inventory" << std::endl;
2650 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2651 TextDest *txt_dst = new TextDestPlayerInventory(client);
2653 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2654 device, fs_src, txt_dst, client);
2656 InventoryLocation inventoryloc;
2657 inventoryloc.setCurrentPlayer();
2658 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2662 void Game::openConsole()
2664 if (!gui_chat_console->isOpenInhibited()) {
2665 // Open up to over half of the screen
2666 gui_chat_console->openConsole(0.6);
2667 guienv->setFocus(gui_chat_console);
2672 void Game::toggleFreeMove(float *statustext_time)
2674 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2676 bool free_move = !g_settings->getBool("free_move");
2677 g_settings->set("free_move", bool_to_cstr(free_move));
2679 *statustext_time = 0;
2680 statustext = msg[free_move];
2681 if (free_move && !client->checkPrivilege("fly"))
2682 statustext += L" (note: no 'fly' privilege)";
2686 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2688 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2689 toggleFreeMove(statustext_time);
2693 void Game::toggleFast(float *statustext_time)
2695 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2696 bool fast_move = !g_settings->getBool("fast_move");
2697 g_settings->set("fast_move", bool_to_cstr(fast_move));
2699 *statustext_time = 0;
2700 statustext = msg[fast_move];
2702 if (fast_move && !client->checkPrivilege("fast"))
2703 statustext += L" (note: no 'fast' privilege)";
2707 void Game::toggleNoClip(float *statustext_time)
2709 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2710 bool noclip = !g_settings->getBool("noclip");
2711 g_settings->set("noclip", bool_to_cstr(noclip));
2713 *statustext_time = 0;
2714 statustext = msg[noclip];
2716 if (noclip && !client->checkPrivilege("noclip"))
2717 statustext += L" (note: no 'noclip' privilege)";
2721 void Game::toggleChat(float *statustext_time, bool *flag)
2723 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2726 *statustext_time = 0;
2727 statustext = msg[*flag];
2731 void Game::toggleHud(float *statustext_time, bool *flag)
2733 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2736 *statustext_time = 0;
2737 statustext = msg[*flag];
2738 if (g_settings->getBool("enable_node_highlighting"))
2739 client->setHighlighted(client->getHighlighted(), *flag);
2743 void Game::toggleFog(float *statustext_time, bool *flag)
2745 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2748 *statustext_time = 0;
2749 statustext = msg[*flag];
2753 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2754 bool *show_profiler_graph)
2756 // Initial / 3x toggle: Chat only
2757 // 1x toggle: Debug text with chat
2758 // 2x toggle: Debug text with profiler graph
2761 *show_profiler_graph = false;
2762 statustext = L"Debug info shown";
2763 } else if (*show_profiler_graph) {
2764 *show_debug = false;
2765 *show_profiler_graph = false;
2766 statustext = L"Debug info and profiler graph hidden";
2768 *show_profiler_graph = true;
2769 statustext = L"Profiler graph shown";
2771 *statustext_time = 0;
2775 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
2777 static const wchar_t *msg[] = {
2778 L"Camera update enabled",
2779 L"Camera update disabled"
2783 *statustext_time = 0;
2784 statustext = msg[*flag];
2788 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
2789 u32 profiler_max_page)
2791 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
2793 // FIXME: This updates the profiler with incomplete values
2794 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
2795 profiler_max_page, driver->getScreenSize().Height);
2797 if (*profiler_current_page != 0) {
2798 std::wstringstream sstr;
2799 sstr << "Profiler shown (page " << *profiler_current_page
2800 << " of " << profiler_max_page << ")";
2801 statustext = sstr.str();
2803 statustext = L"Profiler hidden";
2805 *statustext_time = 0;
2809 void Game::increaseViewRange(float *statustext_time)
2811 s16 range = g_settings->getS16("viewing_range_nodes_min");
2812 s16 range_new = range + 10;
2813 g_settings->set("viewing_range_nodes_min", itos(range_new));
2814 statustext = narrow_to_wide("Minimum viewing range changed to "
2816 *statustext_time = 0;
2820 void Game::decreaseViewRange(float *statustext_time)
2822 s16 range = g_settings->getS16("viewing_range_nodes_min");
2823 s16 range_new = range - 10;
2828 g_settings->set("viewing_range_nodes_min", itos(range_new));
2829 statustext = narrow_to_wide("Minimum viewing range changed to "
2831 *statustext_time = 0;
2835 void Game::toggleFullViewRange(float *statustext_time)
2837 static const wchar_t *msg[] = {
2838 L"Disabled full viewing range",
2839 L"Enabled full viewing range"
2842 draw_control->range_all = !draw_control->range_all;
2843 infostream << msg[draw_control->range_all] << std::endl;
2844 statustext = msg[draw_control->range_all];
2845 *statustext_time = 0;
2849 void Game::updateCameraDirection(CameraOrientation *cam,
2850 VolatileRunFlags *flags)
2852 if ((device->isWindowActive() && noMenuActive()) || random_input) {
2855 if (!random_input) {
2856 // Mac OSX gets upset if this is set every frame
2857 if (device->getCursorControl()->isVisible())
2858 device->getCursorControl()->setVisible(false);
2862 if (flags->first_loop_after_window_activation)
2863 flags->first_loop_after_window_activation = false;
2865 updateCameraOrientation(cam, *flags);
2867 input->setMousePos((driver->getScreenSize().Width / 2),
2868 (driver->getScreenSize().Height / 2));
2872 // Mac OSX gets upset if this is set every frame
2873 if (device->getCursorControl()->isVisible() == false)
2874 device->getCursorControl()->setVisible(true);
2877 if (!flags->first_loop_after_window_activation)
2878 flags->first_loop_after_window_activation = true;
2884 void Game::updateCameraOrientation(CameraOrientation *cam,
2885 const VolatileRunFlags &flags)
2887 #ifdef HAVE_TOUCHSCREENGUI
2888 if (g_touchscreengui) {
2889 cam->camera_yaw = g_touchscreengui->getYaw();
2890 cam->camera_pitch = g_touchscreengui->getPitch();
2893 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
2894 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
2896 if (flags.invert_mouse
2897 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2901 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
2902 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
2904 #ifdef HAVE_TOUCHSCREENGUI
2908 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2912 void Game::updatePlayerControl(const CameraOrientation &cam)
2914 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2916 PlayerControl control(
2917 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
2918 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
2919 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
2920 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
2921 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
2922 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
2923 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
2924 input->getLeftState(),
2925 input->getRightState(),
2929 client->setPlayerControl(control);
2930 LocalPlayer *player = client->getEnv().getLocalPlayer();
2931 player->keyPressed =
2932 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
2933 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
2934 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
2935 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
2936 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
2937 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
2938 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
2939 ( (u32)(input->getLeftState() & 0x1) << 7) |
2940 ( (u32)(input->getRightState() & 0x1) << 8
2947 inline void Game::step(f32 *dtime)
2949 bool can_be_and_is_paused =
2950 (simple_singleplayer_mode && g_menumgr.pausesGame());
2952 if (can_be_and_is_paused) { // This is for a singleplayer server
2953 *dtime = 0; // No time passes
2955 if (server != NULL) {
2956 //TimeTaker timer("server->step(dtime)");
2957 server->step(*dtime);
2960 //TimeTaker timer("client.step(dtime)");
2961 client->step(*dtime);
2966 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
2968 ClientEvent event = client->getClientEvent();
2970 LocalPlayer *player = client->getEnv().getLocalPlayer();
2972 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
2974 if (event.type == CE_PLAYER_DAMAGE &&
2975 client->getHP() != 0) {
2976 //u16 damage = event.player_damage.amount;
2977 //infostream<<"Player damage: "<<damage<<std::endl;
2979 *damage_flash += 100.0;
2980 *damage_flash += 8.0 * event.player_damage.amount;
2982 player->hurt_tilt_timer = 1.5;
2983 player->hurt_tilt_strength = event.player_damage.amount / 4;
2984 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
2986 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2987 gamedef->event()->put(e);
2988 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
2989 cam->camera_yaw = event.player_force_move.yaw;
2990 cam->camera_pitch = event.player_force_move.pitch;
2991 } else if (event.type == CE_DEATHSCREEN) {
2992 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
2995 chat_backend->addMessage(L"", L"You died.");
2997 /* Handle visualization */
2999 player->hurt_tilt_timer = 0;
3000 player->hurt_tilt_strength = 0;
3002 } else if (event.type == CE_SHOW_FORMSPEC) {
3003 FormspecFormSource *fs_src =
3004 new FormspecFormSource(*(event.show_formspec.formspec));
3005 TextDestPlayerInventory *txt_dst =
3006 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3008 create_formspec_menu(¤t_formspec, client, gamedef,
3009 texture_src, device, fs_src, txt_dst, client);
3011 delete(event.show_formspec.formspec);
3012 delete(event.show_formspec.formname);
3013 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3014 (event.type == CE_ADD_PARTICLESPAWNER) ||
3015 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3016 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3018 } else if (event.type == CE_HUDADD) {
3019 u32 id = event.hudadd.id;
3021 LocalPlayer *player = client->getEnv().getLocalPlayer();
3022 HudElement *e = player->getHud(id);
3025 delete event.hudadd.pos;
3026 delete event.hudadd.name;
3027 delete event.hudadd.scale;
3028 delete event.hudadd.text;
3029 delete event.hudadd.align;
3030 delete event.hudadd.offset;
3031 delete event.hudadd.world_pos;
3032 delete event.hudadd.size;
3037 e->type = (HudElementType)event.hudadd.type;
3038 e->pos = *event.hudadd.pos;
3039 e->name = *event.hudadd.name;
3040 e->scale = *event.hudadd.scale;
3041 e->text = *event.hudadd.text;
3042 e->number = event.hudadd.number;
3043 e->item = event.hudadd.item;
3044 e->dir = event.hudadd.dir;
3045 e->align = *event.hudadd.align;
3046 e->offset = *event.hudadd.offset;
3047 e->world_pos = *event.hudadd.world_pos;
3048 e->size = *event.hudadd.size;
3050 u32 new_id = player->addHud(e);
3051 //if this isn't true our huds aren't consistent
3052 assert(new_id == id);
3054 delete event.hudadd.pos;
3055 delete event.hudadd.name;
3056 delete event.hudadd.scale;
3057 delete event.hudadd.text;
3058 delete event.hudadd.align;
3059 delete event.hudadd.offset;
3060 delete event.hudadd.world_pos;
3061 delete event.hudadd.size;
3062 } else if (event.type == CE_HUDRM) {
3063 HudElement *e = player->removeHud(event.hudrm.id);
3067 } else if (event.type == CE_HUDCHANGE) {
3068 u32 id = event.hudchange.id;
3069 HudElement *e = player->getHud(id);
3072 delete event.hudchange.v3fdata;
3073 delete event.hudchange.v2fdata;
3074 delete event.hudchange.sdata;
3075 delete event.hudchange.v2s32data;
3079 switch (event.hudchange.stat) {
3081 e->pos = *event.hudchange.v2fdata;
3085 e->name = *event.hudchange.sdata;
3088 case HUD_STAT_SCALE:
3089 e->scale = *event.hudchange.v2fdata;
3093 e->text = *event.hudchange.sdata;
3096 case HUD_STAT_NUMBER:
3097 e->number = event.hudchange.data;
3101 e->item = event.hudchange.data;
3105 e->dir = event.hudchange.data;
3108 case HUD_STAT_ALIGN:
3109 e->align = *event.hudchange.v2fdata;
3112 case HUD_STAT_OFFSET:
3113 e->offset = *event.hudchange.v2fdata;
3116 case HUD_STAT_WORLD_POS:
3117 e->world_pos = *event.hudchange.v3fdata;
3121 e->size = *event.hudchange.v2s32data;
3125 delete event.hudchange.v3fdata;
3126 delete event.hudchange.v2fdata;
3127 delete event.hudchange.sdata;
3128 delete event.hudchange.v2s32data;
3129 } else if (event.type == CE_SET_SKY) {
3130 sky->setVisible(false);
3137 // Handle according to type
3138 if (*event.set_sky.type == "regular") {
3139 sky->setVisible(true);
3140 } else if (*event.set_sky.type == "skybox" &&
3141 event.set_sky.params->size() == 6) {
3142 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3143 skybox = smgr->addSkyBoxSceneNode(
3144 texture_src->getTexture((*event.set_sky.params)[0]),
3145 texture_src->getTexture((*event.set_sky.params)[1]),
3146 texture_src->getTexture((*event.set_sky.params)[2]),
3147 texture_src->getTexture((*event.set_sky.params)[3]),
3148 texture_src->getTexture((*event.set_sky.params)[4]),
3149 texture_src->getTexture((*event.set_sky.params)[5]));
3151 // Handle everything else as plain color
3153 if (*event.set_sky.type != "plain")
3154 infostream << "Unknown sky type: "
3155 << (*event.set_sky.type) << std::endl;
3157 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3160 delete event.set_sky.bgcolor;
3161 delete event.set_sky.type;
3162 delete event.set_sky.params;
3163 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3164 bool enable = event.override_day_night_ratio.do_override;
3165 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3166 client->getEnv().setDayNightRatioOverride(enable, value);
3172 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3173 f32 dtime, float time_from_last_punch)
3175 LocalPlayer *player = client->getEnv().getLocalPlayer();
3178 For interaction purposes, get info about the held item
3180 - Is it a usable item?
3181 - Can it point to liquids?
3183 ItemStack playeritem;
3185 InventoryList *mlist = local_inventory->getList("main");
3187 if (mlist && client->getPlayerItem() < mlist->getSize())
3188 playeritem = mlist->getItem(client->getPlayerItem());
3191 ToolCapabilities playeritem_toolcap =
3192 playeritem.getToolCapabilities(itemdef_manager);
3194 v3s16 old_camera_offset = camera->getOffset();
3196 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3197 camera->toggleCameraMode();
3198 GenericCAO *playercao = player->getCAO();
3200 assert(playercao != NULL);
3202 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3205 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3206 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3208 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3209 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3211 camera->step(dtime);
3213 v3f camera_position = camera->getPosition();
3214 v3f camera_direction = camera->getDirection();
3215 f32 camera_fov = camera->getFovMax();
3216 v3s16 camera_offset = camera->getOffset();
3218 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3220 if (!flags->disable_camera_update) {
3221 client->getEnv().getClientMap().updateCamera(camera_position,
3222 camera_direction, camera_fov, camera_offset);
3224 if (flags->camera_offset_changed) {
3225 client->updateCameraOffset(camera_offset);
3226 client->getEnv().updateCameraOffset(camera_offset);
3229 clouds->updateCameraOffset(camera_offset);
3235 void Game::updateSound(f32 dtime)
3237 // Update sound listener
3238 v3s16 camera_offset = camera->getOffset();
3239 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3240 v3f(0, 0, 0), // velocity
3241 camera->getDirection(),
3242 camera->getCameraNode()->getUpVector());
3243 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3246 // Update sound maker
3247 soundmaker->step(dtime);
3249 LocalPlayer *player = client->getEnv().getLocalPlayer();
3251 ClientMap &map = client->getEnv().getClientMap();
3252 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3253 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3257 void Game::processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
3258 GameRunData *runData, f32 dtime, bool show_hud, bool show_debug)
3260 LocalPlayer *player = client->getEnv().getLocalPlayer();
3262 ItemStack playeritem;
3264 InventoryList *mlist = local_inventory->getList("main");
3266 if (mlist && client->getPlayerItem() < mlist->getSize())
3267 playeritem = mlist->getItem(client->getPlayerItem());
3270 const ItemDefinition &playeritem_def =
3271 playeritem.getDefinition(itemdef_manager);
3273 v3f player_position = player->getPosition();
3274 v3f camera_position = camera->getPosition();
3275 v3f camera_direction = camera->getDirection();
3276 v3s16 camera_offset = camera->getOffset();
3280 Calculate what block is the crosshair pointing to
3283 f32 d = playeritem_def.range; // max. distance
3284 f32 d_hand = itemdef_manager->get("").range;
3286 if (d < 0 && d_hand >= 0)
3291 core::line3d<f32> shootline;
3293 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3295 shootline = core::line3d<f32>(camera_position,
3296 camera_position + camera_direction * BS * (d + 1));
3299 // prevent player pointing anything in front-view
3300 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3301 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3304 #ifdef HAVE_TOUCHSCREENGUI
3306 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3307 shootline = g_touchscreengui->getShootline();
3308 shootline.start += intToFloat(camera_offset, BS);
3309 shootline.end += intToFloat(camera_offset, BS);
3314 PointedThing pointed = getPointedThing(
3316 client, player_position, camera_direction,
3317 camera_position, shootline, d,
3318 playeritem_def.liquids_pointable,
3319 !runData->ldown_for_dig,
3323 runData->selected_object);
3325 if (pointed != runData->pointed_old) {
3326 infostream << "Pointing at " << pointed.dump() << std::endl;
3328 if (m_cache_enable_node_highlighting) {
3329 if (pointed.type == POINTEDTHING_NODE) {
3330 client->setHighlighted(pointed.node_undersurface, show_hud);
3332 client->setHighlighted(pointed.node_undersurface, false);
3339 - releasing left mouse button
3340 - pointing away from node
3342 if (runData->digging) {
3343 if (input->getLeftReleased()) {
3344 infostream << "Left button released"
3345 << " (stopped digging)" << std::endl;
3346 runData->digging = false;
3347 } else if (pointed != runData->pointed_old) {
3348 if (pointed.type == POINTEDTHING_NODE
3349 && runData->pointed_old.type == POINTEDTHING_NODE
3350 && pointed.node_undersurface
3351 == runData->pointed_old.node_undersurface) {
3352 // Still pointing to the same node, but a different face.
3355 infostream << "Pointing away from node"
3356 << " (stopped digging)" << std::endl;
3357 runData->digging = false;
3361 if (!runData->digging) {
3362 client->interact(1, runData->pointed_old);
3363 client->setCrack(-1, v3s16(0, 0, 0));
3364 runData->dig_time = 0.0;
3368 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3369 runData->ldown_for_dig = false;
3372 runData->left_punch = false;
3374 soundmaker->m_player_leftpunch_sound.name = "";
3376 if (input->getRightState())
3377 runData->repeat_rightclick_timer += dtime;
3379 runData->repeat_rightclick_timer = 0;
3381 if (playeritem_def.usable && input->getLeftState()) {
3382 if (input->getLeftClicked())
3383 client->interact(4, pointed);
3384 } else if (pointed.type == POINTEDTHING_NODE) {
3385 ToolCapabilities playeritem_toolcap =
3386 playeritem.getToolCapabilities(itemdef_manager);
3387 handlePointingAtNode(runData, pointed, playeritem_def,
3388 playeritem_toolcap, dtime);
3389 } else if (pointed.type == POINTEDTHING_OBJECT) {
3390 handlePointingAtObject(runData, pointed, playeritem,
3391 player_position, show_debug);
3392 } else if (input->getLeftState()) {
3393 // When button is held down in air, show continuous animation
3394 runData->left_punch = true;
3397 runData->pointed_old = pointed;
3399 if (runData->left_punch || input->getLeftClicked())
3400 camera->setDigging(0); // left click animation
3402 input->resetLeftClicked();
3403 input->resetRightClicked();
3405 input->resetLeftReleased();
3406 input->resetRightReleased();
3410 void Game::handlePointingAtNode(GameRunData *runData,
3411 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3412 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3414 v3s16 nodepos = pointed.node_undersurface;
3415 v3s16 neighbourpos = pointed.node_abovesurface;
3418 Check information text of node
3421 ClientMap &map = client->getEnv().getClientMap();
3422 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3425 infotext = narrow_to_wide(meta->getString("infotext"));
3427 MapNode n = map.getNodeNoEx(nodepos);
3429 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3430 infotext = L"Unknown node: ";
3431 infotext += narrow_to_wide(nodedef_manager->get(n).name);
3435 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3436 && client->checkPrivilege("interact")) {
3437 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3440 if ((input->getRightClicked() ||
3441 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3442 client->checkPrivilege("interact")) {
3443 runData->repeat_rightclick_timer = 0;
3444 infostream << "Ground right-clicked" << std::endl;
3446 if (meta && meta->getString("formspec") != "" && !random_input
3447 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3448 infostream << "Launching custom inventory view" << std::endl;
3450 InventoryLocation inventoryloc;
3451 inventoryloc.setNodeMeta(nodepos);
3453 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3454 &client->getEnv().getClientMap(), nodepos);
3455 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3457 create_formspec_menu(¤t_formspec, client, gamedef,
3458 texture_src, device, fs_src, txt_dst, client);
3460 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3462 // Report right click to server
3464 camera->setDigging(1); // right click animation (always shown for feedback)
3466 // If the wielded item has node placement prediction,
3468 bool placed = nodePlacementPrediction(*client,
3470 nodepos, neighbourpos);
3474 client->interact(3, pointed);
3476 soundmaker->m_player_rightpunch_sound =
3477 playeritem_def.sound_place;
3479 soundmaker->m_player_rightpunch_sound =
3483 if (playeritem_def.node_placement_prediction == "" ||
3484 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable)
3485 client->interact(3, pointed); // Report to server
3491 void Game::handlePointingAtObject(GameRunData *runData,
3492 const PointedThing &pointed,
3493 const ItemStack &playeritem,
3494 const v3f &player_position,
3497 infotext = narrow_to_wide(runData->selected_object->infoText());
3499 if (infotext == L"" && show_debug) {
3500 infotext = narrow_to_wide(runData->selected_object->debugInfoText());
3503 if (input->getLeftState()) {
3504 bool do_punch = false;
3505 bool do_punch_damage = false;
3507 if (runData->object_hit_delay_timer <= 0.0) {
3509 do_punch_damage = true;
3510 runData->object_hit_delay_timer = object_hit_delay;
3513 if (input->getLeftClicked())
3517 infostream << "Left-clicked object" << std::endl;
3518 runData->left_punch = true;
3521 if (do_punch_damage) {
3522 // Report direct punch
3523 v3f objpos = runData->selected_object->getPosition();
3524 v3f dir = (objpos - player_position).normalize();
3526 bool disable_send = runData->selected_object->directReportPunch(
3527 dir, &playeritem, runData->time_from_last_punch);
3528 runData->time_from_last_punch = 0;
3531 client->interact(0, pointed);
3533 } else if (input->getRightClicked()) {
3534 infostream << "Right-clicked object" << std::endl;
3535 client->interact(3, pointed); // place
3540 void Game::handleDigging(GameRunData *runData,
3541 const PointedThing &pointed, const v3s16 &nodepos,
3542 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3544 if (!runData->digging) {
3545 infostream << "Started digging" << std::endl;
3546 client->interact(0, pointed);
3547 runData->digging = true;
3548 runData->ldown_for_dig = true;
3551 LocalPlayer *player = client->getEnv().getLocalPlayer();
3552 ClientMap &map = client->getEnv().getClientMap();
3553 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3555 // NOTE: Similar piece of code exists on the server side for
3557 // Get digging parameters
3558 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3559 &playeritem_toolcap);
3561 // If can't dig, try hand
3562 if (!params.diggable) {
3563 const ItemDefinition &hand = itemdef_manager->get("");
3564 const ToolCapabilities *tp = hand.tool_capabilities;
3567 params = getDigParams(nodedef_manager->get(n).groups, tp);
3570 if (params.diggable == false) {
3571 // I guess nobody will wait for this long
3572 runData->dig_time_complete = 10000000.0;
3574 runData->dig_time_complete = params.time;
3576 if (m_cache_enable_particles) {
3577 const ContentFeatures &features =
3578 client->getNodeDefManager()->get(n);
3579 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3580 player, nodepos, features.tiles);
3584 if (runData->dig_time_complete >= 0.001) {
3585 runData->dig_index = (float)crack_animation_length
3587 / runData->dig_time_complete;
3589 // This is for torches
3590 runData->dig_index = crack_animation_length;
3593 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3595 if (sound_dig.exists() && params.diggable) {
3596 if (sound_dig.name == "__group") {
3597 if (params.main_group != "") {
3598 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3599 soundmaker->m_player_leftpunch_sound.name =
3600 std::string("default_dig_") +
3604 soundmaker->m_player_leftpunch_sound = sound_dig;
3608 // Don't show cracks if not diggable
3609 if (runData->dig_time_complete >= 100000.0) {
3610 } else if (runData->dig_index < crack_animation_length) {
3611 //TimeTaker timer("client.setTempMod");
3612 //infostream<<"dig_index="<<dig_index<<std::endl;
3613 client->setCrack(runData->dig_index, nodepos);
3615 infostream << "Digging completed" << std::endl;
3616 client->interact(2, pointed);
3617 client->setCrack(-1, v3s16(0, 0, 0));
3618 bool is_valid_position;
3619 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3620 if (is_valid_position)
3621 client->removeNode(nodepos);
3623 if (m_cache_enable_particles) {
3624 const ContentFeatures &features =
3625 client->getNodeDefManager()->get(wasnode);
3626 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3627 player, nodepos, features.tiles);
3630 runData->dig_time = 0;
3631 runData->digging = false;
3633 runData->nodig_delay_timer =
3634 runData->dig_time_complete / (float)crack_animation_length;
3636 // We don't want a corresponding delay to
3637 // very time consuming nodes
3638 if (runData->nodig_delay_timer > 0.3)
3639 runData->nodig_delay_timer = 0.3;
3641 // We want a slight delay to very little
3642 // time consuming nodes
3643 const float mindelay = 0.15;
3645 if (runData->nodig_delay_timer < mindelay)
3646 runData->nodig_delay_timer = mindelay;
3648 // Send event to trigger sound
3649 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3650 gamedef->event()->put(e);
3653 if (runData->dig_time_complete < 100000.0) {
3654 runData->dig_time += dtime;
3656 runData->dig_time = 0;
3657 client->setCrack(-1, nodepos);
3660 camera->setDigging(0); // left click animation
3664 void Game::updateFrame(std::vector<aabb3f> &highlight_boxes,
3665 ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
3666 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam)
3668 LocalPlayer *player = client->getEnv().getLocalPlayer();
3674 if (draw_control->range_all) {
3675 runData->fog_range = 100000 * BS;
3677 runData->fog_range = draw_control->wanted_range * BS
3678 + 0.0 * MAP_BLOCKSIZE * BS;
3679 runData->fog_range = MYMIN(
3681 (draw_control->farthest_drawn + 20) * BS);
3682 runData->fog_range *= 0.9;
3686 Calculate general brightness
3688 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3689 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3690 float direct_brightness;
3693 if (g_settings->getBool("free_move")) {
3694 direct_brightness = time_brightness;
3695 sunlight_seen = true;
3697 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3698 float old_brightness = sky->getBrightness();
3699 direct_brightness = client->getEnv().getClientMap()
3700 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3701 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3705 float time_of_day = runData->time_of_day;
3706 float time_of_day_smooth = runData->time_of_day_smooth;
3708 time_of_day = client->getEnv().getTimeOfDayF();
3710 const float maxsm = 0.05;
3711 const float todsm = 0.05;
3713 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3714 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3715 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3716 time_of_day_smooth = time_of_day;
3718 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3719 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3720 + (time_of_day + 1.0) * todsm;
3722 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3723 + time_of_day * todsm;
3725 runData->time_of_day = time_of_day;
3726 runData->time_of_day_smooth = time_of_day_smooth;
3728 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3729 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3730 player->getPitch());
3736 v3f player_position = player->getPosition();
3737 if (sky->getCloudsVisible()) {
3738 clouds->setVisible(true);
3739 clouds->step(dtime);
3740 clouds->update(v2f(player_position.X, player_position.Z),
3741 sky->getCloudColor());
3743 clouds->setVisible(false);
3750 client->getParticleManager()->step(dtime);
3756 if (m_cache_enable_fog && !flags.force_fog_off) {
3759 video::EFT_FOG_LINEAR,
3760 runData->fog_range * 0.4,
3761 runData->fog_range * 1.0,
3769 video::EFT_FOG_LINEAR,
3779 Get chat messages from client
3782 v2u32 screensize = driver->getScreenSize();
3784 updateChat(*client, dtime, flags.show_debug, screensize,
3785 flags.show_chat, runData->profiler_current_page,
3786 *chat_backend, guitext_chat);
3792 if (client->getPlayerItem() != runData->new_playeritem)
3793 client->selectPlayerItem(runData->new_playeritem);
3795 // Update local inventory if it has changed
3796 if (client->getLocalInventoryUpdated()) {
3797 //infostream<<"Updating local inventory"<<std::endl;
3798 client->getLocalInventory(*local_inventory);
3799 runData->update_wielded_item_trigger = true;
3802 if (runData->update_wielded_item_trigger) {
3803 // Update wielded tool
3804 InventoryList *mlist = local_inventory->getList("main");
3806 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
3807 ItemStack item = mlist->getItem(client->getPlayerItem());
3808 camera->wield(item);
3810 runData->update_wielded_item_trigger = false;
3814 Update block draw list every 200ms or when camera direction has
3817 runData->update_draw_list_timer += dtime;
3819 v3f camera_direction = camera->getDirection();
3820 if (runData->update_draw_list_timer >= 0.2
3821 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3822 || flags.camera_offset_changed) {
3823 runData->update_draw_list_timer = 0;
3824 client->getEnv().getClientMap().updateDrawList(driver);
3825 runData->update_draw_list_last_cam_dir = camera_direction;
3828 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
3831 make sure menu is on top
3832 1. Delete formspec menu reference if menu was removed
3833 2. Else, make sure formspec menu is on top
3835 if (current_formspec) {
3836 if (current_formspec->getReferenceCount() == 1) {
3837 current_formspec->drop();
3838 current_formspec = NULL;
3839 } else if (!noMenuActive()) {
3840 guiroot->bringToFront(current_formspec);
3848 video::SColor skycolor = sky->getSkyColor();
3850 TimeTaker tt_draw("mainloop: draw");
3852 TimeTaker timer("beginScene");
3853 driver->beginScene(true, true, skycolor);
3854 stats->beginscenetime = timer.stop(true);
3857 draw_scene(driver, smgr, *camera, *client, player, *hud, guienv,
3858 highlight_boxes, screensize, skycolor, flags.show_hud);
3863 if (flags.show_profiler_graph)
3864 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3869 if (runData->damage_flash > 0.0) {
3870 video::SColor color(std::min(runData->damage_flash, 180.0f),
3874 driver->draw2DRectangle(color,
3875 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3878 runData->damage_flash -= 100.0 * dtime;
3884 if (player->hurt_tilt_timer > 0.0) {
3885 player->hurt_tilt_timer -= dtime * 5;
3887 if (player->hurt_tilt_timer < 0)
3888 player->hurt_tilt_strength = 0;
3895 TimeTaker timer("endScene");
3897 stats->endscenetime = timer.stop(true);
3900 stats->drawtime = tt_draw.stop(true);
3901 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
3905 void Game::updateGui(float *statustext_time, const RunStats &stats,
3906 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
3907 const CameraOrientation &cam)
3909 v2u32 screensize = driver->getScreenSize();
3910 LocalPlayer *player = client->getEnv().getLocalPlayer();
3911 v3f player_position = player->getPosition();
3913 if (flags.show_debug) {
3914 static float drawtime_avg = 0;
3915 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
3917 u16 fps = 1.0 / stats.dtime_jitter.avg;
3918 //s32 fps = driver->getFPS();
3920 std::ostringstream os(std::ios_base::binary);
3922 << "Minetest " << minetest_version_hash
3924 << " (R: range_all=" << draw_control->range_all << ")"
3925 << std::setprecision(0)
3926 << " drawtime = " << drawtime_avg
3927 << std::setprecision(1)
3928 << ", dtime_jitter = "
3929 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
3930 << std::setprecision(1)
3931 << ", v_range = " << draw_control->wanted_range
3932 << std::setprecision(3)
3933 << ", RTT = " << client->getRTT();
3934 guitext->setText(narrow_to_wide(os.str()).c_str());
3935 guitext->setVisible(true);
3936 } else if (flags.show_hud || flags.show_chat) {
3937 std::ostringstream os(std::ios_base::binary);
3938 os << "Minetest " << minetest_version_hash;
3939 guitext->setText(narrow_to_wide(os.str()).c_str());
3940 guitext->setVisible(true);
3942 guitext->setVisible(false);
3945 if (guitext->isVisible()) {
3946 core::rect<s32> rect(
3948 screensize.X, 5 + g_fontengine->getTextHeight()
3950 guitext->setRelativePosition(rect);
3953 if (flags.show_debug) {
3954 std::ostringstream os(std::ios_base::binary);
3955 os << std::setprecision(1) << std::fixed
3956 << "(" << (player_position.X / BS)
3957 << ", " << (player_position.Y / BS)
3958 << ", " << (player_position.Z / BS)
3959 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
3960 << ") (seed = " << ((u64)client->getMapSeed())
3963 if (runData.pointed_old.type == POINTEDTHING_NODE) {
3964 ClientMap &map = client->getEnv().getClientMap();
3965 const INodeDefManager *nodedef = client->getNodeDefManager();
3966 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
3967 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
3968 const ContentFeatures &features = nodedef->get(n);
3969 os << " (pointing_at = " << nodedef->get(n).name
3970 << " - " << features.tiledef[0].name.c_str()
3975 guitext2->setText(narrow_to_wide(os.str()).c_str());
3976 guitext2->setVisible(true);
3978 core::rect<s32> rect(
3979 5, 5 + g_fontengine->getTextHeight(),
3980 screensize.X, 5 + g_fontengine->getTextHeight() * 2
3982 guitext2->setRelativePosition(rect);
3984 guitext2->setVisible(false);
3987 guitext_info->setText(infotext.c_str());
3988 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
3990 float statustext_time_max = 1.5;
3992 if (!statustext.empty()) {
3993 *statustext_time += dtime;
3995 if (*statustext_time >= statustext_time_max) {
3997 *statustext_time = 0;
4001 guitext_status->setText(statustext.c_str());
4002 guitext_status->setVisible(!statustext.empty());
4004 if (!statustext.empty()) {
4005 s32 status_width = guitext_status->getTextWidth();
4006 s32 status_height = guitext_status->getTextHeight();
4007 s32 status_y = screensize.Y - 150;
4008 s32 status_x = (screensize.X - status_width) / 2;
4009 core::rect<s32> rect(
4010 status_x , status_y - status_height,
4011 status_x + status_width, status_y
4013 guitext_status->setRelativePosition(rect);
4016 video::SColor initial_color(255, 0, 0, 0);
4018 if (guienv->getSkin())
4019 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4021 video::SColor final_color = initial_color;
4022 final_color.setAlpha(0);
4023 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4024 initial_color, final_color,
4025 pow(*statustext_time / statustext_time_max, 2.0f));
4026 guitext_status->setOverrideColor(fade_color);
4027 guitext_status->enableOverrideColor(true);
4032 /* Log times and stuff for visualization */
4033 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4035 Profiler::GraphValues values;
4036 g_profiler->graphGet(values);
4042 /****************************************************************************
4044 ****************************************************************************/
4046 /* On some computers framerate doesn't seem to be automatically limited
4048 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4050 // not using getRealTime is necessary for wine
4051 device->getTimer()->tick(); // Maker sure device time is up-to-date
4052 u32 time = device->getTimer()->getTime();
4054 u32 last_time = fps_timings->last_time;
4056 if (time > last_time) // Make sure time hasn't overflowed
4057 fps_timings->busy_time = time - last_time;
4059 fps_timings->busy_time = 0;
4061 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4062 ? g_settings->getFloat("pause_fps_max")
4063 : g_settings->getFloat("fps_max"));
4065 if (fps_timings->busy_time < frametime_min) {
4066 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4067 device->sleep(fps_timings->sleep_time);
4069 fps_timings->sleep_time = 0;
4072 /* Get the new value of the device timer. Note that device->sleep() may
4073 * not sleep for the entire requested time as sleep may be interrupted and
4074 * therefore it is arguably more accurate to get the new time from the
4075 * device rather than calculating it by adding sleep_time to time.
4078 device->getTimer()->tick(); // Update device timer
4079 time = device->getTimer()->getTime();
4081 if (time > last_time) // Make sure last_time hasn't overflowed
4082 *dtime = (time - last_time) / 1000.0;
4086 fps_timings->last_time = time;
4090 void Game::showOverlayMessage(const char *msg, float dtime,
4091 int percent, bool draw_clouds)
4093 wchar_t *text = wgettext(msg);
4094 draw_load_screen(text, device, guienv, dtime, percent, draw_clouds);
4099 /****************************************************************************
4101 ****************************************************************************/
4103 void Game::extendedResourceCleanup()
4105 // Extended resource accounting
4106 infostream << "Irrlicht resources after cleanup:" << std::endl;
4107 infostream << "\tRemaining meshes : "
4108 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4109 infostream << "\tRemaining textures : "
4110 << driver->getTextureCount() << std::endl;
4112 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4113 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4114 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4118 clearTextureNameCache();
4119 infostream << "\tRemaining materials: "
4120 << driver-> getMaterialRendererCount()
4121 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4126 /****************************************************************************
4127 extern function for launching the game
4128 ****************************************************************************/
4130 void the_game(bool *kill,
4132 InputHandler *input,
4133 IrrlichtDevice *device,
4135 const std::string &map_dir,
4136 const std::string &playername,
4137 const std::string &password,
4138 const std::string &address, // If empty local server is created
4141 std::wstring &error_message,
4142 ChatBackend &chat_backend,
4143 const SubgameSpec &gamespec, // Used for local game
4144 bool simple_singleplayer_mode)
4148 /* Make a copy of the server address because if a local singleplayer server
4149 * is created then this is updated and we don't want to change the value
4150 * passed to us by the calling function
4152 std::string server_address = address;
4156 if (game.startup(kill, random_input, input, device, map_dir,
4157 playername, password, &server_address, port,
4158 &error_message, &chat_backend, gamespec,
4159 simple_singleplayer_mode)) {
4165 } catch (SerializationError &e) {
4166 error_message = L"A serialization error occurred:\n"
4167 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
4168 L" running a different version of Minetest.";
4169 errorstream << wide_to_narrow(error_message) << std::endl;
4170 } catch (ServerError &e) {
4171 error_message = narrow_to_wide(e.what());
4172 errorstream << "ServerError: " << e.what() << std::endl;
4173 } catch (ModError &e) {
4174 errorstream << "ModError: " << e.what() << std::endl;
4175 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");