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.
25 #include "client/tile.h" // For TextureSource
26 #include "client/keys.h"
27 #include "client/joystick_controller.h"
28 #include "clientmap.h"
31 #include "content_cao.h"
32 #include "drawscene.h"
33 #include "event_manager.h"
34 #include "fontengine.h"
39 #include "guiChatConsole.h"
40 #include "guiFormSpecMenu.h"
41 #include "guiKeyChangeMenu.h"
42 #include "guiPasswordChange.h"
43 #include "guiVolumeChange.h"
44 #include "mainmenumanager.h"
46 #include "nodedef.h" // Needed for determining pointing to nodes
47 #include "nodemetadata.h"
48 #include "particles.h"
50 #include "quicktune_shortcutter.h"
53 #include "shader.h" // For ShaderSource
57 #include "util/directiontables.h"
58 #include "util/pointedthing.h"
59 #include "irrlicht_changes/static_text.h"
62 #include "mapblock_mesh.h"
63 #include "script/clientscripting.h"
68 #include "sound_openal.h"
71 #ifdef HAVE_TOUCHSCREENGUI
72 #include "touchscreengui.h"
75 extern Settings *g_settings;
76 extern Profiler *g_profiler;
82 struct TextDestNodeMetadata : public TextDest {
83 TextDestNodeMetadata(v3s16 p, Client *client)
88 // This is deprecated I guess? -celeron55
89 void gotText(std::wstring text)
91 std::string ntext = wide_to_utf8(text);
92 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
93 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
95 fields["text"] = ntext;
96 m_client->sendNodemetaFields(m_p, "", fields);
98 void gotText(const StringMap &fields)
100 m_client->sendNodemetaFields(m_p, "", fields);
107 struct TextDestPlayerInventory : public TextDest {
108 TextDestPlayerInventory(Client *client)
113 TextDestPlayerInventory(Client *client, std::string formname)
116 m_formname = formname;
118 void gotText(const StringMap &fields)
120 m_client->sendInventoryFields(m_formname, fields);
126 struct LocalFormspecHandler : public TextDest {
127 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(const StringMap &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()) {
182 m_client->getScript()->on_formspec_input(m_formname, fields);
188 /* Form update callback */
190 class NodeMetadataFormSource: public IFormSource
193 NodeMetadataFormSource(ClientMap *map, v3s16 p):
198 std::string getForm()
200 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
205 return meta->getString("formspec");
207 std::string resolveText(std::string str)
209 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
214 return meta->resolveString(str);
221 class PlayerInventoryFormSource: public IFormSource
224 PlayerInventoryFormSource(Client *client):
228 std::string getForm()
230 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
231 return player->inventory_formspec;
237 /* Profiler display */
239 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
240 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
242 if (show_profiler == 0) {
243 guitext_profiler->setVisible(false);
246 std::ostringstream os(std::ios_base::binary);
247 g_profiler->printPage(os, show_profiler, show_profiler_max);
248 std::wstring text = utf8_to_wide(os.str());
249 setStaticText(guitext_profiler, text.c_str());
250 guitext_profiler->setVisible(true);
252 s32 w = fe->getTextWidth(text.c_str());
257 unsigned text_height = fe->getTextHeight();
259 core::position2di upper_left, lower_right;
262 upper_left.Y = (text_height + 5) * 2;
263 lower_right.X = 12 + w;
264 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
266 if (lower_right.Y > screen_height * 2 / 3)
267 lower_right.Y = screen_height * 2 / 3;
269 core::rect<s32> rect(upper_left, lower_right);
271 guitext_profiler->setRelativePosition(rect);
272 guitext_profiler->setVisible(true);
280 Profiler::GraphValues values;
286 Meta(float initial = 0,
287 video::SColor color = video::SColor(255, 255, 255, 255)):
293 std::deque<Piece> m_log;
301 void put(const Profiler::GraphValues &values)
304 piece.values = values;
305 m_log.push_back(piece);
307 while (m_log.size() > m_log_max_size)
308 m_log.erase(m_log.begin());
311 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
312 gui::IGUIFont *font) const
314 // Do *not* use UNORDERED_MAP here as the order needs
315 // to be the same for each call to prevent flickering
316 std::map<std::string, Meta> m_meta;
318 for (std::deque<Piece>::const_iterator k = m_log.begin();
319 k != m_log.end(); ++k) {
320 const Piece &piece = *k;
322 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
323 i != piece.values.end(); ++i) {
324 const std::string &id = i->first;
325 const float &value = i->second;
326 std::map<std::string, Meta>::iterator j = m_meta.find(id);
328 if (j == m_meta.end()) {
329 m_meta[id] = Meta(value);
333 if (value < j->second.min)
334 j->second.min = value;
336 if (value > j->second.max)
337 j->second.max = value;
342 static const video::SColor usable_colors[] = {
343 video::SColor(255, 255, 100, 100),
344 video::SColor(255, 90, 225, 90),
345 video::SColor(255, 100, 100, 255),
346 video::SColor(255, 255, 150, 50),
347 video::SColor(255, 220, 220, 100)
349 static const u32 usable_colors_count =
350 sizeof(usable_colors) / sizeof(*usable_colors);
351 u32 next_color_i = 0;
353 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
354 i != m_meta.end(); ++i) {
355 Meta &meta = i->second;
356 video::SColor color(255, 200, 200, 200);
358 if (next_color_i < usable_colors_count)
359 color = usable_colors[next_color_i++];
365 s32 textx = x_left + m_log_max_size + 15;
366 s32 textx2 = textx + 200 - 15;
369 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
370 i != m_meta.end(); ++i) {
371 const std::string &id = i->first;
372 const Meta &meta = i->second;
374 s32 y = y_bottom - meta_i * 50;
375 float show_min = meta.min;
376 float show_max = meta.max;
378 if (show_min >= -0.0001 && show_max >= -0.0001) {
379 if (show_min <= show_max * 0.5)
385 snprintf(buf, 10, "%.3g", show_max);
386 font->draw(utf8_to_wide(buf).c_str(),
387 core::rect<s32>(textx, y - graphh,
388 textx2, y - graphh + texth),
390 snprintf(buf, 10, "%.3g", show_min);
391 font->draw(utf8_to_wide(buf).c_str(),
392 core::rect<s32>(textx, y - texth,
395 font->draw(utf8_to_wide(id).c_str(),
396 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
397 textx2, y - graphh / 2 + texth / 2),
400 s32 graph1h = graphh;
401 bool relativegraph = (show_min != 0 && show_min != show_max);
402 float lastscaledvalue = 0.0;
403 bool lastscaledvalue_exists = false;
405 for (std::deque<Piece>::const_iterator j = m_log.begin();
406 j != m_log.end(); ++j) {
407 const Piece &piece = *j;
409 bool value_exists = false;
410 Profiler::GraphValues::const_iterator k =
411 piece.values.find(id);
413 if (k != piece.values.end()) {
420 lastscaledvalue_exists = false;
424 float scaledvalue = 1.0;
426 if (show_max != show_min)
427 scaledvalue = (value - show_min) / (show_max - show_min);
429 if (scaledvalue == 1.0 && value == 0) {
431 lastscaledvalue_exists = false;
436 if (lastscaledvalue_exists) {
437 s32 ivalue1 = lastscaledvalue * graph1h;
438 s32 ivalue2 = scaledvalue * graph1h;
439 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
440 v2s32(x, graph1y - ivalue2), meta.color);
443 lastscaledvalue = scaledvalue;
444 lastscaledvalue_exists = true;
446 s32 ivalue = scaledvalue * graph1h;
447 driver->draw2DLine(v2s32(x, graph1y),
448 v2s32(x, graph1y - ivalue), meta.color);
459 class NodeDugEvent: public MtEvent
465 NodeDugEvent(v3s16 p, MapNode n):
469 const char *getType() const
477 ISoundManager *m_sound;
478 INodeDefManager *m_ndef;
480 float m_player_step_timer;
482 SimpleSoundSpec m_player_step_sound;
483 SimpleSoundSpec m_player_leftpunch_sound;
484 SimpleSoundSpec m_player_rightpunch_sound;
486 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
489 m_player_step_timer(0)
493 void playPlayerStep()
495 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
496 m_player_step_timer = 0.03;
497 m_sound->playSound(m_player_step_sound, false);
501 static void viewBobbingStep(MtEvent *e, void *data)
503 SoundMaker *sm = (SoundMaker *)data;
504 sm->playPlayerStep();
507 static void playerRegainGround(MtEvent *e, void *data)
509 SoundMaker *sm = (SoundMaker *)data;
510 sm->playPlayerStep();
513 static void playerJump(MtEvent *e, void *data)
515 //SoundMaker *sm = (SoundMaker*)data;
518 static void cameraPunchLeft(MtEvent *e, void *data)
520 SoundMaker *sm = (SoundMaker *)data;
521 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
524 static void cameraPunchRight(MtEvent *e, void *data)
526 SoundMaker *sm = (SoundMaker *)data;
527 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
530 static void nodeDug(MtEvent *e, void *data)
532 SoundMaker *sm = (SoundMaker *)data;
533 NodeDugEvent *nde = (NodeDugEvent *)e;
534 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
537 static void playerDamage(MtEvent *e, void *data)
539 SoundMaker *sm = (SoundMaker *)data;
540 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
543 static void playerFallingDamage(MtEvent *e, void *data)
545 SoundMaker *sm = (SoundMaker *)data;
546 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
549 void registerReceiver(MtEventManager *mgr)
551 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
552 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
553 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
554 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
555 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
556 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
557 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
558 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
561 void step(float dtime)
563 m_player_step_timer -= dtime;
567 // Locally stored sounds don't need to be preloaded because of this
568 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
570 std::set<std::string> m_fetched;
572 void fetchSounds(const std::string &name,
573 std::set<std::string> &dst_paths,
574 std::set<std::string> &dst_datas)
576 if (m_fetched.count(name))
579 m_fetched.insert(name);
580 std::string base = porting::path_share + DIR_DELIM + "sounds";
581 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
582 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
583 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
584 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
585 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
586 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
587 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
588 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
589 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
590 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
591 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
596 // before 1.8 there isn't a "integer interface", only float
597 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
598 typedef f32 SamplerLayer_t;
600 typedef s32 SamplerLayer_t;
604 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
607 bool *m_force_fog_off;
610 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
611 CachedPixelShaderSetting<float> m_fog_distance;
612 CachedVertexShaderSetting<float> m_animation_timer_vertex;
613 CachedPixelShaderSetting<float> m_animation_timer_pixel;
614 CachedPixelShaderSetting<float, 3> m_day_light;
615 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
616 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
617 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
618 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
619 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
620 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
624 void onSettingsChange(const std::string &name)
626 if (name == "enable_fog")
627 m_fog_enabled = g_settings->getBool("enable_fog");
630 static void settingsCallback(const std::string &name, void *userdata)
632 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
635 void setSky(Sky *sky) { m_sky = sky; }
637 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
638 f32 *fog_range, Client *client) :
640 m_force_fog_off(force_fog_off),
641 m_fog_range(fog_range),
642 m_sky_bg_color("skyBgColor"),
643 m_fog_distance("fogDistance"),
644 m_animation_timer_vertex("animationTimer"),
645 m_animation_timer_pixel("animationTimer"),
646 m_day_light("dayLight"),
647 m_eye_position_pixel("eyePosition"),
648 m_eye_position_vertex("eyePosition"),
649 m_minimap_yaw("yawVec"),
650 m_base_texture("baseTexture"),
651 m_normal_texture("normalTexture"),
652 m_texture_flags("textureFlags"),
655 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
656 m_fog_enabled = g_settings->getBool("enable_fog");
659 ~GameGlobalShaderConstantSetter()
661 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
664 virtual void onSetConstants(video::IMaterialRendererServices *services,
671 video::SColor bgcolor = m_sky->getBgColor();
672 video::SColorf bgcolorf(bgcolor);
673 float bgcolorfa[4] = {
679 m_sky_bg_color.set(bgcolorfa, services);
682 float fog_distance = 10000 * BS;
684 if (m_fog_enabled && !*m_force_fog_off)
685 fog_distance = *m_fog_range;
687 m_fog_distance.set(&fog_distance, services);
689 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
690 video::SColorf sunlight;
691 get_sunlight_color(&sunlight, daynight_ratio);
696 m_day_light.set(dnc, services);
698 u32 animation_timer = porting::getTimeMs() % 100000;
699 float animation_timer_f = (float)animation_timer / 100000.f;
700 m_animation_timer_vertex.set(&animation_timer_f, services);
701 m_animation_timer_pixel.set(&animation_timer_f, services);
703 float eye_position_array[3];
704 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
705 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
706 eye_position_array[0] = epos.X;
707 eye_position_array[1] = epos.Y;
708 eye_position_array[2] = epos.Z;
710 epos.getAs3Values(eye_position_array);
712 m_eye_position_pixel.set(eye_position_array, services);
713 m_eye_position_vertex.set(eye_position_array, services);
715 float minimap_yaw_array[3];
716 v3f minimap_yaw = m_client->getMapper()->getYawVec();
717 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
718 minimap_yaw_array[0] = minimap_yaw.X;
719 minimap_yaw_array[1] = minimap_yaw.Y;
720 minimap_yaw_array[2] = minimap_yaw.Z;
722 minimap_yaw.getAs3Values(minimap_yaw_array);
724 m_minimap_yaw.set(minimap_yaw_array, services);
726 SamplerLayer_t base_tex = 0,
729 m_base_texture.set(&base_tex, services);
730 m_normal_texture.set(&normal_tex, services);
731 m_texture_flags.set(&flags_tex, services);
736 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
739 bool *m_force_fog_off;
742 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
744 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
745 f32 *fog_range, Client *client) :
747 m_force_fog_off(force_fog_off),
748 m_fog_range(fog_range),
752 void setSky(Sky *sky) {
754 for (size_t i = 0; i < created_nosky.size(); ++i) {
755 created_nosky[i]->setSky(m_sky);
757 created_nosky.clear();
760 virtual IShaderConstantSetter* create()
762 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
763 m_sky, m_force_fog_off, m_fog_range, m_client);
765 created_nosky.push_back(scs);
771 bool nodePlacementPrediction(Client &client,
772 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
774 std::string prediction = playeritem_def.node_placement_prediction;
775 INodeDefManager *nodedef = client.ndef();
776 ClientMap &map = client.getEnv().getClientMap();
778 bool is_valid_position;
780 node = map.getNodeNoEx(nodepos, &is_valid_position);
781 if (!is_valid_position)
784 if (prediction != "" && !nodedef->get(node).rightclickable) {
785 verbosestream << "Node placement prediction for "
786 << playeritem_def.name << " is "
787 << prediction << std::endl;
788 v3s16 p = neighbourpos;
790 // Place inside node itself if buildable_to
791 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
792 if (is_valid_position)
794 if (nodedef->get(n_under).buildable_to)
797 node = map.getNodeNoEx(p, &is_valid_position);
798 if (is_valid_position &&!nodedef->get(node).buildable_to)
803 // Find id of predicted node
805 bool found = nodedef->getId(prediction, id);
808 errorstream << "Node placement prediction failed for "
809 << playeritem_def.name << " (places "
811 << ") - Name not known" << std::endl;
815 // Predict param2 for facedir and wallmounted nodes
818 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
819 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED) {
820 v3s16 dir = nodepos - neighbourpos;
822 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
823 param2 = dir.Y < 0 ? 1 : 0;
824 } else if (abs(dir.X) > abs(dir.Z)) {
825 param2 = dir.X < 0 ? 3 : 2;
827 param2 = dir.Z < 0 ? 5 : 4;
831 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR ||
832 nodedef->get(id).param_type_2 == CPT2_COLORED_FACEDIR) {
833 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
835 if (abs(dir.X) > abs(dir.Z)) {
836 param2 = dir.X < 0 ? 3 : 1;
838 param2 = dir.Z < 0 ? 2 : 0;
844 //Check attachment if node is in group attached_node
845 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
846 static v3s16 wallmounted_dirs[8] = {
856 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
857 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED)
858 pp = p + wallmounted_dirs[param2];
860 pp = p + v3s16(0, -1, 0);
862 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
866 // Add node to client map
867 MapNode n(id, 0, param2);
870 LocalPlayer *player = client.getEnv().getLocalPlayer();
872 // Dont place node when player would be inside new node
873 // NOTE: This is to be eventually implemented by a mod as client-side Lua
874 if (!nodedef->get(n).walkable ||
875 g_settings->getBool("enable_build_where_you_stand") ||
876 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
877 (nodedef->get(n).walkable &&
878 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
879 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
881 // This triggers the required mesh update too
882 client.addNode(p, n);
885 } catch (InvalidPositionException &e) {
886 errorstream << "Node placement prediction failed for "
887 << playeritem_def.name << " (places "
889 << ") - Position not loaded" << std::endl;
896 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
897 Client *client, IrrlichtDevice *device, JoystickController *joystick,
898 IFormSource *fs_src, TextDest *txt_dest)
901 if (*cur_formspec == 0) {
902 *cur_formspec = new GUIFormSpecMenu(device, joystick,
903 guiroot, -1, &g_menumgr, client, client->getTextureSource(),
905 (*cur_formspec)->doPause = false;
908 Caution: do not call (*cur_formspec)->drop() here --
909 the reference might outlive the menu, so we will
910 periodically check if *cur_formspec is the only
911 remaining reference (i.e. the menu was removed)
912 and delete it in that case.
916 (*cur_formspec)->setFormSource(fs_src);
917 (*cur_formspec)->setTextDest(txt_dest);
923 #define SIZE_TAG "size[11,5.5]"
925 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
928 /******************************************************************************/
929 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
931 IWritableTextureSource *tsrc, IrrlichtDevice *device,
932 JoystickController *joystick, bool singleplayermode)
935 std::string control_text = strgettext("Default Controls:\n"
937 "- single tap: button activate\n"
938 "- double tap: place/use\n"
939 "- slide finger: look around\n"
940 "Menu/Inventory visible:\n"
941 "- double tap (outside):\n"
943 "- touch stack, touch slot:\n"
945 "- touch&drag, tap 2nd finger\n"
946 " --> place single item to slot\n"
949 std::string control_text = strgettext("Default Controls:\n"
951 "- Space: jump/climb\n"
952 "- Shift: sneak/go down\n"
955 "- Mouse: turn/look\n"
956 "- Mouse left: dig/punch\n"
957 "- Mouse right: place/use\n"
958 "- Mouse wheel: select item\n"
963 float ypos = singleplayermode ? 0.5 : 0.1;
964 std::ostringstream os;
966 os << FORMSPEC_VERSION_STRING << SIZE_TAG
967 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
968 << strgettext("Continue") << "]";
970 if (!singleplayermode) {
971 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
972 << strgettext("Change Password") << "]";
976 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
977 << strgettext("Sound Volume") << "]";
978 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
979 << strgettext("Change Keys") << "]";
981 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
982 << strgettext("Exit to Menu") << "]";
983 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
984 << strgettext("Exit to OS") << "]"
985 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
986 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
987 << g_build_info << "\n"
988 << "path_user = " << wrap_rows(porting::path_user, 20)
992 /* Note: FormspecFormSource and LocalFormspecHandler *
993 * are deleted by guiFormSpecMenu */
994 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
995 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
997 create_formspec_menu(cur_formspec, client, device, joystick, fs_src, txt_dst);
998 std::string con("btn_continue");
999 (*cur_formspec)->setFocus(con);
1000 (*cur_formspec)->doPause = true;
1003 /******************************************************************************/
1004 static void updateChat(Client &client, f32 dtime, bool show_debug,
1005 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1006 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1008 // Add chat log output for errors to be shown in chat
1009 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
1011 // Get new messages from error log buffer
1012 while (!chat_log_error_buf.empty()) {
1013 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
1014 if (!g_settings->getBool("disable_escape_sequences")) {
1015 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
1017 chat_backend.addMessage(L"", error_message);
1020 // Get new messages from client
1021 std::wstring message;
1023 while (client.getChatMessage(message)) {
1024 chat_backend.addUnparsedMessage(message);
1027 // Remove old messages
1028 chat_backend.step(dtime);
1030 // Display all messages in a static text element
1031 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1032 EnrichedString recent_chat = chat_backend.getRecentChat();
1033 unsigned int line_height = g_fontengine->getLineHeight();
1035 setStaticText(guitext_chat, recent_chat);
1037 // Update gui element size and position
1041 chat_y += 2 * line_height;
1043 // first pass to calculate height of text to be set
1044 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
1045 porting::getWindowSize().X - 20);
1046 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1047 guitext_chat->setRelativePosition(rect);
1049 //now use real height of text and adjust rect according to this size
1050 rect = core::rect<s32>(10, chat_y, width,
1051 chat_y + guitext_chat->getTextHeight());
1054 guitext_chat->setRelativePosition(rect);
1055 // Don't show chat if disabled or empty or profiler is enabled
1056 guitext_chat->setVisible(
1057 show_chat && recent_chat_count != 0 && !show_profiler);
1061 /****************************************************************************
1062 Fast key cache for main game loop
1063 ****************************************************************************/
1065 /* This is faster than using getKeySetting with the tradeoff that functions
1066 * using it must make sure that it's initialised before using it and there is
1067 * no error handling (for example bounds checking). This is really intended for
1068 * use only in the main running loop of the client (the_game()) where the faster
1069 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1070 * (e.g. formspecs) should continue using getKeySetting().
1078 populate_nonchanging();
1083 // Keys that are not settings dependent
1084 void populate_nonchanging();
1086 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1087 InputHandler *handler;
1090 void KeyCache::populate_nonchanging()
1092 key[KeyType::ESC] = EscapeKey;
1095 void KeyCache::populate()
1097 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1098 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1099 key[KeyType::LEFT] = getKeySetting("keymap_left");
1100 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1101 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1102 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1103 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1105 key[KeyType::AUTORUN] = getKeySetting("keymap_autorun");
1107 key[KeyType::DROP] = getKeySetting("keymap_drop");
1108 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1109 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1110 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1111 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1112 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1113 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1114 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1115 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1116 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1117 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1118 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1119 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1120 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1121 = getKeySetting("keymap_toggle_force_fog_off");
1122 key[KeyType::TOGGLE_UPDATE_CAMERA]
1123 = getKeySetting("keymap_toggle_update_camera");
1124 key[KeyType::TOGGLE_DEBUG]
1125 = getKeySetting("keymap_toggle_debug");
1126 key[KeyType::TOGGLE_PROFILER]
1127 = getKeySetting("keymap_toggle_profiler");
1128 key[KeyType::CAMERA_MODE]
1129 = getKeySetting("keymap_camera_mode");
1130 key[KeyType::INCREASE_VIEWING_RANGE]
1131 = getKeySetting("keymap_increase_viewing_range_min");
1132 key[KeyType::DECREASE_VIEWING_RANGE]
1133 = getKeySetting("keymap_decrease_viewing_range_min");
1134 key[KeyType::RANGESELECT]
1135 = getKeySetting("keymap_rangeselect");
1136 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1138 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1139 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1140 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1141 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1143 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1146 // First clear all keys, then re-add the ones we listen for
1147 handler->dontListenForKeys();
1148 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1149 handler->listenForKey(key[i]);
1151 handler->listenForKey(EscapeKey);
1152 handler->listenForKey(CancelKey);
1153 for (size_t i = 0; i < 10; i++) {
1154 handler->listenForKey(NumberKey[i]);
1160 /****************************************************************************
1162 ****************************************************************************/
1164 const float object_hit_delay = 0.2;
1167 u32 last_time, busy_time, sleep_time;
1171 /* The reason the following structs are not anonymous structs within the
1172 * class is that they are not used by the majority of member functions and
1173 * many functions that do require objects of thse types do not modify them
1174 * (so they can be passed as a const qualified parameter)
1176 struct CameraOrientation {
1177 f32 camera_yaw; // "right/left"
1178 f32 camera_pitch; // "up/down"
1181 struct GameRunData {
1184 PointedThing pointed_old;
1188 bool update_wielded_item_trigger;
1189 bool reset_jump_timer;
1190 float nodig_delay_timer;
1192 float dig_time_complete;
1193 float repeat_rightclick_timer;
1194 float object_hit_delay_timer;
1195 float time_from_last_punch;
1196 ClientActiveObject *selected_object;
1200 float update_draw_list_timer;
1201 float statustext_time;
1205 v3f update_draw_list_last_cam_dir;
1207 u32 profiler_current_page;
1208 u32 profiler_max_page; // Number of pages
1211 float time_of_day_smooth;
1215 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1223 Jitter dtime_jitter, busy_time_jitter;
1226 /* Flags that can, or may, change during main game loop
1228 struct VolatileRunFlags {
1235 bool show_profiler_graph;
1236 bool disable_camera_update;
1237 bool first_loop_after_window_activation;
1238 bool camera_offset_changed;
1242 /****************************************************************************
1244 ****************************************************************************/
1246 /* This is not intended to be a public class. If a public class becomes
1247 * desirable then it may be better to create another 'wrapper' class that
1248 * hides most of the stuff in this class (nothing in this class is required
1249 * by any other file) but exposes the public methods/data only.
1256 bool startup(bool *kill,
1258 InputHandler *input,
1259 IrrlichtDevice *device,
1260 const std::string &map_dir,
1261 const std::string &playername,
1262 const std::string &password,
1263 // If address is "", local server is used and address is updated
1264 std::string *address,
1266 std::string &error_message,
1268 ChatBackend *chat_backend,
1269 const SubgameSpec &gamespec, // Used for local game
1270 bool simple_singleplayer_mode);
1277 void extendedResourceCleanup();
1279 // Basic initialisation
1280 bool init(const std::string &map_dir, std::string *address,
1282 const SubgameSpec &gamespec);
1284 bool createSingleplayerServer(const std::string map_dir,
1285 const SubgameSpec &gamespec, u16 port, std::string *address);
1288 bool createClient(const std::string &playername,
1289 const std::string &password, std::string *address, u16 port);
1292 // Client connection
1293 bool connectToServer(const std::string &playername,
1294 const std::string &password, std::string *address, u16 port,
1295 bool *connect_ok, bool *aborted);
1296 bool getServerContent(bool *aborted);
1300 void updateInteractTimers(GameRunData *runData, f32 dtime);
1301 bool checkConnection();
1302 bool handleCallbacks();
1303 void processQueues();
1304 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1305 const FpsControl &draw_times, f32 dtime);
1306 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1308 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1311 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1313 void processKeyInput(VolatileRunFlags *flags,
1314 float *statustext_time,
1316 bool *reset_jump_timer,
1317 u32 *profiler_current_page,
1318 u32 profiler_max_page);
1319 void processItemSelection(u16 *new_playeritem);
1321 void dropSelectedItem();
1322 void openInventory();
1323 void openConsole(float scale, const wchar_t *line=NULL);
1324 void toggleFreeMove(float *statustext_time);
1325 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1326 void toggleFast(float *statustext_time);
1327 void toggleNoClip(float *statustext_time);
1328 void toggleCinematic(float *statustext_time);
1329 void toggleAutorun(float *statustext_time);
1331 void toggleChat(float *statustext_time, bool *flag);
1332 void toggleHud(float *statustext_time, bool *flag);
1333 void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
1334 bool shift_pressed);
1335 void toggleFog(float *statustext_time, bool *flag);
1336 void toggleDebug(float *statustext_time, bool *show_debug,
1337 bool *show_profiler_graph, bool *show_wireframe);
1338 void toggleUpdateCamera(float *statustext_time, bool *flag);
1339 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1340 u32 profiler_max_page);
1342 void increaseViewRange(float *statustext_time);
1343 void decreaseViewRange(float *statustext_time);
1344 void toggleFullViewRange(float *statustext_time);
1346 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags,
1348 void updateCameraOrientation(CameraOrientation *cam,
1349 const VolatileRunFlags &flags, float dtime);
1350 void updatePlayerControl(const CameraOrientation &cam);
1351 void step(f32 *dtime);
1352 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1353 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1354 float time_from_last_punch);
1355 void updateSound(f32 dtime);
1356 void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud,
1359 * Returns the object or node the player is pointing at.
1360 * Also updates the selected thing in the Hud.
1362 * @param[in] shootline the shootline, starting from
1363 * the camera position. This also gives the maximal distance
1365 * @param[in] liquids_pointable if false, liquids are ignored
1366 * @param[in] look_for_object if false, objects are ignored
1367 * @param[in] camera_offset offset of the camera
1368 * @param[out] selected_object the selected object or
1371 PointedThing updatePointedThing(
1372 const core::line3d<f32> &shootline, bool liquids_pointable,
1373 bool look_for_object, const v3s16 &camera_offset,
1374 ClientActiveObject *&selected_object);
1375 void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
1376 void handlePointingAtNode(GameRunData *runData,
1377 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1378 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1379 void handlePointingAtObject(GameRunData *runData,
1380 const PointedThing &pointed, const ItemStack &playeritem,
1381 const v3f &player_position, bool show_debug);
1382 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1383 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1385 void updateFrame(ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
1386 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1387 void updateGui(float *statustext_time, const RunStats &stats,
1388 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1389 const CameraOrientation &cam);
1390 void updateProfilerGraphs(ProfilerGraph *graph);
1393 void limitFps(FpsControl *fps_timings, f32 *dtime);
1395 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1396 bool draw_clouds = true);
1398 static void settingChangedCallback(const std::string &setting_name, void *data);
1399 void readSettings();
1401 inline bool getLeftClicked()
1403 return input->getLeftClicked() ||
1404 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1406 inline bool getRightClicked()
1408 return input->getRightClicked() ||
1409 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1411 inline bool isLeftPressed()
1413 return input->getLeftState() ||
1414 input->joystick.isKeyDown(KeyType::MOUSE_L);
1416 inline bool isRightPressed()
1418 return input->getRightState() ||
1419 input->joystick.isKeyDown(KeyType::MOUSE_R);
1421 inline bool getLeftReleased()
1423 return input->getLeftReleased() ||
1424 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1427 inline bool isKeyDown(GameKeyType k)
1429 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1431 inline bool wasKeyDown(GameKeyType k)
1433 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1437 void handleAndroidChatInput();
1441 InputHandler *input;
1446 IWritableTextureSource *texture_src;
1447 IWritableShaderSource *shader_src;
1449 // When created, these will be filled with data received from the server
1450 IWritableItemDefManager *itemdef_manager;
1451 IWritableNodeDefManager *nodedef_manager;
1453 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1454 ISoundManager *sound;
1455 bool sound_is_dummy;
1456 SoundMaker *soundmaker;
1458 ChatBackend *chat_backend;
1460 GUIFormSpecMenu *current_formspec;
1461 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1462 std::string cur_formname;
1464 EventManager *eventmgr;
1465 QuicktuneShortcutter *quicktune;
1467 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1468 MapDrawControl *draw_control;
1470 Clouds *clouds; // Free using ->Drop()
1471 Sky *sky; // Free using ->Drop()
1472 Inventory *local_inventory;
1476 GameRunData runData;
1477 VolatileRunFlags flags;
1480 This class does take ownership/responsibily for cleaning up etc of any of
1481 these items (e.g. device)
1483 IrrlichtDevice *device;
1484 video::IVideoDriver *driver;
1485 scene::ISceneManager *smgr;
1487 std::string *error_message;
1488 bool *reconnect_requested;
1489 scene::ISceneNode *skybox;
1492 bool simple_singleplayer_mode;
1495 /* Pre-calculated values
1497 int crack_animation_length;
1501 gui::IGUIStaticText *guitext; // First line of debug text
1502 gui::IGUIStaticText *guitext2; // Second line of debug text
1503 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1504 gui::IGUIStaticText *guitext_status;
1505 gui::IGUIStaticText *guitext_chat; // Chat text
1506 gui::IGUIStaticText *guitext_profiler; // Profiler text
1508 std::wstring infotext;
1509 std::wstring statustext;
1513 IntervalLimiter profiler_interval;
1516 * TODO: Local caching of settings is not optimal and should at some stage
1517 * be updated to use a global settings object for getting thse values
1518 * (as opposed to the this local caching). This can be addressed in
1521 bool m_cache_doubletap_jump;
1522 bool m_cache_enable_clouds;
1523 bool m_cache_enable_joysticks;
1524 bool m_cache_enable_particles;
1525 bool m_cache_enable_fog;
1526 bool m_cache_enable_noclip;
1527 bool m_cache_enable_free_move;
1528 f32 m_cache_mouse_sensitivity;
1529 f32 m_cache_joystick_frustum_sensitivity;
1530 f32 m_repeat_right_click_time;
1531 f32 m_cache_cam_smoothing;
1532 f32 m_cache_fog_start;
1535 bool m_cache_hold_aux1;
1536 bool m_android_chat_open;
1545 itemdef_manager(NULL),
1546 nodedef_manager(NULL),
1548 sound_is_dummy(false),
1551 current_formspec(NULL),
1555 gui_chat_console(NULL),
1560 local_inventory(NULL),
1564 g_settings->registerChangedCallback("doubletap_jump",
1565 &settingChangedCallback, this);
1566 g_settings->registerChangedCallback("enable_clouds",
1567 &settingChangedCallback, this);
1568 g_settings->registerChangedCallback("doubletap_joysticks",
1569 &settingChangedCallback, this);
1570 g_settings->registerChangedCallback("enable_particles",
1571 &settingChangedCallback, this);
1572 g_settings->registerChangedCallback("enable_fog",
1573 &settingChangedCallback, this);
1574 g_settings->registerChangedCallback("mouse_sensitivity",
1575 &settingChangedCallback, this);
1576 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1577 &settingChangedCallback, this);
1578 g_settings->registerChangedCallback("repeat_rightclick_time",
1579 &settingChangedCallback, this);
1580 g_settings->registerChangedCallback("noclip",
1581 &settingChangedCallback, this);
1582 g_settings->registerChangedCallback("free_move",
1583 &settingChangedCallback, this);
1584 g_settings->registerChangedCallback("cinematic",
1585 &settingChangedCallback, this);
1586 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1587 &settingChangedCallback, this);
1588 g_settings->registerChangedCallback("camera_smoothing",
1589 &settingChangedCallback, this);
1594 m_cache_hold_aux1 = false; // This is initialised properly later
1601 /****************************************************************************
1603 ****************************************************************************/
1609 if (!sound_is_dummy)
1612 delete server; // deleted first to stop all server threads
1615 delete local_inventory;
1621 delete nodedef_manager;
1622 delete itemdef_manager;
1623 delete draw_control;
1625 extendedResourceCleanup();
1627 g_settings->deregisterChangedCallback("doubletap_jump",
1628 &settingChangedCallback, this);
1629 g_settings->deregisterChangedCallback("enable_clouds",
1630 &settingChangedCallback, this);
1631 g_settings->deregisterChangedCallback("enable_particles",
1632 &settingChangedCallback, this);
1633 g_settings->deregisterChangedCallback("enable_fog",
1634 &settingChangedCallback, this);
1635 g_settings->deregisterChangedCallback("mouse_sensitivity",
1636 &settingChangedCallback, this);
1637 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1638 &settingChangedCallback, this);
1639 g_settings->deregisterChangedCallback("noclip",
1640 &settingChangedCallback, this);
1641 g_settings->deregisterChangedCallback("free_move",
1642 &settingChangedCallback, this);
1643 g_settings->deregisterChangedCallback("cinematic",
1644 &settingChangedCallback, this);
1645 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1646 &settingChangedCallback, this);
1647 g_settings->deregisterChangedCallback("camera_smoothing",
1648 &settingChangedCallback, this);
1651 bool Game::startup(bool *kill,
1653 InputHandler *input,
1654 IrrlichtDevice *device,
1655 const std::string &map_dir,
1656 const std::string &playername,
1657 const std::string &password,
1658 std::string *address, // can change if simple_singleplayer_mode
1660 std::string &error_message,
1662 ChatBackend *chat_backend,
1663 const SubgameSpec &gamespec,
1664 bool simple_singleplayer_mode)
1667 this->device = device;
1669 this->error_message = &error_message;
1670 this->reconnect_requested = reconnect;
1671 this->random_input = random_input;
1672 this->input = input;
1673 this->chat_backend = chat_backend;
1674 this->simple_singleplayer_mode = simple_singleplayer_mode;
1676 keycache.handler = input;
1677 keycache.populate();
1679 driver = device->getVideoDriver();
1680 smgr = device->getSceneManager();
1682 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1684 memset(&runData, 0, sizeof(runData));
1685 runData.time_from_last_punch = 10.0;
1686 runData.profiler_max_page = 3;
1687 runData.update_wielded_item_trigger = true;
1689 memset(&flags, 0, sizeof(flags));
1690 flags.show_chat = true;
1691 flags.show_hud = true;
1692 flags.show_debug = g_settings->getBool("show_debug");
1693 flags.invert_mouse = g_settings->getBool("invert_mouse");
1694 flags.first_loop_after_window_activation = true;
1696 if (!init(map_dir, address, port, gamespec))
1699 if (!createClient(playername, password, address, port))
1708 ProfilerGraph graph;
1709 RunStats stats = { 0 };
1710 CameraOrientation cam_view_target = { 0 };
1711 CameraOrientation cam_view = { 0 };
1712 FpsControl draw_times = { 0 };
1713 f32 dtime; // in seconds
1715 /* Clear the profiler */
1716 Profiler::GraphValues dummyvalues;
1717 g_profiler->graphGet(dummyvalues);
1719 draw_times.last_time = device->getTimer()->getTime();
1721 set_light_table(g_settings->getFloat("display_gamma"));
1724 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1725 && client->checkPrivilege("fast");
1728 while (device->run()
1729 && !(*kill || g_gamecallback->shutdown_requested
1730 || (server && server->getShutdownRequested()))) {
1732 /* Must be called immediately after a device->run() call because it
1733 * uses device->getTimer()->getTime()
1735 limitFps(&draw_times, &dtime);
1737 updateStats(&stats, draw_times, dtime);
1738 updateInteractTimers(&runData, dtime);
1740 if (!checkConnection())
1742 if (!handleCallbacks())
1748 hud->resizeHotbar();
1750 updateProfilers(runData, stats, draw_times, dtime);
1751 processUserInput(&flags, &runData, dtime);
1752 // Update camera before player movement to avoid camera lag of one frame
1753 updateCameraDirection(&cam_view_target, &flags, dtime);
1754 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1755 cam_view.camera_yaw) * m_cache_cam_smoothing;
1756 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1757 cam_view.camera_pitch) * m_cache_cam_smoothing;
1758 updatePlayerControl(cam_view);
1760 processClientEvents(&cam_view_target, &runData.damage_flash);
1761 updateCamera(&flags, draw_times.busy_time, dtime,
1762 runData.time_from_last_punch);
1764 processPlayerInteraction(&runData, dtime, flags.show_hud,
1766 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
1767 updateProfilerGraphs(&graph);
1769 // Update if minimap has been disabled by the server
1770 flags.show_minimap &= !client->isMinimapDisabledByServer();
1775 void Game::shutdown()
1777 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1778 if (g_settings->get("3d_mode") == "pageflip") {
1779 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1783 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1788 if (gui_chat_console)
1789 gui_chat_console->drop();
1795 while (g_menumgr.menuCount() > 0) {
1796 g_menumgr.m_stack.front()->setVisible(false);
1797 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1800 if (current_formspec) {
1801 current_formspec->drop();
1802 current_formspec = NULL;
1805 chat_backend->addMessage(L"", L"# Disconnected.");
1806 chat_backend->addMessage(L"", L"");
1810 while (!client->isShutdown()) {
1811 assert(texture_src != NULL);
1812 assert(shader_src != NULL);
1813 texture_src->processQueue();
1814 shader_src->processQueue();
1821 /****************************************************************************/
1822 /****************************************************************************
1824 ****************************************************************************/
1825 /****************************************************************************/
1828 const std::string &map_dir,
1829 std::string *address,
1831 const SubgameSpec &gamespec)
1833 showOverlayMessage(wgettext("Loading..."), 0, 0);
1835 texture_src = createTextureSource(device);
1836 shader_src = createShaderSource(device);
1838 itemdef_manager = createItemDefManager();
1839 nodedef_manager = createNodeDefManager();
1841 eventmgr = new EventManager();
1842 quicktune = new QuicktuneShortcutter();
1844 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1845 && eventmgr && quicktune))
1851 // Create a server if not connecting to an existing one
1852 if (*address == "") {
1853 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1860 bool Game::initSound()
1863 if (g_settings->getBool("enable_sound")) {
1864 infostream << "Attempting to use OpenAL audio" << std::endl;
1865 sound = createOpenALSoundManager(&soundfetcher);
1867 infostream << "Failed to initialize OpenAL audio" << std::endl;
1869 infostream << "Sound disabled." << std::endl;
1873 infostream << "Using dummy audio." << std::endl;
1874 sound = &dummySoundManager;
1875 sound_is_dummy = true;
1878 soundmaker = new SoundMaker(sound, nodedef_manager);
1882 soundmaker->registerReceiver(eventmgr);
1887 bool Game::createSingleplayerServer(const std::string map_dir,
1888 const SubgameSpec &gamespec, u16 port, std::string *address)
1890 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1892 std::string bind_str = g_settings->get("bind_address");
1893 Address bind_addr(0, 0, 0, 0, port);
1895 if (g_settings->getBool("ipv6_server")) {
1896 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1900 bind_addr.Resolve(bind_str.c_str());
1901 } catch (ResolveError &e) {
1902 infostream << "Resolving bind address \"" << bind_str
1903 << "\" failed: " << e.what()
1904 << " -- Listening on all addresses." << std::endl;
1907 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1908 *error_message = "Unable to listen on " +
1909 bind_addr.serializeString() +
1910 " because IPv6 is disabled";
1911 errorstream << *error_message << std::endl;
1915 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1916 bind_addr.isIPv6());
1918 server->start(bind_addr);
1923 bool Game::createClient(const std::string &playername,
1924 const std::string &password, std::string *address, u16 port)
1926 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1928 draw_control = new MapDrawControl;
1932 bool could_connect, connect_aborted;
1934 if (!connectToServer(playername, password, address, port,
1935 &could_connect, &connect_aborted))
1938 if (!could_connect) {
1939 if (error_message->empty() && !connect_aborted) {
1940 // Should not happen if error messages are set properly
1941 *error_message = "Connection failed for unknown reason";
1942 errorstream << *error_message << std::endl;
1947 if (!getServerContent(&connect_aborted)) {
1948 if (error_message->empty() && !connect_aborted) {
1949 // Should not happen if error messages are set properly
1950 *error_message = "Connection failed for unknown reason";
1951 errorstream << *error_message << std::endl;
1956 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1957 &flags.force_fog_off, &runData.fog_range, client);
1958 shader_src->addShaderConstantSetterFactory(scsf);
1960 // Update cached textures, meshes and materials
1961 client->afterContentReceived(device);
1965 camera = new Camera(smgr, *draw_control, client);
1966 if (!camera || !camera->successfullyCreated(*error_message))
1968 client->setCamera(camera);
1972 if (m_cache_enable_clouds) {
1973 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1975 *error_message = "Memory allocation error (clouds)";
1976 errorstream << *error_message << std::endl;
1983 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
1985 skybox = NULL; // This is used/set later on in the main run loop
1987 local_inventory = new Inventory(itemdef_manager);
1989 if (!(sky && local_inventory)) {
1990 *error_message = "Memory allocation error (sky or local inventory)";
1991 errorstream << *error_message << std::endl;
1995 /* Pre-calculated values
1997 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1999 v2u32 size = t->getOriginalSize();
2000 crack_animation_length = size.Y / size.X;
2002 crack_animation_length = 5;
2008 /* Set window caption
2010 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2012 str += utf8_to_wide(g_version_hash);
2014 str += driver->getName();
2016 device->setWindowCaption(str.c_str());
2018 LocalPlayer *player = client->getEnv().getLocalPlayer();
2019 player->hurt_tilt_timer = 0;
2020 player->hurt_tilt_strength = 0;
2022 hud = new Hud(driver, smgr, guienv, client, player, local_inventory);
2025 *error_message = "Memory error: could not create HUD";
2026 errorstream << *error_message << std::endl;
2030 mapper = client->getMapper();
2031 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2036 bool Game::initGui()
2038 // First line of debug text
2039 guitext = addStaticText(guienv,
2040 utf8_to_wide(PROJECT_NAME_C).c_str(),
2041 core::rect<s32>(0, 0, 0, 0),
2042 false, false, guiroot);
2044 // Second line of debug text
2045 guitext2 = addStaticText(guienv,
2047 core::rect<s32>(0, 0, 0, 0),
2048 false, false, guiroot);
2050 // At the middle of the screen
2051 // Object infos are shown in this
2052 guitext_info = addStaticText(guienv,
2054 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2055 false, true, guiroot);
2057 // Status text (displays info when showing and hiding GUI stuff, etc.)
2058 guitext_status = addStaticText(guienv,
2060 core::rect<s32>(0, 0, 0, 0),
2061 false, false, guiroot);
2062 guitext_status->setVisible(false);
2065 guitext_chat = addStaticText(
2068 core::rect<s32>(0, 0, 0, 0),
2069 //false, false); // Disable word wrap as of now
2070 false, true, guiroot);
2072 // Remove stale "recent" chat messages from previous connections
2073 chat_backend->clearRecentChat();
2075 // Chat backend and console
2076 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2077 -1, chat_backend, client, &g_menumgr);
2078 if (!gui_chat_console) {
2079 *error_message = "Could not allocate memory for chat console";
2080 errorstream << *error_message << std::endl;
2084 // Profiler text (size is updated when text is updated)
2085 guitext_profiler = addStaticText(guienv,
2087 core::rect<s32>(0, 0, 0, 0),
2088 false, false, guiroot);
2089 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2090 guitext_profiler->setVisible(false);
2091 guitext_profiler->setWordWrap(true);
2093 #ifdef HAVE_TOUCHSCREENGUI
2095 if (g_touchscreengui)
2096 g_touchscreengui->init(texture_src);
2103 bool Game::connectToServer(const std::string &playername,
2104 const std::string &password, std::string *address, u16 port,
2105 bool *connect_ok, bool *aborted)
2107 *connect_ok = false; // Let's not be overly optimistic
2109 bool local_server_mode = false;
2111 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2113 Address connect_address(0, 0, 0, 0, port);
2116 connect_address.Resolve(address->c_str());
2118 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2119 //connect_address.Resolve("localhost");
2120 if (connect_address.isIPv6()) {
2121 IPv6AddressBytes addr_bytes;
2122 addr_bytes.bytes[15] = 1;
2123 connect_address.setAddress(&addr_bytes);
2125 connect_address.setAddress(127, 0, 0, 1);
2127 local_server_mode = true;
2129 } catch (ResolveError &e) {
2130 *error_message = std::string("Couldn't resolve address: ") + e.what();
2131 errorstream << *error_message << std::endl;
2135 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2136 *error_message = "Unable to connect to " +
2137 connect_address.serializeString() +
2138 " because IPv6 is disabled";
2139 errorstream << *error_message << std::endl;
2143 client = new Client(device,
2144 playername.c_str(), password,
2145 *draw_control, texture_src, shader_src,
2146 itemdef_manager, nodedef_manager, sound, eventmgr,
2147 connect_address.isIPv6());
2152 infostream << "Connecting to server at ";
2153 connect_address.print(&infostream);
2154 infostream << std::endl;
2156 client->connect(connect_address, *address,
2157 simple_singleplayer_mode || local_server_mode);
2160 Wait for server to accept connection
2166 FpsControl fps_control = { 0 };
2168 f32 wait_time = 0; // in seconds
2170 fps_control.last_time = device->getTimer()->getTime();
2174 while (device->run()) {
2176 limitFps(&fps_control, &dtime);
2178 // Update client and server
2179 client->step(dtime);
2182 server->step(dtime);
2185 if (client->getState() == LC_Init) {
2191 if (client->accessDenied()) {
2192 *error_message = "Access denied. Reason: "
2193 + client->accessDeniedReason();
2194 *reconnect_requested = client->reconnectRequested();
2195 errorstream << *error_message << std::endl;
2199 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2201 infostream << "Connect aborted [Escape]" << std::endl;
2206 // Only time out if we aren't waiting for the server we started
2207 if ((*address != "") && (wait_time > 10)) {
2208 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2209 // If no pre v25 init was sent, and no answer was received,
2210 // but the low level connection could be established
2211 // (meaning that we have a peer id), then we probably wanted
2212 // to connect to a legacy server. In this case, tell the user
2213 // to enable the option to be able to connect.
2214 if (!sent_old_init &&
2215 (client->getProtoVersion() == 0) &&
2216 client->connectedToServer()) {
2217 *error_message = "Connection failure: init packet not "
2218 "recognized by server.\n"
2219 "Most likely the server uses an old protocol version (<v25).\n"
2220 "Please ask the server owner to update to 0.4.13 or later.\n"
2221 "To still connect to the server in the meantime,\n"
2222 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2223 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2224 "entry in the advanced settings menu.";
2226 *error_message = "Connection timed out.";
2228 errorstream << *error_message << std::endl;
2233 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2235 } catch (con::PeerNotFoundException &e) {
2236 // TODO: Should something be done here? At least an info/error
2244 bool Game::getServerContent(bool *aborted)
2248 FpsControl fps_control = { 0 };
2249 f32 dtime; // in seconds
2251 fps_control.last_time = device->getTimer()->getTime();
2253 while (device->run()) {
2255 limitFps(&fps_control, &dtime);
2257 // Update client and server
2258 client->step(dtime);
2261 server->step(dtime);
2264 if (client->mediaReceived() && client->itemdefReceived() &&
2265 client->nodedefReceived()) {
2270 if (!checkConnection())
2273 if (client->getState() < LC_Init) {
2274 *error_message = "Client disconnected";
2275 errorstream << *error_message << std::endl;
2279 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2281 infostream << "Connect aborted [Escape]" << std::endl;
2288 if (!client->itemdefReceived()) {
2289 const wchar_t *text = wgettext("Item definitions...");
2291 draw_load_screen(text, device, guienv, dtime, progress);
2293 } else if (!client->nodedefReceived()) {
2294 const wchar_t *text = wgettext("Node definitions...");
2296 draw_load_screen(text, device, guienv, dtime, progress);
2299 std::stringstream message;
2300 message.precision(3);
2301 message << gettext("Media...");
2303 if ((USE_CURL == 0) ||
2304 (!g_settings->getBool("enable_remote_media_server"))) {
2305 float cur = client->getCurRate();
2306 std::string cur_unit = gettext("KiB/s");
2310 cur_unit = gettext("MiB/s");
2313 message << " (" << cur << ' ' << cur_unit << ")";
2316 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2317 draw_load_screen(utf8_to_wide(message.str()), device,
2318 guienv, dtime, progress);
2326 /****************************************************************************/
2327 /****************************************************************************
2329 ****************************************************************************/
2330 /****************************************************************************/
2332 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2334 if (runData->nodig_delay_timer >= 0)
2335 runData->nodig_delay_timer -= dtime;
2337 if (runData->object_hit_delay_timer >= 0)
2338 runData->object_hit_delay_timer -= dtime;
2340 runData->time_from_last_punch += dtime;
2344 /* returns false if game should exit, otherwise true
2346 inline bool Game::checkConnection()
2348 if (client->accessDenied()) {
2349 *error_message = "Access denied. Reason: "
2350 + client->accessDeniedReason();
2351 *reconnect_requested = client->reconnectRequested();
2352 errorstream << *error_message << std::endl;
2360 /* returns false if game should exit, otherwise true
2362 inline bool Game::handleCallbacks()
2364 if (g_gamecallback->disconnect_requested) {
2365 g_gamecallback->disconnect_requested = false;
2369 if (g_gamecallback->changepassword_requested) {
2370 (new GUIPasswordChange(guienv, guiroot, -1,
2371 &g_menumgr, client))->drop();
2372 g_gamecallback->changepassword_requested = false;
2375 if (g_gamecallback->changevolume_requested) {
2376 (new GUIVolumeChange(guienv, guiroot, -1,
2377 &g_menumgr))->drop();
2378 g_gamecallback->changevolume_requested = false;
2381 if (g_gamecallback->keyconfig_requested) {
2382 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2383 &g_menumgr))->drop();
2384 g_gamecallback->keyconfig_requested = false;
2387 if (g_gamecallback->keyconfig_changed) {
2388 keycache.populate(); // update the cache with new settings
2389 g_gamecallback->keyconfig_changed = false;
2396 void Game::processQueues()
2398 texture_src->processQueue();
2399 itemdef_manager->processQueue(client);
2400 shader_src->processQueue();
2404 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2405 const FpsControl &draw_times, f32 dtime)
2407 float profiler_print_interval =
2408 g_settings->getFloat("profiler_print_interval");
2409 bool print_to_log = true;
2411 if (profiler_print_interval == 0) {
2412 print_to_log = false;
2413 profiler_print_interval = 5;
2416 if (profiler_interval.step(dtime, profiler_print_interval)) {
2418 infostream << "Profiler:" << std::endl;
2419 g_profiler->print(infostream);
2422 update_profiler_gui(guitext_profiler, g_fontengine,
2423 runData.profiler_current_page, runData.profiler_max_page,
2424 driver->getScreenSize().Height);
2426 g_profiler->clear();
2429 addProfilerGraphs(stats, draw_times, dtime);
2433 void Game::addProfilerGraphs(const RunStats &stats,
2434 const FpsControl &draw_times, f32 dtime)
2436 g_profiler->graphAdd("mainloop_other",
2437 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2439 if (draw_times.sleep_time != 0)
2440 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2441 g_profiler->graphAdd("mainloop_dtime", dtime);
2443 g_profiler->add("Elapsed time", dtime);
2444 g_profiler->avg("FPS", 1. / dtime);
2448 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2455 /* Time average and jitter calculation
2457 jp = &stats->dtime_jitter;
2458 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2460 jitter = dtime - jp->avg;
2462 if (jitter > jp->max)
2465 jp->counter += dtime;
2467 if (jp->counter > 0.0) {
2469 jp->max_sample = jp->max;
2470 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2474 /* Busytime average and jitter calculation
2476 jp = &stats->busy_time_jitter;
2477 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2479 jitter = draw_times.busy_time - jp->avg;
2481 if (jitter > jp->max)
2483 if (jitter < jp->min)
2486 jp->counter += dtime;
2488 if (jp->counter > 0.0) {
2490 jp->max_sample = jp->max;
2491 jp->min_sample = jp->min;
2499 /****************************************************************************
2501 ****************************************************************************/
2503 void Game::processUserInput(VolatileRunFlags *flags,
2504 GameRunData *runData, f32 dtime)
2506 // Reset input if window not active or some menu is active
2507 if (device->isWindowActive() == false
2508 || noMenuActive() == false
2509 || guienv->hasFocus(gui_chat_console)) {
2511 #ifdef HAVE_TOUCHSCREENGUI
2512 g_touchscreengui->hide();
2515 #ifdef HAVE_TOUCHSCREENGUI
2516 else if (g_touchscreengui) {
2517 /* on touchscreengui step may generate own input events which ain't
2518 * what we want in case we just did clear them */
2519 g_touchscreengui->step(dtime);
2523 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2524 gui_chat_console->closeConsoleAtOnce();
2527 // Input handler step() (used by the random input generator)
2531 if (current_formspec != NULL)
2532 current_formspec->getAndroidUIInput();
2534 handleAndroidChatInput();
2537 // Increase timer for double tap of "keymap_jump"
2538 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2539 runData->jump_timer += dtime;
2543 &runData->statustext_time,
2544 &runData->jump_timer,
2545 &runData->reset_jump_timer,
2546 &runData->profiler_current_page,
2547 runData->profiler_max_page);
2549 processItemSelection(&runData->new_playeritem);
2553 void Game::processKeyInput(VolatileRunFlags *flags,
2554 float *statustext_time,
2556 bool *reset_jump_timer,
2557 u32 *profiler_current_page,
2558 u32 profiler_max_page)
2561 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2563 if (wasKeyDown(KeyType::DROP)) {
2565 } else if (wasKeyDown(KeyType::AUTORUN)) {
2566 toggleAutorun(statustext_time);
2567 } else if (wasKeyDown(KeyType::INVENTORY)) {
2569 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2570 if (!gui_chat_console->isOpenInhibited()) {
2571 show_pause_menu(¤t_formspec, client,
2572 texture_src, device, &input->joystick,
2573 simple_singleplayer_mode);
2575 } else if (wasKeyDown(KeyType::CHAT)) {
2576 openConsole(0.2, L"");
2577 } else if (wasKeyDown(KeyType::CMD)) {
2578 openConsole(0.2, L"/");
2579 } else if (wasKeyDown(KeyType::CONSOLE)) {
2580 openConsole(core::clamp(
2581 g_settings->getFloat("console_height"), 0.1f, 1.0f));
2582 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2583 toggleFreeMove(statustext_time);
2584 } else if (wasKeyDown(KeyType::JUMP)) {
2585 toggleFreeMoveAlt(statustext_time, jump_timer);
2586 *reset_jump_timer = true;
2587 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2588 toggleFast(statustext_time);
2589 } else if (wasKeyDown(KeyType::NOCLIP)) {
2590 toggleNoClip(statustext_time);
2591 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2592 toggleCinematic(statustext_time);
2593 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2594 client->makeScreenshot(device);
2595 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2596 toggleHud(statustext_time, &flags->show_hud);
2597 } else if (wasKeyDown(KeyType::MINIMAP)) {
2598 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2599 isKeyDown(KeyType::SNEAK));
2600 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2601 toggleChat(statustext_time, &flags->show_chat);
2602 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2603 toggleFog(statustext_time, &flags->force_fog_off);
2604 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2605 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2606 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2607 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph,
2608 &draw_control->show_wireframe);
2609 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2610 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2611 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2612 increaseViewRange(statustext_time);
2613 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2614 decreaseViewRange(statustext_time);
2615 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2616 toggleFullViewRange(statustext_time);
2617 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2619 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2621 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2623 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2625 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2626 // Print debug stacks
2627 dstream << "-----------------------------------------"
2629 dstream << "Printing debug stacks:" << std::endl;
2630 dstream << "-----------------------------------------"
2632 debug_stacks_print();
2635 if (!isKeyDown(KeyType::JUMP) && *reset_jump_timer) {
2636 *reset_jump_timer = false;
2642 if (quicktune->hasMessage()) {
2643 std::string msg = quicktune->getMessage();
2644 statustext = utf8_to_wide(msg);
2645 *statustext_time = 0;
2649 void Game::processItemSelection(u16 *new_playeritem)
2651 LocalPlayer *player = client->getEnv().getLocalPlayer();
2653 /* Item selection using mouse wheel
2655 *new_playeritem = client->getPlayerItem();
2657 s32 wheel = input->getMouseWheel();
2658 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2659 player->hud_hotbar_itemcount - 1);
2663 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN)) {
2667 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP)) {
2672 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2674 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2677 /* Item selection using keyboard
2679 for (u16 i = 0; i < 10; i++) {
2680 static const KeyPress *item_keys[10] = {
2681 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2682 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2683 NumberKey + 9, NumberKey + 0,
2686 if (input->wasKeyDown(*item_keys[i])) {
2687 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2688 *new_playeritem = i;
2689 infostream << "Selected item: " << new_playeritem << std::endl;
2697 void Game::dropSelectedItem()
2699 IDropAction *a = new IDropAction();
2701 a->from_inv.setCurrentPlayer();
2702 a->from_list = "main";
2703 a->from_i = client->getPlayerItem();
2704 client->inventoryAction(a);
2708 void Game::openInventory()
2711 * Don't permit to open inventory is CAO or player doesn't exists.
2712 * This prevent showing an empty inventory at player load
2715 LocalPlayer *player = client->getEnv().getLocalPlayer();
2716 if (player == NULL || player->getCAO() == NULL)
2719 infostream << "the_game: " << "Launching inventory" << std::endl;
2721 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2722 TextDest *txt_dst = new TextDestPlayerInventory(client);
2724 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
2727 InventoryLocation inventoryloc;
2728 inventoryloc.setCurrentPlayer();
2729 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2733 void Game::openConsole(float scale, const wchar_t *line)
2735 assert(scale > 0.0f && scale <= 1.0f);
2738 porting::showInputDialog(gettext("ok"), "", "", 2);
2739 m_android_chat_open = true;
2741 if (gui_chat_console->isOpenInhibited())
2743 gui_chat_console->openConsole(scale);
2745 gui_chat_console->setCloseOnEnter(true);
2746 gui_chat_console->replaceAndAddToHistory(line);
2752 void Game::handleAndroidChatInput()
2754 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2755 std::string text = porting::getInputDialogValue();
2756 client->typeChatMessage(utf8_to_wide(text));
2762 void Game::toggleFreeMove(float *statustext_time)
2764 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2766 bool free_move = !g_settings->getBool("free_move");
2767 g_settings->set("free_move", bool_to_cstr(free_move));
2769 *statustext_time = 0;
2770 statustext = msg[free_move];
2771 if (free_move && !client->checkPrivilege("fly"))
2772 statustext += L" (note: no 'fly' privilege)";
2776 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2778 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2779 toggleFreeMove(statustext_time);
2783 void Game::toggleFast(float *statustext_time)
2785 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2786 bool fast_move = !g_settings->getBool("fast_move");
2787 g_settings->set("fast_move", bool_to_cstr(fast_move));
2789 *statustext_time = 0;
2790 statustext = msg[fast_move];
2792 bool has_fast_privs = client->checkPrivilege("fast");
2794 if (fast_move && !has_fast_privs)
2795 statustext += L" (note: no 'fast' privilege)";
2798 m_cache_hold_aux1 = fast_move && has_fast_privs;
2803 void Game::toggleNoClip(float *statustext_time)
2805 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2806 bool noclip = !g_settings->getBool("noclip");
2807 g_settings->set("noclip", bool_to_cstr(noclip));
2809 *statustext_time = 0;
2810 statustext = msg[noclip];
2812 if (noclip && !client->checkPrivilege("noclip"))
2813 statustext += L" (note: no 'noclip' privilege)";
2816 void Game::toggleCinematic(float *statustext_time)
2818 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2819 bool cinematic = !g_settings->getBool("cinematic");
2820 g_settings->set("cinematic", bool_to_cstr(cinematic));
2822 *statustext_time = 0;
2823 statustext = msg[cinematic];
2826 // Add WoW-style autorun by toggling continuous forward.
2827 void Game::toggleAutorun(float *statustext_time)
2829 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2830 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2831 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2833 *statustext_time = 0;
2834 statustext = msg[autorun_enabled ? 1 : 0];
2837 void Game::toggleChat(float *statustext_time, bool *flag)
2839 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2842 *statustext_time = 0;
2843 statustext = msg[*flag];
2847 void Game::toggleHud(float *statustext_time, bool *flag)
2849 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2852 *statustext_time = 0;
2853 statustext = msg[*flag];
2856 void Game::toggleMinimap(float *statustext_time, bool *flag,
2857 bool show_hud, bool shift_pressed)
2859 if (!show_hud || !g_settings->getBool("enable_minimap"))
2862 if (shift_pressed) {
2863 mapper->toggleMinimapShape();
2867 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2869 MinimapMode mode = MINIMAP_MODE_OFF;
2870 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2871 mode = mapper->getMinimapMode();
2872 mode = (MinimapMode)((int)mode + 1);
2877 case MINIMAP_MODE_SURFACEx1:
2878 statustext = L"Minimap in surface mode, Zoom x1";
2880 case MINIMAP_MODE_SURFACEx2:
2881 statustext = L"Minimap in surface mode, Zoom x2";
2883 case MINIMAP_MODE_SURFACEx4:
2884 statustext = L"Minimap in surface mode, Zoom x4";
2886 case MINIMAP_MODE_RADARx1:
2887 statustext = L"Minimap in radar mode, Zoom x1";
2889 case MINIMAP_MODE_RADARx2:
2890 statustext = L"Minimap in radar mode, Zoom x2";
2892 case MINIMAP_MODE_RADARx4:
2893 statustext = L"Minimap in radar mode, Zoom x4";
2896 mode = MINIMAP_MODE_OFF;
2898 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2899 L"Minimap hidden" : L"Minimap disabled by server";
2902 *statustext_time = 0;
2903 mapper->setMinimapMode(mode);
2906 void Game::toggleFog(float *statustext_time, bool *flag)
2908 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2911 *statustext_time = 0;
2912 statustext = msg[*flag];
2916 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2917 bool *show_profiler_graph, bool *show_wireframe)
2919 // Initial / 4x toggle: Chat only
2920 // 1x toggle: Debug text with chat
2921 // 2x toggle: Debug text with profiler graph
2922 // 3x toggle: Debug text and wireframe
2925 *show_profiler_graph = false;
2926 *show_wireframe = false;
2927 statustext = L"Debug info shown";
2928 } else if (!*show_profiler_graph && !*show_wireframe) {
2929 *show_profiler_graph = true;
2930 statustext = L"Profiler graph shown";
2931 } else if (!*show_wireframe && client->checkPrivilege("debug")) {
2932 *show_profiler_graph = false;
2933 *show_wireframe = true;
2934 statustext = L"Wireframe shown";
2936 *show_debug = false;
2937 *show_profiler_graph = false;
2938 *show_wireframe = false;
2939 if (client->checkPrivilege("debug")) {
2940 statustext = L"Debug info, profiler graph, and wireframe hidden";
2942 statustext = L"Debug info and profiler graph hidden";
2945 *statustext_time = 0;
2949 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
2951 static const wchar_t *msg[] = {
2952 L"Camera update enabled",
2953 L"Camera update disabled"
2957 *statustext_time = 0;
2958 statustext = msg[*flag];
2962 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
2963 u32 profiler_max_page)
2965 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
2967 // FIXME: This updates the profiler with incomplete values
2968 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
2969 profiler_max_page, driver->getScreenSize().Height);
2971 if (*profiler_current_page != 0) {
2972 std::wstringstream sstr;
2973 sstr << "Profiler shown (page " << *profiler_current_page
2974 << " of " << profiler_max_page << ")";
2975 statustext = sstr.str();
2977 statustext = L"Profiler hidden";
2979 *statustext_time = 0;
2983 void Game::increaseViewRange(float *statustext_time)
2985 s16 range = g_settings->getS16("viewing_range");
2986 s16 range_new = range + 10;
2988 if (range_new > 4000) {
2990 statustext = utf8_to_wide("Viewing range is at maximum: "
2993 statustext = utf8_to_wide("Viewing range changed to "
2996 g_settings->set("viewing_range", itos(range_new));
2997 *statustext_time = 0;
3001 void Game::decreaseViewRange(float *statustext_time)
3003 s16 range = g_settings->getS16("viewing_range");
3004 s16 range_new = range - 10;
3006 if (range_new < 20) {
3008 statustext = utf8_to_wide("Viewing range is at minimum: "
3011 statustext = utf8_to_wide("Viewing range changed to "
3014 g_settings->set("viewing_range", itos(range_new));
3015 *statustext_time = 0;
3019 void Game::toggleFullViewRange(float *statustext_time)
3021 static const wchar_t *msg[] = {
3022 L"Disabled full viewing range",
3023 L"Enabled full viewing range"
3026 draw_control->range_all = !draw_control->range_all;
3027 infostream << msg[draw_control->range_all] << std::endl;
3028 statustext = msg[draw_control->range_all];
3029 *statustext_time = 0;
3033 void Game::updateCameraDirection(CameraOrientation *cam,
3034 VolatileRunFlags *flags, float dtime)
3036 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3039 if (!random_input) {
3040 // Mac OSX gets upset if this is set every frame
3041 if (device->getCursorControl()->isVisible())
3042 device->getCursorControl()->setVisible(false);
3046 if (flags->first_loop_after_window_activation)
3047 flags->first_loop_after_window_activation = false;
3049 updateCameraOrientation(cam, *flags, dtime);
3051 input->setMousePos((driver->getScreenSize().Width / 2),
3052 (driver->getScreenSize().Height / 2));
3056 // Mac OSX gets upset if this is set every frame
3057 if (device->getCursorControl()->isVisible() == false)
3058 device->getCursorControl()->setVisible(true);
3061 if (!flags->first_loop_after_window_activation)
3062 flags->first_loop_after_window_activation = true;
3067 void Game::updateCameraOrientation(CameraOrientation *cam,
3068 const VolatileRunFlags &flags, float dtime)
3070 #ifdef HAVE_TOUCHSCREENGUI
3071 if (g_touchscreengui) {
3072 cam->camera_yaw += g_touchscreengui->getYawChange();
3073 cam->camera_pitch = g_touchscreengui->getPitch();
3077 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3078 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3080 if (flags.invert_mouse
3081 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3085 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3086 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3088 #ifdef HAVE_TOUCHSCREENGUI
3092 if (m_cache_enable_joysticks) {
3093 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3094 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) *
3096 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) *
3100 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3104 void Game::updatePlayerControl(const CameraOrientation &cam)
3106 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3108 // DO NOT use the isKeyDown method for the forward, backward, left, right
3109 // buttons, as the code that uses the controls needs to be able to
3110 // distinguish between the two in order to know when to use joysticks.
3112 PlayerControl control(
3113 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3114 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3115 input->isKeyDown(keycache.key[KeyType::LEFT]),
3116 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3117 isKeyDown(KeyType::JUMP),
3118 isKeyDown(KeyType::SPECIAL1),
3119 isKeyDown(KeyType::SNEAK),
3120 isKeyDown(KeyType::ZOOM),
3125 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3126 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3130 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3131 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3132 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3133 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3134 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3135 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3136 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3137 ( (u32)(isLeftPressed() & 0x1) << 7) |
3138 ( (u32)(isRightPressed() & 0x1) << 8
3142 /* For Android, simulate holding down AUX1 (fast move) if the user has
3143 * the fast_move setting toggled on. If there is an aux1 key defined for
3144 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3147 if (m_cache_hold_aux1) {
3148 control.aux1 = control.aux1 ^ true;
3149 keypress_bits ^= ((u32)(1U << 5));
3153 client->setPlayerControl(control);
3154 LocalPlayer *player = client->getEnv().getLocalPlayer();
3155 player->keyPressed = keypress_bits;
3161 inline void Game::step(f32 *dtime)
3163 bool can_be_and_is_paused =
3164 (simple_singleplayer_mode && g_menumgr.pausesGame());
3166 if (can_be_and_is_paused) { // This is for a singleplayer server
3167 *dtime = 0; // No time passes
3169 if (server != NULL) {
3170 //TimeTaker timer("server->step(dtime)");
3171 server->step(*dtime);
3174 //TimeTaker timer("client.step(dtime)");
3175 client->step(*dtime);
3180 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3182 ClientEvent event = client->getClientEvent();
3184 LocalPlayer *player = client->getEnv().getLocalPlayer();
3186 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3188 if (event.type == CE_PLAYER_DAMAGE &&
3189 client->getHP() != 0) {
3190 client->getScript()->on_damage_taken(event.player_damage.amount);
3192 *damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3193 *damage_flash = MYMIN(*damage_flash, 127.0);
3195 player->hurt_tilt_timer = 1.5;
3196 player->hurt_tilt_strength =
3197 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3199 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3200 client->event()->put(e);
3201 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3202 cam->camera_yaw = event.player_force_move.yaw;
3203 cam->camera_pitch = event.player_force_move.pitch;
3204 } else if (event.type == CE_DEATHSCREEN) {
3205 client->getScript()->on_death();
3207 /* Handle visualization */
3209 player->hurt_tilt_timer = 0;
3210 player->hurt_tilt_strength = 0;
3212 } else if (event.type == CE_SHOW_FORMSPEC) {
3213 if (*(event.show_formspec.formspec) == "") {
3214 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3215 current_formspec->quitMenu();
3218 FormspecFormSource *fs_src =
3219 new FormspecFormSource(*(event.show_formspec.formspec));
3220 TextDestPlayerInventory *txt_dst =
3221 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3223 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3225 cur_formname = *(event.show_formspec.formname);
3228 delete(event.show_formspec.formspec);
3229 delete(event.show_formspec.formname);
3230 } else if (event.type == CE_SHOW_LOCAL_FORMSPEC) {
3231 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3232 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3233 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3235 delete event.show_formspec.formspec;
3236 delete event.show_formspec.formname;
3237 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3238 (event.type == CE_ADD_PARTICLESPAWNER) ||
3239 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3240 client->getParticleManager()->handleParticleEvent(&event, client,
3242 } else if (event.type == CE_HUDADD) {
3243 u32 id = event.hudadd.id;
3245 LocalPlayer *player = client->getEnv().getLocalPlayer();
3246 HudElement *e = player->getHud(id);
3249 delete event.hudadd.pos;
3250 delete event.hudadd.name;
3251 delete event.hudadd.scale;
3252 delete event.hudadd.text;
3253 delete event.hudadd.align;
3254 delete event.hudadd.offset;
3255 delete event.hudadd.world_pos;
3256 delete event.hudadd.size;
3261 e->type = (HudElementType)event.hudadd.type;
3262 e->pos = *event.hudadd.pos;
3263 e->name = *event.hudadd.name;
3264 e->scale = *event.hudadd.scale;
3265 e->text = *event.hudadd.text;
3266 e->number = event.hudadd.number;
3267 e->item = event.hudadd.item;
3268 e->dir = event.hudadd.dir;
3269 e->align = *event.hudadd.align;
3270 e->offset = *event.hudadd.offset;
3271 e->world_pos = *event.hudadd.world_pos;
3272 e->size = *event.hudadd.size;
3274 u32 new_id = player->addHud(e);
3275 //if this isn't true our huds aren't consistent
3276 sanity_check(new_id == id);
3278 delete event.hudadd.pos;
3279 delete event.hudadd.name;
3280 delete event.hudadd.scale;
3281 delete event.hudadd.text;
3282 delete event.hudadd.align;
3283 delete event.hudadd.offset;
3284 delete event.hudadd.world_pos;
3285 delete event.hudadd.size;
3286 } else if (event.type == CE_HUDRM) {
3287 HudElement *e = player->removeHud(event.hudrm.id);
3291 } else if (event.type == CE_HUDCHANGE) {
3292 u32 id = event.hudchange.id;
3293 HudElement *e = player->getHud(id);
3296 delete event.hudchange.v3fdata;
3297 delete event.hudchange.v2fdata;
3298 delete event.hudchange.sdata;
3299 delete event.hudchange.v2s32data;
3303 switch (event.hudchange.stat) {
3305 e->pos = *event.hudchange.v2fdata;
3309 e->name = *event.hudchange.sdata;
3312 case HUD_STAT_SCALE:
3313 e->scale = *event.hudchange.v2fdata;
3317 e->text = *event.hudchange.sdata;
3320 case HUD_STAT_NUMBER:
3321 e->number = event.hudchange.data;
3325 e->item = event.hudchange.data;
3329 e->dir = event.hudchange.data;
3332 case HUD_STAT_ALIGN:
3333 e->align = *event.hudchange.v2fdata;
3336 case HUD_STAT_OFFSET:
3337 e->offset = *event.hudchange.v2fdata;
3340 case HUD_STAT_WORLD_POS:
3341 e->world_pos = *event.hudchange.v3fdata;
3345 e->size = *event.hudchange.v2s32data;
3349 delete event.hudchange.v3fdata;
3350 delete event.hudchange.v2fdata;
3351 delete event.hudchange.sdata;
3352 delete event.hudchange.v2s32data;
3353 } else if (event.type == CE_SET_SKY) {
3354 sky->setVisible(false);
3361 // Handle according to type
3362 if (*event.set_sky.type == "regular") {
3363 sky->setVisible(true);
3364 } else if (*event.set_sky.type == "skybox" &&
3365 event.set_sky.params->size() == 6) {
3366 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3367 skybox = smgr->addSkyBoxSceneNode(
3368 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3369 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3370 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3371 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3372 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3373 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3375 // Handle everything else as plain color
3377 if (*event.set_sky.type != "plain")
3378 infostream << "Unknown sky type: "
3379 << (*event.set_sky.type) << std::endl;
3381 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3384 delete event.set_sky.bgcolor;
3385 delete event.set_sky.type;
3386 delete event.set_sky.params;
3387 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3388 bool enable = event.override_day_night_ratio.do_override;
3389 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3390 client->getEnv().setDayNightRatioOverride(enable, value);
3396 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3397 f32 dtime, float time_from_last_punch)
3399 LocalPlayer *player = client->getEnv().getLocalPlayer();
3402 For interaction purposes, get info about the held item
3404 - Is it a usable item?
3405 - Can it point to liquids?
3407 ItemStack playeritem;
3409 InventoryList *mlist = local_inventory->getList("main");
3411 if (mlist && client->getPlayerItem() < mlist->getSize())
3412 playeritem = mlist->getItem(client->getPlayerItem());
3414 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3415 InventoryList *hlist = local_inventory->getList("hand");
3417 playeritem = hlist->getItem(0);
3421 ToolCapabilities playeritem_toolcap =
3422 playeritem.getToolCapabilities(itemdef_manager);
3424 v3s16 old_camera_offset = camera->getOffset();
3426 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3427 GenericCAO *playercao = player->getCAO();
3429 // If playercao not loaded, don't change camera
3430 if (playercao == NULL)
3433 camera->toggleCameraMode();
3435 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3436 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3439 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3440 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3442 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3443 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3445 camera->step(dtime);
3447 v3f camera_position = camera->getPosition();
3448 v3f camera_direction = camera->getDirection();
3449 f32 camera_fov = camera->getFovMax();
3450 v3s16 camera_offset = camera->getOffset();
3452 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3454 if (!flags->disable_camera_update) {
3455 client->getEnv().getClientMap().updateCamera(camera_position,
3456 camera_direction, camera_fov, camera_offset);
3458 if (flags->camera_offset_changed) {
3459 client->updateCameraOffset(camera_offset);
3460 client->getEnv().updateCameraOffset(camera_offset);
3463 clouds->updateCameraOffset(camera_offset);
3469 void Game::updateSound(f32 dtime)
3471 // Update sound listener
3472 v3s16 camera_offset = camera->getOffset();
3473 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3474 v3f(0, 0, 0), // velocity
3475 camera->getDirection(),
3476 camera->getCameraNode()->getUpVector());
3477 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3480 // Update sound maker
3481 soundmaker->step(dtime);
3483 LocalPlayer *player = client->getEnv().getLocalPlayer();
3485 ClientMap &map = client->getEnv().getClientMap();
3486 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3487 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3491 void Game::processPlayerInteraction(GameRunData *runData,
3492 f32 dtime, bool show_hud, bool show_debug)
3494 LocalPlayer *player = client->getEnv().getLocalPlayer();
3496 ItemStack playeritem;
3498 InventoryList *mlist = local_inventory->getList("main");
3500 if (mlist && client->getPlayerItem() < mlist->getSize())
3501 playeritem = mlist->getItem(client->getPlayerItem());
3504 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3505 InventoryList *hlist = local_inventory->getList("hand");
3507 playeritem = hlist->getItem(0);
3509 const ItemDefinition &playeritem_def =
3510 playeritem.getDefinition(itemdef_manager);
3512 v3f player_position = player->getPosition();
3513 v3f camera_position = camera->getPosition();
3514 v3f camera_direction = camera->getDirection();
3515 v3s16 camera_offset = camera->getOffset();
3519 Calculate what block is the crosshair pointing to
3522 f32 d = playeritem_def.range; // max. distance
3523 f32 d_hand = itemdef_manager->get("").range;
3525 if (d < 0 && d_hand >= 0)
3530 core::line3d<f32> shootline;
3532 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3533 shootline = core::line3d<f32>(camera_position,
3534 camera_position + camera_direction * BS * d);
3536 // prevent player pointing anything in front-view
3537 shootline = core::line3d<f32>(camera_position,camera_position);
3540 #ifdef HAVE_TOUCHSCREENGUI
3542 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3543 shootline = g_touchscreengui->getShootline();
3544 shootline.start += intToFloat(camera_offset, BS);
3545 shootline.end += intToFloat(camera_offset, BS);
3550 PointedThing pointed = updatePointedThing(shootline,
3551 playeritem_def.liquids_pointable,
3552 !runData->ldown_for_dig,
3555 runData->selected_object);
3557 if (pointed != runData->pointed_old) {
3558 infostream << "Pointing at " << pointed.dump() << std::endl;
3559 hud->updateSelectionMesh(camera_offset);
3564 - releasing left mouse button
3565 - pointing away from node
3567 if (runData->digging) {
3568 if (getLeftReleased()) {
3569 infostream << "Left button released"
3570 << " (stopped digging)" << std::endl;
3571 runData->digging = false;
3572 } else if (pointed != runData->pointed_old) {
3573 if (pointed.type == POINTEDTHING_NODE
3574 && runData->pointed_old.type == POINTEDTHING_NODE
3575 && pointed.node_undersurface
3576 == runData->pointed_old.node_undersurface) {
3577 // Still pointing to the same node, but a different face.
3580 infostream << "Pointing away from node"
3581 << " (stopped digging)" << std::endl;
3582 runData->digging = false;
3583 hud->updateSelectionMesh(camera_offset);
3587 if (!runData->digging) {
3588 client->interact(1, runData->pointed_old);
3589 client->setCrack(-1, v3s16(0, 0, 0));
3590 runData->dig_time = 0.0;
3594 if (!runData->digging && runData->ldown_for_dig && !isLeftPressed()) {
3595 runData->ldown_for_dig = false;
3598 runData->left_punch = false;
3600 soundmaker->m_player_leftpunch_sound.name = "";
3602 if (isRightPressed())
3603 runData->repeat_rightclick_timer += dtime;
3605 runData->repeat_rightclick_timer = 0;
3607 if (playeritem_def.usable && isLeftPressed()) {
3608 if (getLeftClicked())
3609 client->interact(4, pointed);
3610 } else if (pointed.type == POINTEDTHING_NODE) {
3611 ToolCapabilities playeritem_toolcap =
3612 playeritem.getToolCapabilities(itemdef_manager);
3613 handlePointingAtNode(runData, pointed, playeritem_def,
3614 playeritem_toolcap, dtime);
3615 } else if (pointed.type == POINTEDTHING_OBJECT) {
3616 handlePointingAtObject(runData, pointed, playeritem,
3617 player_position, show_debug);
3618 } else if (isLeftPressed()) {
3619 // When button is held down in air, show continuous animation
3620 runData->left_punch = true;
3621 } else if (getRightClicked()) {
3622 handlePointingAtNothing(runData, playeritem);
3625 runData->pointed_old = pointed;
3627 if (runData->left_punch || getLeftClicked())
3628 camera->setDigging(0); // left click animation
3630 input->resetLeftClicked();
3631 input->resetRightClicked();
3633 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3634 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3636 input->resetLeftReleased();
3637 input->resetRightReleased();
3639 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3640 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3644 PointedThing Game::updatePointedThing(
3645 const core::line3d<f32> &shootline,
3646 bool liquids_pointable,
3647 bool look_for_object,
3648 const v3s16 &camera_offset,
3649 ClientActiveObject *&selected_object)
3651 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3652 selectionboxes->clear();
3653 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3654 static const bool show_entity_selectionbox = g_settings->getBool(
3655 "show_entity_selectionbox");
3657 ClientMap &map = client->getEnv().getClientMap();
3658 INodeDefManager *nodedef=client->getNodeDefManager();
3660 selected_object = NULL;
3662 PointedThing result=client->getEnv().getPointedThing(
3663 shootline, liquids_pointable, look_for_object);
3664 if (result.type == POINTEDTHING_OBJECT) {
3665 selected_object = client->getEnv().getActiveObject(result.object_id);
3666 if (show_entity_selectionbox && selected_object->doShowSelectionBox()) {
3667 aabb3f *selection_box = selected_object->getSelectionBox();
3669 // Box should exist because object was
3670 // returned in the first place
3672 assert(selection_box);
3674 v3f pos = selected_object->getPosition();
3675 selectionboxes->push_back(aabb3f(
3676 selection_box->MinEdge, selection_box->MaxEdge));
3677 selectionboxes->push_back(
3678 aabb3f(selection_box->MinEdge, selection_box->MaxEdge));
3679 hud->setSelectionPos(pos, camera_offset);
3681 } else if (result.type == POINTEDTHING_NODE) {
3682 // Update selection boxes
3683 MapNode n = map.getNodeNoEx(result.node_undersurface);
3684 std::vector<aabb3f> boxes;
3685 n.getSelectionBoxes(nodedef, &boxes,
3686 n.getNeighbors(result.node_undersurface, &map));
3689 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3690 i != boxes.end(); ++i) {
3692 box.MinEdge -= v3f(d, d, d);
3693 box.MaxEdge += v3f(d, d, d);
3694 selectionboxes->push_back(box);
3696 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3698 hud->setSelectedFaceNormal(v3f(
3699 result.intersection_normal.X,
3700 result.intersection_normal.Y,
3701 result.intersection_normal.Z));
3704 // Update selection mesh light level and vertex colors
3705 if (selectionboxes->size() > 0) {
3706 v3f pf = hud->getSelectionPos();
3707 v3s16 p = floatToInt(pf, BS);
3709 // Get selection mesh light level
3710 MapNode n = map.getNodeNoEx(p);
3711 u16 node_light = getInteriorLight(n, -1, nodedef);
3712 u16 light_level = node_light;
3714 for (u8 i = 0; i < 6; i++) {
3715 n = map.getNodeNoEx(p + g_6dirs[i]);
3716 node_light = getInteriorLight(n, -1, nodedef);
3717 if (node_light > light_level)
3718 light_level = node_light;
3721 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3723 final_color_blend(&c, light_level, daynight_ratio);
3725 // Modify final color a bit with time
3726 u32 timer = porting::getTimeMs() % 5000;
3727 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3728 float sin_r = 0.08 * sin(timerf);
3729 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3730 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3732 core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3734 core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3736 core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3738 // Set mesh final color
3739 hud->setSelectionMeshColor(c);
3745 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3747 infostream << "Right Clicked in Air" << std::endl;
3748 PointedThing fauxPointed;
3749 fauxPointed.type = POINTEDTHING_NOTHING;
3750 client->interact(5, fauxPointed);
3754 void Game::handlePointingAtNode(GameRunData *runData,
3755 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3756 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3758 v3s16 nodepos = pointed.node_undersurface;
3759 v3s16 neighbourpos = pointed.node_abovesurface;
3762 Check information text of node
3765 ClientMap &map = client->getEnv().getClientMap();
3766 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3769 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3771 MapNode n = map.getNodeNoEx(nodepos);
3773 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3774 infotext = L"Unknown node: ";
3775 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3779 if (runData->nodig_delay_timer <= 0.0 && isLeftPressed()
3780 && client->checkPrivilege("interact")) {
3781 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3784 if ((getRightClicked() ||
3785 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3786 client->checkPrivilege("interact")) {
3787 runData->repeat_rightclick_timer = 0;
3788 infostream << "Ground right-clicked" << std::endl;
3790 if (meta && meta->getString("formspec") != "" && !random_input
3791 && !isKeyDown(KeyType::SNEAK)) {
3792 infostream << "Launching custom inventory view" << std::endl;
3794 InventoryLocation inventoryloc;
3795 inventoryloc.setNodeMeta(nodepos);
3797 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3798 &client->getEnv().getClientMap(), nodepos);
3799 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3801 create_formspec_menu(¤t_formspec, client,
3802 device, &input->joystick, fs_src, txt_dst);
3805 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3807 // Report right click to server
3809 camera->setDigging(1); // right click animation (always shown for feedback)
3811 // If the wielded item has node placement prediction,
3813 bool placed = nodePlacementPrediction(*client,
3815 nodepos, neighbourpos);
3819 client->interact(3, pointed);
3821 soundmaker->m_player_rightpunch_sound =
3822 playeritem_def.sound_place;
3824 soundmaker->m_player_rightpunch_sound =
3827 if (playeritem_def.node_placement_prediction == "" ||
3828 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3829 client->interact(3, pointed); // Report to server
3831 soundmaker->m_player_rightpunch_sound =
3832 playeritem_def.sound_place_failed;
3840 void Game::handlePointingAtObject(GameRunData *runData,
3841 const PointedThing &pointed,
3842 const ItemStack &playeritem,
3843 const v3f &player_position,
3846 infotext = unescape_enriched(
3847 utf8_to_wide(runData->selected_object->infoText()));
3850 if (infotext != L"") {
3853 infotext += unescape_enriched(utf8_to_wide(
3854 runData->selected_object->debugInfoText()));
3857 if (isLeftPressed()) {
3858 bool do_punch = false;
3859 bool do_punch_damage = false;
3861 if (runData->object_hit_delay_timer <= 0.0) {
3863 do_punch_damage = true;
3864 runData->object_hit_delay_timer = object_hit_delay;
3867 if (getLeftClicked())
3871 infostream << "Left-clicked object" << std::endl;
3872 runData->left_punch = true;
3875 if (do_punch_damage) {
3876 // Report direct punch
3877 v3f objpos = runData->selected_object->getPosition();
3878 v3f dir = (objpos - player_position).normalize();
3880 bool disable_send = runData->selected_object->directReportPunch(
3881 dir, &playeritem, runData->time_from_last_punch);
3882 runData->time_from_last_punch = 0;
3885 client->interact(0, pointed);
3887 } else if (getRightClicked()) {
3888 infostream << "Right-clicked object" << std::endl;
3889 client->interact(3, pointed); // place
3894 void Game::handleDigging(GameRunData *runData,
3895 const PointedThing &pointed, const v3s16 &nodepos,
3896 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3898 if (!runData->digging) {
3899 infostream << "Started digging" << std::endl;
3900 client->interact(0, pointed);
3901 runData->digging = true;
3902 runData->ldown_for_dig = true;
3905 LocalPlayer *player = client->getEnv().getLocalPlayer();
3906 ClientMap &map = client->getEnv().getClientMap();
3907 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3909 // NOTE: Similar piece of code exists on the server side for
3911 // Get digging parameters
3912 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3913 &playeritem_toolcap);
3915 // If can't dig, try hand
3916 if (!params.diggable) {
3917 const ItemDefinition &hand = itemdef_manager->get("");
3918 const ToolCapabilities *tp = hand.tool_capabilities;
3921 params = getDigParams(nodedef_manager->get(n).groups, tp);
3924 if (params.diggable == false) {
3925 // I guess nobody will wait for this long
3926 runData->dig_time_complete = 10000000.0;
3928 runData->dig_time_complete = params.time;
3930 if (m_cache_enable_particles) {
3931 const ContentFeatures &features =
3932 client->getNodeDefManager()->get(n);
3933 client->getParticleManager()->addPunchingParticles(client, smgr,
3934 player, nodepos, n, features);
3938 if (runData->dig_time_complete >= 0.001) {
3939 runData->dig_index = (float)crack_animation_length
3941 / runData->dig_time_complete;
3943 // This is for torches
3944 runData->dig_index = crack_animation_length;
3947 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3949 if (sound_dig.exists() && params.diggable) {
3950 if (sound_dig.name == "__group") {
3951 if (params.main_group != "") {
3952 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3953 soundmaker->m_player_leftpunch_sound.name =
3954 std::string("default_dig_") +
3958 soundmaker->m_player_leftpunch_sound = sound_dig;
3962 // Don't show cracks if not diggable
3963 if (runData->dig_time_complete >= 100000.0) {
3964 } else if (runData->dig_index < crack_animation_length) {
3965 //TimeTaker timer("client.setTempMod");
3966 //infostream<<"dig_index="<<dig_index<<std::endl;
3967 client->setCrack(runData->dig_index, nodepos);
3969 infostream << "Digging completed" << std::endl;
3970 client->setCrack(-1, v3s16(0, 0, 0));
3972 runData->dig_time = 0;
3973 runData->digging = false;
3975 runData->nodig_delay_timer =
3976 runData->dig_time_complete / (float)crack_animation_length;
3978 // We don't want a corresponding delay to
3979 // very time consuming nodes
3980 if (runData->nodig_delay_timer > 0.3)
3981 runData->nodig_delay_timer = 0.3;
3983 // We want a slight delay to very little
3984 // time consuming nodes
3985 const float mindelay = 0.15;
3987 if (runData->nodig_delay_timer < mindelay)
3988 runData->nodig_delay_timer = mindelay;
3990 bool is_valid_position;
3991 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3992 if (is_valid_position) {
3993 bool block = client->getScript()->on_dignode(nodepos, wasnode);
3997 client->removeNode(nodepos);
4000 client->interact(2, pointed);
4002 if (m_cache_enable_particles) {
4003 const ContentFeatures &features =
4004 client->getNodeDefManager()->get(wasnode);
4005 client->getParticleManager()->addDiggingParticles(client, smgr,
4006 player, nodepos, wasnode, features);
4010 // Send event to trigger sound
4011 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4012 client->event()->put(e);
4015 if (runData->dig_time_complete < 100000.0) {
4016 runData->dig_time += dtime;
4018 runData->dig_time = 0;
4019 client->setCrack(-1, nodepos);
4022 camera->setDigging(0); // left click animation
4026 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
4027 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
4028 const CameraOrientation &cam)
4030 LocalPlayer *player = client->getEnv().getLocalPlayer();
4036 if (draw_control->range_all) {
4037 runData->fog_range = 100000 * BS;
4039 runData->fog_range = draw_control->wanted_range * BS;
4043 Calculate general brightness
4045 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4046 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4047 float direct_brightness;
4050 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4051 direct_brightness = time_brightness;
4052 sunlight_seen = true;
4054 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4055 float old_brightness = sky->getBrightness();
4056 direct_brightness = client->getEnv().getClientMap()
4057 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
4058 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4062 float time_of_day = runData->time_of_day;
4063 float time_of_day_smooth = runData->time_of_day_smooth;
4065 time_of_day = client->getEnv().getTimeOfDayF();
4067 const float maxsm = 0.05;
4068 const float todsm = 0.05;
4070 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4071 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4072 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4073 time_of_day_smooth = time_of_day;
4075 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4076 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4077 + (time_of_day + 1.0) * todsm;
4079 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4080 + time_of_day * todsm;
4082 runData->time_of_day = time_of_day;
4083 runData->time_of_day_smooth = time_of_day_smooth;
4085 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4086 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4087 player->getPitch());
4093 v3f player_position = player->getPosition();
4094 if (sky->getCloudsVisible()) {
4095 clouds->setVisible(true);
4096 clouds->step(dtime);
4097 clouds->update(v2f(player_position.X, player_position.Z),
4098 sky->getCloudColor());
4100 clouds->setVisible(false);
4107 client->getParticleManager()->step(dtime);
4113 if (m_cache_enable_fog && !flags.force_fog_off) {
4116 video::EFT_FOG_LINEAR,
4117 runData->fog_range * m_cache_fog_start,
4118 runData->fog_range * 1.0,
4126 video::EFT_FOG_LINEAR,
4136 Get chat messages from client
4139 v2u32 screensize = driver->getScreenSize();
4141 updateChat(*client, dtime, flags.show_debug, screensize,
4142 flags.show_chat, runData->profiler_current_page,
4143 *chat_backend, guitext_chat);
4149 if (client->getPlayerItem() != runData->new_playeritem)
4150 client->selectPlayerItem(runData->new_playeritem);
4152 // Update local inventory if it has changed
4153 if (client->getLocalInventoryUpdated()) {
4154 //infostream<<"Updating local inventory"<<std::endl;
4155 client->getLocalInventory(*local_inventory);
4156 runData->update_wielded_item_trigger = true;
4159 if (runData->update_wielded_item_trigger) {
4160 // Update wielded tool
4161 InventoryList *mlist = local_inventory->getList("main");
4163 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4164 ItemStack item = mlist->getItem(client->getPlayerItem());
4165 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4166 InventoryList *hlist = local_inventory->getList("hand");
4168 item = hlist->getItem(0);
4170 camera->wield(item);
4173 runData->update_wielded_item_trigger = false;
4177 Update block draw list every 200ms or when camera direction has
4180 runData->update_draw_list_timer += dtime;
4182 v3f camera_direction = camera->getDirection();
4183 if (runData->update_draw_list_timer >= 0.2
4184 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4185 || flags.camera_offset_changed) {
4186 runData->update_draw_list_timer = 0;
4187 client->getEnv().getClientMap().updateDrawList(driver);
4188 runData->update_draw_list_last_cam_dir = camera_direction;
4191 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4194 make sure menu is on top
4195 1. Delete formspec menu reference if menu was removed
4196 2. Else, make sure formspec menu is on top
4198 if (current_formspec) {
4199 if (current_formspec->getReferenceCount() == 1) {
4200 current_formspec->drop();
4201 current_formspec = NULL;
4202 } else if (!noMenuActive()) {
4203 guiroot->bringToFront(current_formspec);
4211 video::SColor skycolor = sky->getSkyColor();
4213 TimeTaker tt_draw("mainloop: draw");
4215 TimeTaker timer("beginScene");
4216 driver->beginScene(true, true, skycolor);
4217 stats->beginscenetime = timer.stop(true);
4220 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4221 guienv, screensize, skycolor, flags.show_hud,
4222 flags.show_minimap);
4227 if (flags.show_profiler_graph)
4228 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4233 if (runData->damage_flash > 0.0) {
4234 video::SColor color(runData->damage_flash, 180, 0, 0);
4235 driver->draw2DRectangle(color,
4236 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4239 runData->damage_flash -= 100.0 * dtime;
4245 if (player->hurt_tilt_timer > 0.0) {
4246 player->hurt_tilt_timer -= dtime * 5;
4248 if (player->hurt_tilt_timer < 0)
4249 player->hurt_tilt_strength = 0;
4253 Update minimap pos and rotation
4255 if (flags.show_minimap && flags.show_hud) {
4256 mapper->setPos(floatToInt(player->getPosition(), BS));
4257 mapper->setAngle(player->getYaw());
4264 TimeTaker timer("endScene");
4266 stats->endscenetime = timer.stop(true);
4269 stats->drawtime = tt_draw.stop(true);
4270 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4274 inline static const char *yawToDirectionString(int yaw)
4276 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4278 yaw = wrapDegrees_0_360(yaw);
4279 yaw = (yaw + 45) % 360 / 90;
4281 return direction[yaw];
4285 void Game::updateGui(float *statustext_time, const RunStats &stats,
4286 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4287 const CameraOrientation &cam)
4289 v2u32 screensize = driver->getScreenSize();
4290 LocalPlayer *player = client->getEnv().getLocalPlayer();
4291 v3f player_position = player->getPosition();
4293 if (flags.show_debug) {
4294 static float drawtime_avg = 0;
4295 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4297 u16 fps = 1.0 / stats.dtime_jitter.avg;
4298 //s32 fps = driver->getFPS();
4300 std::ostringstream os(std::ios_base::binary);
4302 << PROJECT_NAME_C " " << g_version_hash
4304 << " (R: range_all=" << draw_control->range_all << ")"
4305 << std::setprecision(0)
4306 << " drawtime = " << drawtime_avg
4307 << std::setprecision(1)
4308 << ", dtime_jitter = "
4309 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4310 << std::setprecision(1)
4311 << ", v_range = " << draw_control->wanted_range
4312 << std::setprecision(3)
4313 << ", RTT = " << client->getRTT();
4314 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4315 guitext->setVisible(true);
4317 guitext->setVisible(false);
4320 if (guitext->isVisible()) {
4321 core::rect<s32> rect(
4323 screensize.X, 5 + g_fontengine->getTextHeight()
4325 guitext->setRelativePosition(rect);
4328 if (flags.show_debug) {
4329 std::ostringstream os(std::ios_base::binary);
4330 os << std::setprecision(1) << std::fixed
4331 << "(" << (player_position.X / BS)
4332 << ", " << (player_position.Y / BS)
4333 << ", " << (player_position.Z / BS)
4334 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4335 << " " << yawToDirectionString(cam.camera_yaw)
4336 << ") (seed = " << ((u64)client->getMapSeed())
4339 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4340 ClientMap &map = client->getEnv().getClientMap();
4341 const INodeDefManager *nodedef = client->getNodeDefManager();
4342 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4343 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4344 const ContentFeatures &features = nodedef->get(n);
4345 os << " (pointing_at = " << nodedef->get(n).name
4346 << " - " << features.tiledef[0].name.c_str()
4351 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4352 guitext2->setVisible(true);
4354 core::rect<s32> rect(
4355 5, 5 + g_fontengine->getTextHeight(),
4356 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4358 guitext2->setRelativePosition(rect);
4360 guitext2->setVisible(false);
4363 setStaticText(guitext_info, infotext.c_str());
4364 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4366 float statustext_time_max = 1.5;
4368 if (!statustext.empty()) {
4369 *statustext_time += dtime;
4371 if (*statustext_time >= statustext_time_max) {
4373 *statustext_time = 0;
4377 setStaticText(guitext_status, statustext.c_str());
4378 guitext_status->setVisible(!statustext.empty());
4380 if (!statustext.empty()) {
4381 s32 status_width = guitext_status->getTextWidth();
4382 s32 status_height = guitext_status->getTextHeight();
4383 s32 status_y = screensize.Y - 150;
4384 s32 status_x = (screensize.X - status_width) / 2;
4385 core::rect<s32> rect(
4386 status_x , status_y - status_height,
4387 status_x + status_width, status_y
4389 guitext_status->setRelativePosition(rect);
4392 video::SColor initial_color(255, 0, 0, 0);
4394 if (guienv->getSkin())
4395 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4397 video::SColor final_color = initial_color;
4398 final_color.setAlpha(0);
4399 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4400 initial_color, final_color,
4401 pow(*statustext_time / statustext_time_max, 2.0f));
4402 guitext_status->setOverrideColor(fade_color);
4403 guitext_status->enableOverrideColor(true);
4408 /* Log times and stuff for visualization */
4409 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4411 Profiler::GraphValues values;
4412 g_profiler->graphGet(values);
4418 /****************************************************************************
4420 ****************************************************************************/
4422 /* On some computers framerate doesn't seem to be automatically limited
4424 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4426 // not using getRealTime is necessary for wine
4427 device->getTimer()->tick(); // Maker sure device time is up-to-date
4428 u32 time = device->getTimer()->getTime();
4429 u32 last_time = fps_timings->last_time;
4431 if (time > last_time) // Make sure time hasn't overflowed
4432 fps_timings->busy_time = time - last_time;
4434 fps_timings->busy_time = 0;
4436 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4437 ? g_settings->getFloat("pause_fps_max")
4438 : g_settings->getFloat("fps_max"));
4440 if (fps_timings->busy_time < frametime_min) {
4441 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4442 device->sleep(fps_timings->sleep_time);
4444 fps_timings->sleep_time = 0;
4447 /* Get the new value of the device timer. Note that device->sleep() may
4448 * not sleep for the entire requested time as sleep may be interrupted and
4449 * therefore it is arguably more accurate to get the new time from the
4450 * device rather than calculating it by adding sleep_time to time.
4453 device->getTimer()->tick(); // Update device timer
4454 time = device->getTimer()->getTime();
4456 if (time > last_time) // Make sure last_time hasn't overflowed
4457 *dtime = (time - last_time) / 1000.0;
4461 fps_timings->last_time = time;
4464 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4465 // pass a copy of it to this function
4466 // Note: \p msg must be allocated using new (not malloc())
4467 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4468 int percent, bool draw_clouds)
4470 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4474 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4476 ((Game *)data)->readSettings();
4479 void Game::readSettings()
4481 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4482 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4483 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4484 m_cache_enable_particles = g_settings->getBool("enable_particles");
4485 m_cache_enable_fog = g_settings->getBool("enable_fog");
4486 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4487 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4488 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4490 m_cache_enable_noclip = g_settings->getBool("noclip");
4491 m_cache_enable_free_move = g_settings->getBool("free_move");
4493 m_cache_fog_start = g_settings->getFloat("fog_start");
4495 m_cache_cam_smoothing = 0;
4496 if (g_settings->getBool("cinematic"))
4497 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4499 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4501 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4502 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4503 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4507 /****************************************************************************/
4508 /****************************************************************************
4510 ****************************************************************************/
4511 /****************************************************************************/
4513 void Game::extendedResourceCleanup()
4515 // Extended resource accounting
4516 infostream << "Irrlicht resources after cleanup:" << std::endl;
4517 infostream << "\tRemaining meshes : "
4518 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4519 infostream << "\tRemaining textures : "
4520 << driver->getTextureCount() << std::endl;
4522 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4523 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4524 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4528 clearTextureNameCache();
4529 infostream << "\tRemaining materials: "
4530 << driver-> getMaterialRendererCount()
4531 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4535 /****************************************************************************/
4536 /****************************************************************************
4537 extern function for launching the game
4538 ****************************************************************************/
4539 /****************************************************************************/
4541 void the_game(bool *kill,
4543 InputHandler *input,
4544 IrrlichtDevice *device,
4546 const std::string &map_dir,
4547 const std::string &playername,
4548 const std::string &password,
4549 const std::string &address, // If empty local server is created
4552 std::string &error_message,
4553 ChatBackend &chat_backend,
4554 bool *reconnect_requested,
4555 const SubgameSpec &gamespec, // Used for local game
4556 bool simple_singleplayer_mode)
4560 /* Make a copy of the server address because if a local singleplayer server
4561 * is created then this is updated and we don't want to change the value
4562 * passed to us by the calling function
4564 std::string server_address = address;
4568 if (game.startup(kill, random_input, input, device, map_dir,
4569 playername, password, &server_address, port, error_message,
4570 reconnect_requested, &chat_backend, gamespec,
4571 simple_singleplayer_mode)) {
4576 } catch (SerializationError &e) {
4577 error_message = std::string("A serialization error occurred:\n")
4578 + e.what() + "\n\nThe server is probably "
4579 " running a different version of " PROJECT_NAME_C ".";
4580 errorstream << error_message << std::endl;
4581 } catch (ServerError &e) {
4582 error_message = e.what();
4583 errorstream << "ServerError: " << error_message << std::endl;
4584 } catch (ModError &e) {
4585 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4586 errorstream << "ModError: " << error_message << std::endl;