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"
45 #include "mainmenumanager.h"
47 #include "nodedef.h" // Needed for determining pointing to nodes
48 #include "nodemetadata.h"
49 #include "particles.h"
51 #include "quicktune_shortcutter.h"
54 #include "shader.h" // For ShaderSource
58 #include "util/directiontables.h"
59 #include "util/pointedthing.h"
60 #include "irrlicht_changes/static_text.h"
63 #include "mapblock_mesh.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();
128 LocalFormspecHandler(std::string formname) :
131 m_formname = formname;
134 LocalFormspecHandler(std::string formname, Client *client) :
137 m_formname = formname;
140 void gotText(std::wstring message)
142 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
145 void gotText(const StringMap &fields)
147 if (m_formname == "MT_PAUSE_MENU") {
148 if (fields.find("btn_sound") != fields.end()) {
149 g_gamecallback->changeVolume();
153 if (fields.find("btn_key_config") != fields.end()) {
154 g_gamecallback->keyConfig();
158 if (fields.find("btn_exit_menu") != fields.end()) {
159 g_gamecallback->disconnect();
163 if (fields.find("btn_exit_os") != fields.end()) {
164 g_gamecallback->exitToOS();
168 if (fields.find("btn_change_password") != fields.end()) {
169 g_gamecallback->changePassword();
173 if (fields.find("quit") != fields.end()) {
177 if (fields.find("btn_continue") != fields.end()) {
182 if (m_formname == "MT_DEATH_SCREEN") {
183 assert(m_client != 0);
185 if ((fields.find("btn_respawn") != fields.end())) {
186 m_client->sendRespawn();
190 if (fields.find("quit") != fields.end()) {
191 m_client->sendRespawn();
196 // don't show error message for unhandled cursor keys
197 if ((fields.find("key_up") != fields.end()) ||
198 (fields.find("key_down") != fields.end()) ||
199 (fields.find("key_left") != fields.end()) ||
200 (fields.find("key_right") != fields.end())) {
204 errorstream << "LocalFormspecHandler::gotText unhandled >"
205 << m_formname << "< event" << std::endl;
208 StringMap::const_iterator it;
209 for (it = fields.begin(); it != fields.end(); ++it) {
210 errorstream << "\t" << i << ": " << it->first
211 << "=" << it->second << std::endl;
219 /* Form update callback */
221 class NodeMetadataFormSource: public IFormSource
224 NodeMetadataFormSource(ClientMap *map, v3s16 p):
229 std::string getForm()
231 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
236 return meta->getString("formspec");
238 std::string resolveText(std::string str)
240 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
245 return meta->resolveString(str);
252 class PlayerInventoryFormSource: public IFormSource
255 PlayerInventoryFormSource(Client *client):
259 std::string getForm()
261 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
262 return player->inventory_formspec;
268 /* Profiler display */
270 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
271 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
273 if (show_profiler == 0) {
274 guitext_profiler->setVisible(false);
277 std::ostringstream os(std::ios_base::binary);
278 g_profiler->printPage(os, show_profiler, show_profiler_max);
279 std::wstring text = utf8_to_wide(os.str());
280 setStaticText(guitext_profiler, text.c_str());
281 guitext_profiler->setVisible(true);
283 s32 w = fe->getTextWidth(text.c_str());
288 unsigned text_height = fe->getTextHeight();
290 core::position2di upper_left, lower_right;
293 upper_left.Y = (text_height + 5) * 2;
294 lower_right.X = 12 + w;
295 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
297 if (lower_right.Y > screen_height * 2 / 3)
298 lower_right.Y = screen_height * 2 / 3;
300 core::rect<s32> rect(upper_left, lower_right);
302 guitext_profiler->setRelativePosition(rect);
303 guitext_profiler->setVisible(true);
311 Profiler::GraphValues values;
317 Meta(float initial = 0,
318 video::SColor color = video::SColor(255, 255, 255, 255)):
324 std::deque<Piece> m_log;
332 void put(const Profiler::GraphValues &values)
335 piece.values = values;
336 m_log.push_back(piece);
338 while (m_log.size() > m_log_max_size)
339 m_log.erase(m_log.begin());
342 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
343 gui::IGUIFont *font) const
345 // Do *not* use UNORDERED_MAP here as the order needs
346 // to be the same for each call to prevent flickering
347 std::map<std::string, Meta> m_meta;
349 for (std::deque<Piece>::const_iterator k = m_log.begin();
350 k != m_log.end(); ++k) {
351 const Piece &piece = *k;
353 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
354 i != piece.values.end(); ++i) {
355 const std::string &id = i->first;
356 const float &value = i->second;
357 std::map<std::string, Meta>::iterator j = m_meta.find(id);
359 if (j == m_meta.end()) {
360 m_meta[id] = Meta(value);
364 if (value < j->second.min)
365 j->second.min = value;
367 if (value > j->second.max)
368 j->second.max = value;
373 static const video::SColor usable_colors[] = {
374 video::SColor(255, 255, 100, 100),
375 video::SColor(255, 90, 225, 90),
376 video::SColor(255, 100, 100, 255),
377 video::SColor(255, 255, 150, 50),
378 video::SColor(255, 220, 220, 100)
380 static const u32 usable_colors_count =
381 sizeof(usable_colors) / sizeof(*usable_colors);
382 u32 next_color_i = 0;
384 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
385 i != m_meta.end(); ++i) {
386 Meta &meta = i->second;
387 video::SColor color(255, 200, 200, 200);
389 if (next_color_i < usable_colors_count)
390 color = usable_colors[next_color_i++];
396 s32 textx = x_left + m_log_max_size + 15;
397 s32 textx2 = textx + 200 - 15;
400 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
401 i != m_meta.end(); ++i) {
402 const std::string &id = i->first;
403 const Meta &meta = i->second;
405 s32 y = y_bottom - meta_i * 50;
406 float show_min = meta.min;
407 float show_max = meta.max;
409 if (show_min >= -0.0001 && show_max >= -0.0001) {
410 if (show_min <= show_max * 0.5)
416 snprintf(buf, 10, "%.3g", show_max);
417 font->draw(utf8_to_wide(buf).c_str(),
418 core::rect<s32>(textx, y - graphh,
419 textx2, y - graphh + texth),
421 snprintf(buf, 10, "%.3g", show_min);
422 font->draw(utf8_to_wide(buf).c_str(),
423 core::rect<s32>(textx, y - texth,
426 font->draw(utf8_to_wide(id).c_str(),
427 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
428 textx2, y - graphh / 2 + texth / 2),
431 s32 graph1h = graphh;
432 bool relativegraph = (show_min != 0 && show_min != show_max);
433 float lastscaledvalue = 0.0;
434 bool lastscaledvalue_exists = false;
436 for (std::deque<Piece>::const_iterator j = m_log.begin();
437 j != m_log.end(); ++j) {
438 const Piece &piece = *j;
440 bool value_exists = false;
441 Profiler::GraphValues::const_iterator k =
442 piece.values.find(id);
444 if (k != piece.values.end()) {
451 lastscaledvalue_exists = false;
455 float scaledvalue = 1.0;
457 if (show_max != show_min)
458 scaledvalue = (value - show_min) / (show_max - show_min);
460 if (scaledvalue == 1.0 && value == 0) {
462 lastscaledvalue_exists = false;
467 if (lastscaledvalue_exists) {
468 s32 ivalue1 = lastscaledvalue * graph1h;
469 s32 ivalue2 = scaledvalue * graph1h;
470 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
471 v2s32(x, graph1y - ivalue2), meta.color);
474 lastscaledvalue = scaledvalue;
475 lastscaledvalue_exists = true;
477 s32 ivalue = scaledvalue * graph1h;
478 driver->draw2DLine(v2s32(x, graph1y),
479 v2s32(x, graph1y - ivalue), meta.color);
490 class NodeDugEvent: public MtEvent
496 NodeDugEvent(v3s16 p, MapNode n):
500 const char *getType() const
508 ISoundManager *m_sound;
509 INodeDefManager *m_ndef;
511 float m_player_step_timer;
513 SimpleSoundSpec m_player_step_sound;
514 SimpleSoundSpec m_player_leftpunch_sound;
515 SimpleSoundSpec m_player_rightpunch_sound;
517 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
520 m_player_step_timer(0)
524 void playPlayerStep()
526 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
527 m_player_step_timer = 0.03;
528 m_sound->playSound(m_player_step_sound, false);
532 static void viewBobbingStep(MtEvent *e, void *data)
534 SoundMaker *sm = (SoundMaker *)data;
535 sm->playPlayerStep();
538 static void playerRegainGround(MtEvent *e, void *data)
540 SoundMaker *sm = (SoundMaker *)data;
541 sm->playPlayerStep();
544 static void playerJump(MtEvent *e, void *data)
546 //SoundMaker *sm = (SoundMaker*)data;
549 static void cameraPunchLeft(MtEvent *e, void *data)
551 SoundMaker *sm = (SoundMaker *)data;
552 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
555 static void cameraPunchRight(MtEvent *e, void *data)
557 SoundMaker *sm = (SoundMaker *)data;
558 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
561 static void nodeDug(MtEvent *e, void *data)
563 SoundMaker *sm = (SoundMaker *)data;
564 NodeDugEvent *nde = (NodeDugEvent *)e;
565 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
568 static void playerDamage(MtEvent *e, void *data)
570 SoundMaker *sm = (SoundMaker *)data;
571 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
574 static void playerFallingDamage(MtEvent *e, void *data)
576 SoundMaker *sm = (SoundMaker *)data;
577 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
580 void registerReceiver(MtEventManager *mgr)
582 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
583 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
584 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
585 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
586 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
587 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
588 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
589 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
592 void step(float dtime)
594 m_player_step_timer -= dtime;
598 // Locally stored sounds don't need to be preloaded because of this
599 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
601 std::set<std::string> m_fetched;
603 void fetchSounds(const std::string &name,
604 std::set<std::string> &dst_paths,
605 std::set<std::string> &dst_datas)
607 if (m_fetched.count(name))
610 m_fetched.insert(name);
611 std::string base = porting::path_share + DIR_DELIM + "sounds";
612 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
613 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
614 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
615 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
616 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
617 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
618 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
619 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
620 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
621 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
622 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
627 // before 1.8 there isn't a "integer interface", only float
628 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
629 typedef f32 SamplerLayer_t;
631 typedef s32 SamplerLayer_t;
635 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
638 bool *m_force_fog_off;
641 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
642 CachedPixelShaderSetting<float> m_fog_distance;
643 CachedVertexShaderSetting<float> m_animation_timer_vertex;
644 CachedPixelShaderSetting<float> m_animation_timer_pixel;
645 CachedPixelShaderSetting<float, 3> m_day_light;
646 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
647 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
648 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
649 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
650 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
651 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
655 void onSettingsChange(const std::string &name)
657 if (name == "enable_fog")
658 m_fog_enabled = g_settings->getBool("enable_fog");
661 static void settingsCallback(const std::string &name, void *userdata)
663 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
666 void setSky(Sky *sky) { m_sky = sky; }
668 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
669 f32 *fog_range, Client *client) :
671 m_force_fog_off(force_fog_off),
672 m_fog_range(fog_range),
673 m_sky_bg_color("skyBgColor"),
674 m_fog_distance("fogDistance"),
675 m_animation_timer_vertex("animationTimer"),
676 m_animation_timer_pixel("animationTimer"),
677 m_day_light("dayLight"),
678 m_eye_position_pixel("eyePosition"),
679 m_eye_position_vertex("eyePosition"),
680 m_minimap_yaw("yawVec"),
681 m_base_texture("baseTexture"),
682 m_normal_texture("normalTexture"),
683 m_texture_flags("textureFlags"),
686 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
687 m_fog_enabled = g_settings->getBool("enable_fog");
690 ~GameGlobalShaderConstantSetter()
692 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
695 virtual void onSetConstants(video::IMaterialRendererServices *services,
702 video::SColor bgcolor = m_sky->getBgColor();
703 video::SColorf bgcolorf(bgcolor);
704 float bgcolorfa[4] = {
710 m_sky_bg_color.set(bgcolorfa, services);
713 float fog_distance = 10000 * BS;
715 if (m_fog_enabled && !*m_force_fog_off)
716 fog_distance = *m_fog_range;
718 m_fog_distance.set(&fog_distance, services);
720 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
721 video::SColorf sunlight;
722 get_sunlight_color(&sunlight, daynight_ratio);
727 m_day_light.set(dnc, services);
729 u32 animation_timer = porting::getTimeMs() % 100000;
730 float animation_timer_f = (float)animation_timer / 100000.f;
731 m_animation_timer_vertex.set(&animation_timer_f, services);
732 m_animation_timer_pixel.set(&animation_timer_f, services);
734 float eye_position_array[3];
735 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
736 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
737 eye_position_array[0] = epos.X;
738 eye_position_array[1] = epos.Y;
739 eye_position_array[2] = epos.Z;
741 epos.getAs3Values(eye_position_array);
743 m_eye_position_pixel.set(eye_position_array, services);
744 m_eye_position_vertex.set(eye_position_array, services);
746 float minimap_yaw_array[3];
747 v3f minimap_yaw = m_client->getMapper()->getYawVec();
748 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
749 minimap_yaw_array[0] = minimap_yaw.X;
750 minimap_yaw_array[1] = minimap_yaw.Y;
751 minimap_yaw_array[2] = minimap_yaw.Z;
753 minimap_yaw.getAs3Values(minimap_yaw_array);
755 m_minimap_yaw.set(minimap_yaw_array, services);
757 SamplerLayer_t base_tex = 0,
760 m_base_texture.set(&base_tex, services);
761 m_normal_texture.set(&normal_tex, services);
762 m_texture_flags.set(&flags_tex, services);
767 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
770 bool *m_force_fog_off;
773 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
775 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
776 f32 *fog_range, Client *client) :
778 m_force_fog_off(force_fog_off),
779 m_fog_range(fog_range),
783 void setSky(Sky *sky) {
785 for (size_t i = 0; i < created_nosky.size(); ++i) {
786 created_nosky[i]->setSky(m_sky);
788 created_nosky.clear();
791 virtual IShaderConstantSetter* create()
793 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
794 m_sky, m_force_fog_off, m_fog_range, m_client);
796 created_nosky.push_back(scs);
802 bool nodePlacementPrediction(Client &client,
803 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
805 std::string prediction = playeritem_def.node_placement_prediction;
806 INodeDefManager *nodedef = client.ndef();
807 ClientMap &map = client.getEnv().getClientMap();
809 bool is_valid_position;
811 node = map.getNodeNoEx(nodepos, &is_valid_position);
812 if (!is_valid_position)
815 if (prediction != "" && !nodedef->get(node).rightclickable) {
816 verbosestream << "Node placement prediction for "
817 << playeritem_def.name << " is "
818 << prediction << std::endl;
819 v3s16 p = neighbourpos;
821 // Place inside node itself if buildable_to
822 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
823 if (is_valid_position)
825 if (nodedef->get(n_under).buildable_to)
828 node = map.getNodeNoEx(p, &is_valid_position);
829 if (is_valid_position &&!nodedef->get(node).buildable_to)
834 // Find id of predicted node
836 bool found = nodedef->getId(prediction, id);
839 errorstream << "Node placement prediction failed for "
840 << playeritem_def.name << " (places "
842 << ") - Name not known" << std::endl;
846 // Predict param2 for facedir and wallmounted nodes
849 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
850 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED) {
851 v3s16 dir = nodepos - neighbourpos;
853 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
854 param2 = dir.Y < 0 ? 1 : 0;
855 } else if (abs(dir.X) > abs(dir.Z)) {
856 param2 = dir.X < 0 ? 3 : 2;
858 param2 = dir.Z < 0 ? 5 : 4;
862 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR ||
863 nodedef->get(id).param_type_2 == CPT2_COLORED_FACEDIR) {
864 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
866 if (abs(dir.X) > abs(dir.Z)) {
867 param2 = dir.X < 0 ? 3 : 1;
869 param2 = dir.Z < 0 ? 2 : 0;
875 //Check attachment if node is in group attached_node
876 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
877 static v3s16 wallmounted_dirs[8] = {
887 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
888 pp = p + wallmounted_dirs[param2];
890 pp = p + v3s16(0, -1, 0);
892 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
896 // Add node to client map
897 MapNode n(id, 0, param2);
900 LocalPlayer *player = client.getEnv().getLocalPlayer();
902 // Dont place node when player would be inside new node
903 // NOTE: This is to be eventually implemented by a mod as client-side Lua
904 if (!nodedef->get(n).walkable ||
905 g_settings->getBool("enable_build_where_you_stand") ||
906 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
907 (nodedef->get(n).walkable &&
908 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
909 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
911 // This triggers the required mesh update too
912 client.addNode(p, n);
915 } catch (InvalidPositionException &e) {
916 errorstream << "Node placement prediction failed for "
917 << playeritem_def.name << " (places "
919 << ") - Position not loaded" << std::endl;
926 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
927 Client *client, IrrlichtDevice *device, JoystickController *joystick,
928 IFormSource *fs_src, TextDest *txt_dest)
931 if (*cur_formspec == 0) {
932 *cur_formspec = new GUIFormSpecMenu(device, joystick,
933 guiroot, -1, &g_menumgr, client, client->getTextureSource(),
935 (*cur_formspec)->doPause = false;
938 Caution: do not call (*cur_formspec)->drop() here --
939 the reference might outlive the menu, so we will
940 periodically check if *cur_formspec is the only
941 remaining reference (i.e. the menu was removed)
942 and delete it in that case.
946 (*cur_formspec)->setFormSource(fs_src);
947 (*cur_formspec)->setTextDest(txt_dest);
953 #define SIZE_TAG "size[11,5.5]"
955 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
958 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
960 IWritableTextureSource *tsrc, IrrlichtDevice *device,
961 JoystickController *joystick)
963 std::string formspec =
964 std::string(FORMSPEC_VERSION_STRING) +
966 "bgcolor[#320000b4;true]"
967 "label[4.85,1.35;" + gettext("You died.") + "]"
968 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
972 /* Note: FormspecFormSource and LocalFormspecHandler
973 * are deleted by guiFormSpecMenu */
974 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
975 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
977 create_formspec_menu(cur_formspec, client, device, joystick, fs_src, txt_dst);
980 /******************************************************************************/
981 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
983 IWritableTextureSource *tsrc, IrrlichtDevice *device,
984 JoystickController *joystick, bool singleplayermode)
987 std::string control_text = strgettext("Default Controls:\n"
989 "- single tap: button activate\n"
990 "- double tap: place/use\n"
991 "- slide finger: look around\n"
992 "Menu/Inventory visible:\n"
993 "- double tap (outside):\n"
995 "- touch stack, touch slot:\n"
997 "- touch&drag, tap 2nd finger\n"
998 " --> place single item to slot\n"
1001 std::string control_text = strgettext("Default Controls:\n"
1003 "- Space: jump/climb\n"
1004 "- Shift: sneak/go down\n"
1007 "- Mouse: turn/look\n"
1008 "- Mouse left: dig/punch\n"
1009 "- Mouse right: place/use\n"
1010 "- Mouse wheel: select item\n"
1015 float ypos = singleplayermode ? 0.5 : 0.1;
1016 std::ostringstream os;
1018 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1019 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1020 << strgettext("Continue") << "]";
1022 if (!singleplayermode) {
1023 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1024 << strgettext("Change Password") << "]";
1028 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1029 << strgettext("Sound Volume") << "]";
1030 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1031 << strgettext("Change Keys") << "]";
1033 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1034 << strgettext("Exit to Menu") << "]";
1035 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1036 << strgettext("Exit to OS") << "]"
1037 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1038 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1039 << g_build_info << "\n"
1040 << "path_user = " << wrap_rows(porting::path_user, 20)
1044 /* Note: FormspecFormSource and LocalFormspecHandler *
1045 * are deleted by guiFormSpecMenu */
1046 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1047 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1049 create_formspec_menu(cur_formspec, client, device, joystick, fs_src, txt_dst);
1050 std::string con("btn_continue");
1051 (*cur_formspec)->setFocus(con);
1052 (*cur_formspec)->doPause = true;
1055 /******************************************************************************/
1056 static void updateChat(Client &client, f32 dtime, bool show_debug,
1057 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1058 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1060 // Add chat log output for errors to be shown in chat
1061 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
1063 // Get new messages from error log buffer
1064 while (!chat_log_error_buf.empty()) {
1065 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
1066 if (!g_settings->getBool("disable_escape_sequences")) {
1067 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
1069 chat_backend.addMessage(L"", error_message);
1072 // Get new messages from client
1073 std::wstring message;
1075 while (client.getChatMessage(message)) {
1076 chat_backend.addUnparsedMessage(message);
1079 // Remove old messages
1080 chat_backend.step(dtime);
1082 // Display all messages in a static text element
1083 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1084 EnrichedString recent_chat = chat_backend.getRecentChat();
1085 unsigned int line_height = g_fontengine->getLineHeight();
1087 setStaticText(guitext_chat, recent_chat);
1089 // Update gui element size and position
1093 chat_y += 2 * line_height;
1095 // first pass to calculate height of text to be set
1096 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
1097 porting::getWindowSize().X - 20);
1098 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1099 guitext_chat->setRelativePosition(rect);
1101 //now use real height of text and adjust rect according to this size
1102 rect = core::rect<s32>(10, chat_y, width,
1103 chat_y + guitext_chat->getTextHeight());
1106 guitext_chat->setRelativePosition(rect);
1107 // Don't show chat if disabled or empty or profiler is enabled
1108 guitext_chat->setVisible(
1109 show_chat && recent_chat_count != 0 && !show_profiler);
1113 /****************************************************************************
1114 Fast key cache for main game loop
1115 ****************************************************************************/
1117 /* This is faster than using getKeySetting with the tradeoff that functions
1118 * using it must make sure that it's initialised before using it and there is
1119 * no error handling (for example bounds checking). This is really intended for
1120 * use only in the main running loop of the client (the_game()) where the faster
1121 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1122 * (e.g. formspecs) should continue using getKeySetting().
1130 populate_nonchanging();
1135 // Keys that are not settings dependent
1136 void populate_nonchanging();
1138 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1139 InputHandler *handler;
1142 void KeyCache::populate_nonchanging()
1144 key[KeyType::ESC] = EscapeKey;
1147 void KeyCache::populate()
1149 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1150 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1151 key[KeyType::LEFT] = getKeySetting("keymap_left");
1152 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1153 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1154 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1155 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1157 key[KeyType::AUTORUN] = getKeySetting("keymap_autorun");
1159 key[KeyType::DROP] = getKeySetting("keymap_drop");
1160 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1161 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1162 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1163 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1164 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1165 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1166 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1167 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1168 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1169 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1170 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1171 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1172 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1173 = getKeySetting("keymap_toggle_force_fog_off");
1174 key[KeyType::TOGGLE_UPDATE_CAMERA]
1175 = getKeySetting("keymap_toggle_update_camera");
1176 key[KeyType::TOGGLE_DEBUG]
1177 = getKeySetting("keymap_toggle_debug");
1178 key[KeyType::TOGGLE_PROFILER]
1179 = getKeySetting("keymap_toggle_profiler");
1180 key[KeyType::CAMERA_MODE]
1181 = getKeySetting("keymap_camera_mode");
1182 key[KeyType::INCREASE_VIEWING_RANGE]
1183 = getKeySetting("keymap_increase_viewing_range_min");
1184 key[KeyType::DECREASE_VIEWING_RANGE]
1185 = getKeySetting("keymap_decrease_viewing_range_min");
1186 key[KeyType::RANGESELECT]
1187 = getKeySetting("keymap_rangeselect");
1188 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1190 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1191 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1192 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1193 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1195 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1198 // First clear all keys, then re-add the ones we listen for
1199 handler->dontListenForKeys();
1200 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1201 handler->listenForKey(key[i]);
1203 handler->listenForKey(EscapeKey);
1204 handler->listenForKey(CancelKey);
1205 for (size_t i = 0; i < 10; i++) {
1206 handler->listenForKey(NumberKey[i]);
1212 /****************************************************************************
1214 ****************************************************************************/
1216 const float object_hit_delay = 0.2;
1219 u32 last_time, busy_time, sleep_time;
1223 /* The reason the following structs are not anonymous structs within the
1224 * class is that they are not used by the majority of member functions and
1225 * many functions that do require objects of thse types do not modify them
1226 * (so they can be passed as a const qualified parameter)
1228 struct CameraOrientation {
1229 f32 camera_yaw; // "right/left"
1230 f32 camera_pitch; // "up/down"
1233 struct GameRunData {
1236 PointedThing pointed_old;
1240 bool update_wielded_item_trigger;
1241 bool reset_jump_timer;
1242 float nodig_delay_timer;
1244 float dig_time_complete;
1245 float repeat_rightclick_timer;
1246 float object_hit_delay_timer;
1247 float time_from_last_punch;
1248 ClientActiveObject *selected_object;
1252 float update_draw_list_timer;
1253 float statustext_time;
1257 v3f update_draw_list_last_cam_dir;
1259 u32 profiler_current_page;
1260 u32 profiler_max_page; // Number of pages
1263 float time_of_day_smooth;
1267 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1275 Jitter dtime_jitter, busy_time_jitter;
1278 /* Flags that can, or may, change during main game loop
1280 struct VolatileRunFlags {
1287 bool show_profiler_graph;
1288 bool disable_camera_update;
1289 bool first_loop_after_window_activation;
1290 bool camera_offset_changed;
1294 /****************************************************************************
1296 ****************************************************************************/
1298 /* This is not intended to be a public class. If a public class becomes
1299 * desirable then it may be better to create another 'wrapper' class that
1300 * hides most of the stuff in this class (nothing in this class is required
1301 * by any other file) but exposes the public methods/data only.
1308 bool startup(bool *kill,
1310 InputHandler *input,
1311 IrrlichtDevice *device,
1312 const std::string &map_dir,
1313 const std::string &playername,
1314 const std::string &password,
1315 // If address is "", local server is used and address is updated
1316 std::string *address,
1318 std::string &error_message,
1320 ChatBackend *chat_backend,
1321 const SubgameSpec &gamespec, // Used for local game
1322 bool simple_singleplayer_mode);
1329 void extendedResourceCleanup();
1331 // Basic initialisation
1332 bool init(const std::string &map_dir, std::string *address,
1334 const SubgameSpec &gamespec);
1336 bool createSingleplayerServer(const std::string map_dir,
1337 const SubgameSpec &gamespec, u16 port, std::string *address);
1340 bool createClient(const std::string &playername,
1341 const std::string &password, std::string *address, u16 port);
1344 // Client connection
1345 bool connectToServer(const std::string &playername,
1346 const std::string &password, std::string *address, u16 port,
1347 bool *connect_ok, bool *aborted);
1348 bool getServerContent(bool *aborted);
1352 void updateInteractTimers(GameRunData *runData, f32 dtime);
1353 bool checkConnection();
1354 bool handleCallbacks();
1355 void processQueues();
1356 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1357 const FpsControl &draw_times, f32 dtime);
1358 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1360 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1363 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1365 void processKeyInput(VolatileRunFlags *flags,
1366 float *statustext_time,
1368 bool *reset_jump_timer,
1369 u32 *profiler_current_page,
1370 u32 profiler_max_page);
1371 void processItemSelection(u16 *new_playeritem);
1373 void dropSelectedItem();
1374 void openInventory();
1375 void openConsole(float scale, const wchar_t *line=NULL);
1376 void toggleFreeMove(float *statustext_time);
1377 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1378 void toggleFast(float *statustext_time);
1379 void toggleNoClip(float *statustext_time);
1380 void toggleCinematic(float *statustext_time);
1381 void toggleAutorun(float *statustext_time);
1383 void toggleChat(float *statustext_time, bool *flag);
1384 void toggleHud(float *statustext_time, bool *flag);
1385 void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
1386 bool shift_pressed);
1387 void toggleFog(float *statustext_time, bool *flag);
1388 void toggleDebug(float *statustext_time, bool *show_debug,
1389 bool *show_profiler_graph, bool *show_wireframe);
1390 void toggleUpdateCamera(float *statustext_time, bool *flag);
1391 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1392 u32 profiler_max_page);
1394 void increaseViewRange(float *statustext_time);
1395 void decreaseViewRange(float *statustext_time);
1396 void toggleFullViewRange(float *statustext_time);
1398 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags,
1400 void updateCameraOrientation(CameraOrientation *cam,
1401 const VolatileRunFlags &flags, float dtime);
1402 void updatePlayerControl(const CameraOrientation &cam);
1403 void step(f32 *dtime);
1404 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1405 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1406 float time_from_last_punch);
1407 void updateSound(f32 dtime);
1408 void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud,
1411 * Returns the object or node the player is pointing at.
1412 * Also updates the selected thing in the Hud.
1414 * @param[in] shootline the shootline, starting from
1415 * the camera position. This also gives the maximal distance
1417 * @param[in] liquids_pointable if false, liquids are ignored
1418 * @param[in] look_for_object if false, objects are ignored
1419 * @param[in] camera_offset offset of the camera
1420 * @param[out] selected_object the selected object or
1423 PointedThing updatePointedThing(
1424 const core::line3d<f32> &shootline, bool liquids_pointable,
1425 bool look_for_object, const v3s16 &camera_offset,
1426 ClientActiveObject *&selected_object);
1427 void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
1428 void handlePointingAtNode(GameRunData *runData,
1429 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1430 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1431 void handlePointingAtObject(GameRunData *runData,
1432 const PointedThing &pointed, const ItemStack &playeritem,
1433 const v3f &player_position, bool show_debug);
1434 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1435 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1437 void updateFrame(ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
1438 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1439 void updateGui(float *statustext_time, const RunStats &stats,
1440 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1441 const CameraOrientation &cam);
1442 void updateProfilerGraphs(ProfilerGraph *graph);
1445 void limitFps(FpsControl *fps_timings, f32 *dtime);
1447 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1448 bool draw_clouds = true);
1450 static void settingChangedCallback(const std::string &setting_name, void *data);
1451 void readSettings();
1453 inline bool getLeftClicked()
1455 return input->getLeftClicked() ||
1456 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1458 inline bool getRightClicked()
1460 return input->getRightClicked() ||
1461 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1463 inline bool isLeftPressed()
1465 return input->getLeftState() ||
1466 input->joystick.isKeyDown(KeyType::MOUSE_L);
1468 inline bool isRightPressed()
1470 return input->getRightState() ||
1471 input->joystick.isKeyDown(KeyType::MOUSE_R);
1473 inline bool getLeftReleased()
1475 return input->getLeftReleased() ||
1476 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1479 inline bool isKeyDown(GameKeyType k)
1481 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1483 inline bool wasKeyDown(GameKeyType k)
1485 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1489 void handleAndroidChatInput();
1493 InputHandler *input;
1498 IWritableTextureSource *texture_src;
1499 IWritableShaderSource *shader_src;
1501 // When created, these will be filled with data received from the server
1502 IWritableItemDefManager *itemdef_manager;
1503 IWritableNodeDefManager *nodedef_manager;
1505 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1506 ISoundManager *sound;
1507 bool sound_is_dummy;
1508 SoundMaker *soundmaker;
1510 ChatBackend *chat_backend;
1512 GUIFormSpecMenu *current_formspec;
1513 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1514 std::string cur_formname;
1516 EventManager *eventmgr;
1517 QuicktuneShortcutter *quicktune;
1519 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1520 MapDrawControl *draw_control;
1522 Clouds *clouds; // Free using ->Drop()
1523 Sky *sky; // Free using ->Drop()
1524 Inventory *local_inventory;
1528 GameRunData runData;
1529 VolatileRunFlags flags;
1532 This class does take ownership/responsibily for cleaning up etc of any of
1533 these items (e.g. device)
1535 IrrlichtDevice *device;
1536 video::IVideoDriver *driver;
1537 scene::ISceneManager *smgr;
1539 std::string *error_message;
1540 bool *reconnect_requested;
1541 scene::ISceneNode *skybox;
1544 bool simple_singleplayer_mode;
1547 /* Pre-calculated values
1549 int crack_animation_length;
1553 gui::IGUIStaticText *guitext; // First line of debug text
1554 gui::IGUIStaticText *guitext2; // Second line of debug text
1555 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1556 gui::IGUIStaticText *guitext_status;
1557 gui::IGUIStaticText *guitext_chat; // Chat text
1558 gui::IGUIStaticText *guitext_profiler; // Profiler text
1560 std::wstring infotext;
1561 std::wstring statustext;
1565 IntervalLimiter profiler_interval;
1568 * TODO: Local caching of settings is not optimal and should at some stage
1569 * be updated to use a global settings object for getting thse values
1570 * (as opposed to the this local caching). This can be addressed in
1573 bool m_cache_doubletap_jump;
1574 bool m_cache_enable_clouds;
1575 bool m_cache_enable_joysticks;
1576 bool m_cache_enable_particles;
1577 bool m_cache_enable_fog;
1578 bool m_cache_enable_noclip;
1579 bool m_cache_enable_free_move;
1580 f32 m_cache_mouse_sensitivity;
1581 f32 m_cache_joystick_frustum_sensitivity;
1582 f32 m_repeat_right_click_time;
1583 f32 m_cache_cam_smoothing;
1584 f32 m_cache_fog_start;
1587 bool m_cache_hold_aux1;
1588 bool m_android_chat_open;
1597 itemdef_manager(NULL),
1598 nodedef_manager(NULL),
1600 sound_is_dummy(false),
1603 current_formspec(NULL),
1607 gui_chat_console(NULL),
1612 local_inventory(NULL),
1616 g_settings->registerChangedCallback("doubletap_jump",
1617 &settingChangedCallback, this);
1618 g_settings->registerChangedCallback("enable_clouds",
1619 &settingChangedCallback, this);
1620 g_settings->registerChangedCallback("doubletap_joysticks",
1621 &settingChangedCallback, this);
1622 g_settings->registerChangedCallback("enable_particles",
1623 &settingChangedCallback, this);
1624 g_settings->registerChangedCallback("enable_fog",
1625 &settingChangedCallback, this);
1626 g_settings->registerChangedCallback("mouse_sensitivity",
1627 &settingChangedCallback, this);
1628 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1629 &settingChangedCallback, this);
1630 g_settings->registerChangedCallback("repeat_rightclick_time",
1631 &settingChangedCallback, this);
1632 g_settings->registerChangedCallback("noclip",
1633 &settingChangedCallback, this);
1634 g_settings->registerChangedCallback("free_move",
1635 &settingChangedCallback, this);
1636 g_settings->registerChangedCallback("cinematic",
1637 &settingChangedCallback, this);
1638 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1639 &settingChangedCallback, this);
1640 g_settings->registerChangedCallback("camera_smoothing",
1641 &settingChangedCallback, this);
1646 m_cache_hold_aux1 = false; // This is initialised properly later
1653 /****************************************************************************
1655 ****************************************************************************/
1661 if (!sound_is_dummy)
1664 delete server; // deleted first to stop all server threads
1667 delete local_inventory;
1673 delete nodedef_manager;
1674 delete itemdef_manager;
1675 delete draw_control;
1677 extendedResourceCleanup();
1679 g_settings->deregisterChangedCallback("doubletap_jump",
1680 &settingChangedCallback, this);
1681 g_settings->deregisterChangedCallback("enable_clouds",
1682 &settingChangedCallback, this);
1683 g_settings->deregisterChangedCallback("enable_particles",
1684 &settingChangedCallback, this);
1685 g_settings->deregisterChangedCallback("enable_fog",
1686 &settingChangedCallback, this);
1687 g_settings->deregisterChangedCallback("mouse_sensitivity",
1688 &settingChangedCallback, this);
1689 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1690 &settingChangedCallback, this);
1691 g_settings->deregisterChangedCallback("noclip",
1692 &settingChangedCallback, this);
1693 g_settings->deregisterChangedCallback("free_move",
1694 &settingChangedCallback, this);
1695 g_settings->deregisterChangedCallback("cinematic",
1696 &settingChangedCallback, this);
1697 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1698 &settingChangedCallback, this);
1699 g_settings->deregisterChangedCallback("camera_smoothing",
1700 &settingChangedCallback, this);
1703 bool Game::startup(bool *kill,
1705 InputHandler *input,
1706 IrrlichtDevice *device,
1707 const std::string &map_dir,
1708 const std::string &playername,
1709 const std::string &password,
1710 std::string *address, // can change if simple_singleplayer_mode
1712 std::string &error_message,
1714 ChatBackend *chat_backend,
1715 const SubgameSpec &gamespec,
1716 bool simple_singleplayer_mode)
1719 this->device = device;
1721 this->error_message = &error_message;
1722 this->reconnect_requested = reconnect;
1723 this->random_input = random_input;
1724 this->input = input;
1725 this->chat_backend = chat_backend;
1726 this->simple_singleplayer_mode = simple_singleplayer_mode;
1728 keycache.handler = input;
1729 keycache.populate();
1731 driver = device->getVideoDriver();
1732 smgr = device->getSceneManager();
1734 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1736 memset(&runData, 0, sizeof(runData));
1737 runData.time_from_last_punch = 10.0;
1738 runData.profiler_max_page = 3;
1739 runData.update_wielded_item_trigger = true;
1741 memset(&flags, 0, sizeof(flags));
1742 flags.show_chat = true;
1743 flags.show_hud = true;
1744 flags.show_debug = g_settings->getBool("show_debug");
1745 flags.invert_mouse = g_settings->getBool("invert_mouse");
1746 flags.first_loop_after_window_activation = true;
1748 if (!init(map_dir, address, port, gamespec))
1751 if (!createClient(playername, password, address, port))
1760 ProfilerGraph graph;
1761 RunStats stats = { 0 };
1762 CameraOrientation cam_view_target = { 0 };
1763 CameraOrientation cam_view = { 0 };
1764 FpsControl draw_times = { 0 };
1765 f32 dtime; // in seconds
1767 /* Clear the profiler */
1768 Profiler::GraphValues dummyvalues;
1769 g_profiler->graphGet(dummyvalues);
1771 draw_times.last_time = device->getTimer()->getTime();
1773 set_light_table(g_settings->getFloat("display_gamma"));
1776 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1777 && client->checkPrivilege("fast");
1780 while (device->run()
1781 && !(*kill || g_gamecallback->shutdown_requested
1782 || (server && server->getShutdownRequested()))) {
1784 /* Must be called immediately after a device->run() call because it
1785 * uses device->getTimer()->getTime()
1787 limitFps(&draw_times, &dtime);
1789 updateStats(&stats, draw_times, dtime);
1790 updateInteractTimers(&runData, dtime);
1792 if (!checkConnection())
1794 if (!handleCallbacks())
1800 hud->resizeHotbar();
1802 updateProfilers(runData, stats, draw_times, dtime);
1803 processUserInput(&flags, &runData, dtime);
1804 // Update camera before player movement to avoid camera lag of one frame
1805 updateCameraDirection(&cam_view_target, &flags, dtime);
1806 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1807 cam_view.camera_yaw) * m_cache_cam_smoothing;
1808 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1809 cam_view.camera_pitch) * m_cache_cam_smoothing;
1810 updatePlayerControl(cam_view);
1812 processClientEvents(&cam_view_target, &runData.damage_flash);
1813 updateCamera(&flags, draw_times.busy_time, dtime,
1814 runData.time_from_last_punch);
1816 processPlayerInteraction(&runData, dtime, flags.show_hud,
1818 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
1819 updateProfilerGraphs(&graph);
1821 // Update if minimap has been disabled by the server
1822 flags.show_minimap &= !client->isMinimapDisabledByServer();
1827 void Game::shutdown()
1829 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1830 if (g_settings->get("3d_mode") == "pageflip") {
1831 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1835 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1840 if (gui_chat_console)
1841 gui_chat_console->drop();
1847 while (g_menumgr.menuCount() > 0) {
1848 g_menumgr.m_stack.front()->setVisible(false);
1849 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1852 if (current_formspec) {
1853 current_formspec->drop();
1854 current_formspec = NULL;
1857 chat_backend->addMessage(L"", L"# Disconnected.");
1858 chat_backend->addMessage(L"", L"");
1862 while (!client->isShutdown()) {
1863 assert(texture_src != NULL);
1864 assert(shader_src != NULL);
1865 texture_src->processQueue();
1866 shader_src->processQueue();
1873 /****************************************************************************/
1874 /****************************************************************************
1876 ****************************************************************************/
1877 /****************************************************************************/
1880 const std::string &map_dir,
1881 std::string *address,
1883 const SubgameSpec &gamespec)
1885 showOverlayMessage(wgettext("Loading..."), 0, 0);
1887 texture_src = createTextureSource(device);
1888 shader_src = createShaderSource(device);
1890 itemdef_manager = createItemDefManager();
1891 nodedef_manager = createNodeDefManager();
1893 eventmgr = new EventManager();
1894 quicktune = new QuicktuneShortcutter();
1896 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1897 && eventmgr && quicktune))
1903 // Create a server if not connecting to an existing one
1904 if (*address == "") {
1905 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1912 bool Game::initSound()
1915 if (g_settings->getBool("enable_sound")) {
1916 infostream << "Attempting to use OpenAL audio" << std::endl;
1917 sound = createOpenALSoundManager(&soundfetcher);
1919 infostream << "Failed to initialize OpenAL audio" << std::endl;
1921 infostream << "Sound disabled." << std::endl;
1925 infostream << "Using dummy audio." << std::endl;
1926 sound = &dummySoundManager;
1927 sound_is_dummy = true;
1930 soundmaker = new SoundMaker(sound, nodedef_manager);
1934 soundmaker->registerReceiver(eventmgr);
1939 bool Game::createSingleplayerServer(const std::string map_dir,
1940 const SubgameSpec &gamespec, u16 port, std::string *address)
1942 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1944 std::string bind_str = g_settings->get("bind_address");
1945 Address bind_addr(0, 0, 0, 0, port);
1947 if (g_settings->getBool("ipv6_server")) {
1948 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1952 bind_addr.Resolve(bind_str.c_str());
1953 } catch (ResolveError &e) {
1954 infostream << "Resolving bind address \"" << bind_str
1955 << "\" failed: " << e.what()
1956 << " -- Listening on all addresses." << std::endl;
1959 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1960 *error_message = "Unable to listen on " +
1961 bind_addr.serializeString() +
1962 " because IPv6 is disabled";
1963 errorstream << *error_message << std::endl;
1967 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1968 bind_addr.isIPv6());
1970 server->start(bind_addr);
1975 bool Game::createClient(const std::string &playername,
1976 const std::string &password, std::string *address, u16 port)
1978 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1980 draw_control = new MapDrawControl;
1984 bool could_connect, connect_aborted;
1986 if (!connectToServer(playername, password, address, port,
1987 &could_connect, &connect_aborted))
1990 if (!could_connect) {
1991 if (error_message->empty() && !connect_aborted) {
1992 // Should not happen if error messages are set properly
1993 *error_message = "Connection failed for unknown reason";
1994 errorstream << *error_message << std::endl;
1999 if (!getServerContent(&connect_aborted)) {
2000 if (error_message->empty() && !connect_aborted) {
2001 // Should not happen if error messages are set properly
2002 *error_message = "Connection failed for unknown reason";
2003 errorstream << *error_message << std::endl;
2008 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
2009 &flags.force_fog_off, &runData.fog_range, client);
2010 shader_src->addShaderConstantSetterFactory(scsf);
2012 // Update cached textures, meshes and materials
2013 client->afterContentReceived(device);
2017 camera = new Camera(smgr, *draw_control, client);
2018 if (!camera || !camera->successfullyCreated(*error_message))
2020 client->setCamera(camera);
2024 if (m_cache_enable_clouds) {
2025 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2027 *error_message = "Memory allocation error (clouds)";
2028 errorstream << *error_message << std::endl;
2035 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2037 skybox = NULL; // This is used/set later on in the main run loop
2039 local_inventory = new Inventory(itemdef_manager);
2041 if (!(sky && local_inventory)) {
2042 *error_message = "Memory allocation error (sky or local inventory)";
2043 errorstream << *error_message << std::endl;
2047 /* Pre-calculated values
2049 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2051 v2u32 size = t->getOriginalSize();
2052 crack_animation_length = size.Y / size.X;
2054 crack_animation_length = 5;
2060 /* Set window caption
2062 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2064 str += utf8_to_wide(g_version_hash);
2066 str += driver->getName();
2068 device->setWindowCaption(str.c_str());
2070 LocalPlayer *player = client->getEnv().getLocalPlayer();
2071 player->hurt_tilt_timer = 0;
2072 player->hurt_tilt_strength = 0;
2074 hud = new Hud(driver, smgr, guienv, client, player, local_inventory);
2077 *error_message = "Memory error: could not create HUD";
2078 errorstream << *error_message << std::endl;
2082 mapper = client->getMapper();
2083 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2088 bool Game::initGui()
2090 // First line of debug text
2091 guitext = addStaticText(guienv,
2092 utf8_to_wide(PROJECT_NAME_C).c_str(),
2093 core::rect<s32>(0, 0, 0, 0),
2094 false, false, guiroot);
2096 // Second line of debug text
2097 guitext2 = addStaticText(guienv,
2099 core::rect<s32>(0, 0, 0, 0),
2100 false, false, guiroot);
2102 // At the middle of the screen
2103 // Object infos are shown in this
2104 guitext_info = addStaticText(guienv,
2106 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2107 false, true, guiroot);
2109 // Status text (displays info when showing and hiding GUI stuff, etc.)
2110 guitext_status = addStaticText(guienv,
2112 core::rect<s32>(0, 0, 0, 0),
2113 false, false, guiroot);
2114 guitext_status->setVisible(false);
2117 guitext_chat = addStaticText(
2120 core::rect<s32>(0, 0, 0, 0),
2121 //false, false); // Disable word wrap as of now
2122 false, true, guiroot);
2124 // Remove stale "recent" chat messages from previous connections
2125 chat_backend->clearRecentChat();
2127 // Chat backend and console
2128 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2129 -1, chat_backend, client, &g_menumgr);
2130 if (!gui_chat_console) {
2131 *error_message = "Could not allocate memory for chat console";
2132 errorstream << *error_message << std::endl;
2136 // Profiler text (size is updated when text is updated)
2137 guitext_profiler = addStaticText(guienv,
2139 core::rect<s32>(0, 0, 0, 0),
2140 false, false, guiroot);
2141 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2142 guitext_profiler->setVisible(false);
2143 guitext_profiler->setWordWrap(true);
2145 #ifdef HAVE_TOUCHSCREENGUI
2147 if (g_touchscreengui)
2148 g_touchscreengui->init(texture_src);
2155 bool Game::connectToServer(const std::string &playername,
2156 const std::string &password, std::string *address, u16 port,
2157 bool *connect_ok, bool *aborted)
2159 *connect_ok = false; // Let's not be overly optimistic
2161 bool local_server_mode = false;
2163 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2165 Address connect_address(0, 0, 0, 0, port);
2168 connect_address.Resolve(address->c_str());
2170 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2171 //connect_address.Resolve("localhost");
2172 if (connect_address.isIPv6()) {
2173 IPv6AddressBytes addr_bytes;
2174 addr_bytes.bytes[15] = 1;
2175 connect_address.setAddress(&addr_bytes);
2177 connect_address.setAddress(127, 0, 0, 1);
2179 local_server_mode = true;
2181 } catch (ResolveError &e) {
2182 *error_message = std::string("Couldn't resolve address: ") + e.what();
2183 errorstream << *error_message << std::endl;
2187 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2188 *error_message = "Unable to connect to " +
2189 connect_address.serializeString() +
2190 " because IPv6 is disabled";
2191 errorstream << *error_message << std::endl;
2195 client = new Client(device,
2196 playername.c_str(), password,
2197 *draw_control, texture_src, shader_src,
2198 itemdef_manager, nodedef_manager, sound, eventmgr,
2199 connect_address.isIPv6());
2204 infostream << "Connecting to server at ";
2205 connect_address.print(&infostream);
2206 infostream << std::endl;
2208 client->connect(connect_address, *address,
2209 simple_singleplayer_mode || local_server_mode);
2212 Wait for server to accept connection
2218 FpsControl fps_control = { 0 };
2220 f32 wait_time = 0; // in seconds
2222 fps_control.last_time = device->getTimer()->getTime();
2224 while (device->run()) {
2226 limitFps(&fps_control, &dtime);
2228 // Update client and server
2229 client->step(dtime);
2232 server->step(dtime);
2235 if (client->getState() == LC_Init) {
2241 if (client->accessDenied()) {
2242 *error_message = "Access denied. Reason: "
2243 + client->accessDeniedReason();
2244 *reconnect_requested = client->reconnectRequested();
2245 errorstream << *error_message << std::endl;
2249 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2251 infostream << "Connect aborted [Escape]" << std::endl;
2256 // Only time out if we aren't waiting for the server we started
2257 if ((*address != "") && (wait_time > 10)) {
2258 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2259 // If no pre v25 init was sent, and no answer was received,
2260 // but the low level connection could be established
2261 // (meaning that we have a peer id), then we probably wanted
2262 // to connect to a legacy server. In this case, tell the user
2263 // to enable the option to be able to connect.
2264 if (!sent_old_init &&
2265 (client->getProtoVersion() == 0) &&
2266 client->connectedToServer()) {
2267 *error_message = "Connection failure: init packet not "
2268 "recognized by server.\n"
2269 "Most likely the server uses an old protocol version (<v25).\n"
2270 "Please ask the server owner to update to 0.4.13 or later.\n"
2271 "To still connect to the server in the meantime,\n"
2272 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2273 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2274 "entry in the advanced settings menu.";
2276 *error_message = "Connection timed out.";
2278 errorstream << *error_message << std::endl;
2283 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2285 } catch (con::PeerNotFoundException &e) {
2286 // TODO: Should something be done here? At least an info/error
2294 bool Game::getServerContent(bool *aborted)
2298 FpsControl fps_control = { 0 };
2299 f32 dtime; // in seconds
2301 fps_control.last_time = device->getTimer()->getTime();
2303 while (device->run()) {
2305 limitFps(&fps_control, &dtime);
2307 // Update client and server
2308 client->step(dtime);
2311 server->step(dtime);
2314 if (client->mediaReceived() && client->itemdefReceived() &&
2315 client->nodedefReceived()) {
2320 if (!checkConnection())
2323 if (client->getState() < LC_Init) {
2324 *error_message = "Client disconnected";
2325 errorstream << *error_message << std::endl;
2329 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2331 infostream << "Connect aborted [Escape]" << std::endl;
2338 if (!client->itemdefReceived()) {
2339 const wchar_t *text = wgettext("Item definitions...");
2341 draw_load_screen(text, device, guienv, dtime, progress);
2343 } else if (!client->nodedefReceived()) {
2344 const wchar_t *text = wgettext("Node definitions...");
2346 draw_load_screen(text, device, guienv, dtime, progress);
2349 std::stringstream message;
2350 message.precision(3);
2351 message << gettext("Media...");
2353 if ((USE_CURL == 0) ||
2354 (!g_settings->getBool("enable_remote_media_server"))) {
2355 float cur = client->getCurRate();
2356 std::string cur_unit = gettext("KiB/s");
2360 cur_unit = gettext("MiB/s");
2363 message << " (" << cur << ' ' << cur_unit << ")";
2366 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2367 draw_load_screen(utf8_to_wide(message.str()), device,
2368 guienv, dtime, progress);
2376 /****************************************************************************/
2377 /****************************************************************************
2379 ****************************************************************************/
2380 /****************************************************************************/
2382 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2384 if (runData->nodig_delay_timer >= 0)
2385 runData->nodig_delay_timer -= dtime;
2387 if (runData->object_hit_delay_timer >= 0)
2388 runData->object_hit_delay_timer -= dtime;
2390 runData->time_from_last_punch += dtime;
2394 /* returns false if game should exit, otherwise true
2396 inline bool Game::checkConnection()
2398 if (client->accessDenied()) {
2399 *error_message = "Access denied. Reason: "
2400 + client->accessDeniedReason();
2401 *reconnect_requested = client->reconnectRequested();
2402 errorstream << *error_message << std::endl;
2410 /* returns false if game should exit, otherwise true
2412 inline bool Game::handleCallbacks()
2414 if (g_gamecallback->disconnect_requested) {
2415 g_gamecallback->disconnect_requested = false;
2419 if (g_gamecallback->changepassword_requested) {
2420 (new GUIPasswordChange(guienv, guiroot, -1,
2421 &g_menumgr, client))->drop();
2422 g_gamecallback->changepassword_requested = false;
2425 if (g_gamecallback->changevolume_requested) {
2426 (new GUIVolumeChange(guienv, guiroot, -1,
2427 &g_menumgr))->drop();
2428 g_gamecallback->changevolume_requested = false;
2431 if (g_gamecallback->keyconfig_requested) {
2432 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2433 &g_menumgr))->drop();
2434 g_gamecallback->keyconfig_requested = false;
2437 if (g_gamecallback->keyconfig_changed) {
2438 keycache.populate(); // update the cache with new settings
2439 g_gamecallback->keyconfig_changed = false;
2446 void Game::processQueues()
2448 texture_src->processQueue();
2449 itemdef_manager->processQueue(client);
2450 shader_src->processQueue();
2454 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2455 const FpsControl &draw_times, f32 dtime)
2457 float profiler_print_interval =
2458 g_settings->getFloat("profiler_print_interval");
2459 bool print_to_log = true;
2461 if (profiler_print_interval == 0) {
2462 print_to_log = false;
2463 profiler_print_interval = 5;
2466 if (profiler_interval.step(dtime, profiler_print_interval)) {
2468 infostream << "Profiler:" << std::endl;
2469 g_profiler->print(infostream);
2472 update_profiler_gui(guitext_profiler, g_fontengine,
2473 runData.profiler_current_page, runData.profiler_max_page,
2474 driver->getScreenSize().Height);
2476 g_profiler->clear();
2479 addProfilerGraphs(stats, draw_times, dtime);
2483 void Game::addProfilerGraphs(const RunStats &stats,
2484 const FpsControl &draw_times, f32 dtime)
2486 g_profiler->graphAdd("mainloop_other",
2487 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2489 if (draw_times.sleep_time != 0)
2490 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2491 g_profiler->graphAdd("mainloop_dtime", dtime);
2493 g_profiler->add("Elapsed time", dtime);
2494 g_profiler->avg("FPS", 1. / dtime);
2498 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2505 /* Time average and jitter calculation
2507 jp = &stats->dtime_jitter;
2508 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2510 jitter = dtime - jp->avg;
2512 if (jitter > jp->max)
2515 jp->counter += dtime;
2517 if (jp->counter > 0.0) {
2519 jp->max_sample = jp->max;
2520 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2524 /* Busytime average and jitter calculation
2526 jp = &stats->busy_time_jitter;
2527 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2529 jitter = draw_times.busy_time - jp->avg;
2531 if (jitter > jp->max)
2533 if (jitter < jp->min)
2536 jp->counter += dtime;
2538 if (jp->counter > 0.0) {
2540 jp->max_sample = jp->max;
2541 jp->min_sample = jp->min;
2549 /****************************************************************************
2551 ****************************************************************************/
2553 void Game::processUserInput(VolatileRunFlags *flags,
2554 GameRunData *runData, f32 dtime)
2556 // Reset input if window not active or some menu is active
2557 if (device->isWindowActive() == false
2558 || noMenuActive() == false
2559 || guienv->hasFocus(gui_chat_console)) {
2561 #ifdef HAVE_TOUCHSCREENGUI
2562 g_touchscreengui->hide();
2565 #ifdef HAVE_TOUCHSCREENGUI
2566 else if (g_touchscreengui) {
2567 /* on touchscreengui step may generate own input events which ain't
2568 * what we want in case we just did clear them */
2569 g_touchscreengui->step(dtime);
2573 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2574 gui_chat_console->closeConsoleAtOnce();
2577 // Input handler step() (used by the random input generator)
2581 if (current_formspec != NULL)
2582 current_formspec->getAndroidUIInput();
2584 handleAndroidChatInput();
2587 // Increase timer for double tap of "keymap_jump"
2588 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2589 runData->jump_timer += dtime;
2593 &runData->statustext_time,
2594 &runData->jump_timer,
2595 &runData->reset_jump_timer,
2596 &runData->profiler_current_page,
2597 runData->profiler_max_page);
2599 processItemSelection(&runData->new_playeritem);
2603 void Game::processKeyInput(VolatileRunFlags *flags,
2604 float *statustext_time,
2606 bool *reset_jump_timer,
2607 u32 *profiler_current_page,
2608 u32 profiler_max_page)
2611 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2613 if (wasKeyDown(KeyType::DROP)) {
2615 } else if (wasKeyDown(KeyType::AUTORUN)) {
2616 toggleAutorun(statustext_time);
2617 } else if (wasKeyDown(KeyType::INVENTORY)) {
2619 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2620 if (!gui_chat_console->isOpenInhibited()) {
2621 show_pause_menu(¤t_formspec, client,
2622 texture_src, device, &input->joystick,
2623 simple_singleplayer_mode);
2625 } else if (wasKeyDown(KeyType::CHAT)) {
2626 openConsole(0.2, L"");
2627 } else if (wasKeyDown(KeyType::CMD)) {
2628 openConsole(0.2, L"/");
2629 } else if (wasKeyDown(KeyType::CONSOLE)) {
2630 openConsole(core::clamp(
2631 g_settings->getFloat("console_height"), 0.1f, 1.0f));
2632 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2633 toggleFreeMove(statustext_time);
2634 } else if (wasKeyDown(KeyType::JUMP)) {
2635 toggleFreeMoveAlt(statustext_time, jump_timer);
2636 *reset_jump_timer = true;
2637 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2638 toggleFast(statustext_time);
2639 } else if (wasKeyDown(KeyType::NOCLIP)) {
2640 toggleNoClip(statustext_time);
2641 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2642 toggleCinematic(statustext_time);
2643 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2644 client->makeScreenshot(device);
2645 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2646 toggleHud(statustext_time, &flags->show_hud);
2647 } else if (wasKeyDown(KeyType::MINIMAP)) {
2648 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2649 isKeyDown(KeyType::SNEAK));
2650 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2651 toggleChat(statustext_time, &flags->show_chat);
2652 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2653 toggleFog(statustext_time, &flags->force_fog_off);
2654 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2655 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2656 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2657 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph,
2658 &draw_control->show_wireframe);
2659 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2660 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2661 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2662 increaseViewRange(statustext_time);
2663 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2664 decreaseViewRange(statustext_time);
2665 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2666 toggleFullViewRange(statustext_time);
2667 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2669 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2671 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2673 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2675 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2676 // Print debug stacks
2677 dstream << "-----------------------------------------"
2679 dstream << "Printing debug stacks:" << std::endl;
2680 dstream << "-----------------------------------------"
2682 debug_stacks_print();
2685 if (!isKeyDown(KeyType::JUMP) && *reset_jump_timer) {
2686 *reset_jump_timer = false;
2692 if (quicktune->hasMessage()) {
2693 std::string msg = quicktune->getMessage();
2694 statustext = utf8_to_wide(msg);
2695 *statustext_time = 0;
2699 void Game::processItemSelection(u16 *new_playeritem)
2701 LocalPlayer *player = client->getEnv().getLocalPlayer();
2703 /* Item selection using mouse wheel
2705 *new_playeritem = client->getPlayerItem();
2707 s32 wheel = input->getMouseWheel();
2708 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2709 player->hud_hotbar_itemcount - 1);
2713 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN)) {
2717 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP)) {
2722 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2724 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2727 /* Item selection using keyboard
2729 for (u16 i = 0; i < 10; i++) {
2730 static const KeyPress *item_keys[10] = {
2731 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2732 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2733 NumberKey + 9, NumberKey + 0,
2736 if (input->wasKeyDown(*item_keys[i])) {
2737 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2738 *new_playeritem = i;
2739 infostream << "Selected item: " << new_playeritem << std::endl;
2747 void Game::dropSelectedItem()
2749 IDropAction *a = new IDropAction();
2751 a->from_inv.setCurrentPlayer();
2752 a->from_list = "main";
2753 a->from_i = client->getPlayerItem();
2754 client->inventoryAction(a);
2758 void Game::openInventory()
2761 * Don't permit to open inventory is CAO or player doesn't exists.
2762 * This prevent showing an empty inventory at player load
2765 LocalPlayer *player = client->getEnv().getLocalPlayer();
2766 if (player == NULL || player->getCAO() == NULL)
2769 infostream << "the_game: " << "Launching inventory" << std::endl;
2771 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2772 TextDest *txt_dst = new TextDestPlayerInventory(client);
2774 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
2777 InventoryLocation inventoryloc;
2778 inventoryloc.setCurrentPlayer();
2779 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2783 void Game::openConsole(float scale, const wchar_t *line)
2785 assert(scale > 0.0f && scale <= 1.0f);
2788 porting::showInputDialog(gettext("ok"), "", "", 2);
2789 m_android_chat_open = true;
2791 if (gui_chat_console->isOpenInhibited())
2793 gui_chat_console->openConsole(scale);
2795 gui_chat_console->setCloseOnEnter(true);
2796 gui_chat_console->replaceAndAddToHistory(line);
2802 void Game::handleAndroidChatInput()
2804 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2805 std::string text = porting::getInputDialogValue();
2806 client->typeChatMessage(utf8_to_wide(text));
2812 void Game::toggleFreeMove(float *statustext_time)
2814 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2816 bool free_move = !g_settings->getBool("free_move");
2817 g_settings->set("free_move", bool_to_cstr(free_move));
2819 *statustext_time = 0;
2820 statustext = msg[free_move];
2821 if (free_move && !client->checkPrivilege("fly"))
2822 statustext += L" (note: no 'fly' privilege)";
2826 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2828 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2829 toggleFreeMove(statustext_time);
2833 void Game::toggleFast(float *statustext_time)
2835 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2836 bool fast_move = !g_settings->getBool("fast_move");
2837 g_settings->set("fast_move", bool_to_cstr(fast_move));
2839 *statustext_time = 0;
2840 statustext = msg[fast_move];
2842 bool has_fast_privs = client->checkPrivilege("fast");
2844 if (fast_move && !has_fast_privs)
2845 statustext += L" (note: no 'fast' privilege)";
2848 m_cache_hold_aux1 = fast_move && has_fast_privs;
2853 void Game::toggleNoClip(float *statustext_time)
2855 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2856 bool noclip = !g_settings->getBool("noclip");
2857 g_settings->set("noclip", bool_to_cstr(noclip));
2859 *statustext_time = 0;
2860 statustext = msg[noclip];
2862 if (noclip && !client->checkPrivilege("noclip"))
2863 statustext += L" (note: no 'noclip' privilege)";
2866 void Game::toggleCinematic(float *statustext_time)
2868 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2869 bool cinematic = !g_settings->getBool("cinematic");
2870 g_settings->set("cinematic", bool_to_cstr(cinematic));
2872 *statustext_time = 0;
2873 statustext = msg[cinematic];
2876 // Add WoW-style autorun by toggling continuous forward.
2877 void Game::toggleAutorun(float *statustext_time)
2879 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2880 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2881 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2883 *statustext_time = 0;
2884 statustext = msg[autorun_enabled ? 1 : 0];
2887 void Game::toggleChat(float *statustext_time, bool *flag)
2889 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2892 *statustext_time = 0;
2893 statustext = msg[*flag];
2897 void Game::toggleHud(float *statustext_time, bool *flag)
2899 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2902 *statustext_time = 0;
2903 statustext = msg[*flag];
2906 void Game::toggleMinimap(float *statustext_time, bool *flag,
2907 bool show_hud, bool shift_pressed)
2909 if (!show_hud || !g_settings->getBool("enable_minimap"))
2912 if (shift_pressed) {
2913 mapper->toggleMinimapShape();
2917 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2919 MinimapMode mode = MINIMAP_MODE_OFF;
2920 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2921 mode = mapper->getMinimapMode();
2922 mode = (MinimapMode)((int)mode + 1);
2927 case MINIMAP_MODE_SURFACEx1:
2928 statustext = L"Minimap in surface mode, Zoom x1";
2930 case MINIMAP_MODE_SURFACEx2:
2931 statustext = L"Minimap in surface mode, Zoom x2";
2933 case MINIMAP_MODE_SURFACEx4:
2934 statustext = L"Minimap in surface mode, Zoom x4";
2936 case MINIMAP_MODE_RADARx1:
2937 statustext = L"Minimap in radar mode, Zoom x1";
2939 case MINIMAP_MODE_RADARx2:
2940 statustext = L"Minimap in radar mode, Zoom x2";
2942 case MINIMAP_MODE_RADARx4:
2943 statustext = L"Minimap in radar mode, Zoom x4";
2946 mode = MINIMAP_MODE_OFF;
2948 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2949 L"Minimap hidden" : L"Minimap disabled by server";
2952 *statustext_time = 0;
2953 mapper->setMinimapMode(mode);
2956 void Game::toggleFog(float *statustext_time, bool *flag)
2958 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2961 *statustext_time = 0;
2962 statustext = msg[*flag];
2966 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2967 bool *show_profiler_graph, bool *show_wireframe)
2969 // Initial / 4x toggle: Chat only
2970 // 1x toggle: Debug text with chat
2971 // 2x toggle: Debug text with profiler graph
2972 // 3x toggle: Debug text and wireframe
2975 *show_profiler_graph = false;
2976 *show_wireframe = false;
2977 statustext = L"Debug info shown";
2978 } else if (!*show_profiler_graph && !*show_wireframe) {
2979 *show_profiler_graph = true;
2980 statustext = L"Profiler graph shown";
2981 } else if (!*show_wireframe && client->checkPrivilege("debug")) {
2982 *show_profiler_graph = false;
2983 *show_wireframe = true;
2984 statustext = L"Wireframe shown";
2986 *show_debug = false;
2987 *show_profiler_graph = false;
2988 *show_wireframe = false;
2989 if (client->checkPrivilege("debug")) {
2990 statustext = L"Debug info, profiler graph, and wireframe hidden";
2992 statustext = L"Debug info and profiler graph hidden";
2995 *statustext_time = 0;
2999 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
3001 static const wchar_t *msg[] = {
3002 L"Camera update enabled",
3003 L"Camera update disabled"
3007 *statustext_time = 0;
3008 statustext = msg[*flag];
3012 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
3013 u32 profiler_max_page)
3015 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
3017 // FIXME: This updates the profiler with incomplete values
3018 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
3019 profiler_max_page, driver->getScreenSize().Height);
3021 if (*profiler_current_page != 0) {
3022 std::wstringstream sstr;
3023 sstr << "Profiler shown (page " << *profiler_current_page
3024 << " of " << profiler_max_page << ")";
3025 statustext = sstr.str();
3027 statustext = L"Profiler hidden";
3029 *statustext_time = 0;
3033 void Game::increaseViewRange(float *statustext_time)
3035 s16 range = g_settings->getS16("viewing_range");
3036 s16 range_new = range + 10;
3038 if (range_new > 4000) {
3040 statustext = utf8_to_wide("Viewing range is at maximum: "
3043 statustext = utf8_to_wide("Viewing range changed to "
3046 g_settings->set("viewing_range", itos(range_new));
3047 *statustext_time = 0;
3051 void Game::decreaseViewRange(float *statustext_time)
3053 s16 range = g_settings->getS16("viewing_range");
3054 s16 range_new = range - 10;
3056 if (range_new < 20) {
3058 statustext = utf8_to_wide("Viewing range is at minimum: "
3061 statustext = utf8_to_wide("Viewing range changed to "
3064 g_settings->set("viewing_range", itos(range_new));
3065 *statustext_time = 0;
3069 void Game::toggleFullViewRange(float *statustext_time)
3071 static const wchar_t *msg[] = {
3072 L"Disabled full viewing range",
3073 L"Enabled full viewing range"
3076 draw_control->range_all = !draw_control->range_all;
3077 infostream << msg[draw_control->range_all] << std::endl;
3078 statustext = msg[draw_control->range_all];
3079 *statustext_time = 0;
3083 void Game::updateCameraDirection(CameraOrientation *cam,
3084 VolatileRunFlags *flags, float dtime)
3086 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3089 if (!random_input) {
3090 // Mac OSX gets upset if this is set every frame
3091 if (device->getCursorControl()->isVisible())
3092 device->getCursorControl()->setVisible(false);
3096 if (flags->first_loop_after_window_activation)
3097 flags->first_loop_after_window_activation = false;
3099 updateCameraOrientation(cam, *flags, dtime);
3101 input->setMousePos((driver->getScreenSize().Width / 2),
3102 (driver->getScreenSize().Height / 2));
3106 // Mac OSX gets upset if this is set every frame
3107 if (device->getCursorControl()->isVisible() == false)
3108 device->getCursorControl()->setVisible(true);
3111 if (!flags->first_loop_after_window_activation)
3112 flags->first_loop_after_window_activation = true;
3117 void Game::updateCameraOrientation(CameraOrientation *cam,
3118 const VolatileRunFlags &flags, float dtime)
3120 #ifdef HAVE_TOUCHSCREENGUI
3121 if (g_touchscreengui) {
3122 cam->camera_yaw += g_touchscreengui->getYawChange();
3123 cam->camera_pitch = g_touchscreengui->getPitch();
3127 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3128 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3130 if (flags.invert_mouse
3131 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3135 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3136 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3138 #ifdef HAVE_TOUCHSCREENGUI
3142 if (m_cache_enable_joysticks) {
3143 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3144 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) *
3146 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) *
3150 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3154 void Game::updatePlayerControl(const CameraOrientation &cam)
3156 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3158 // DO NOT use the isKeyDown method for the forward, backward, left, right
3159 // buttons, as the code that uses the controls needs to be able to
3160 // distinguish between the two in order to know when to use joysticks.
3162 PlayerControl control(
3163 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3164 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3165 input->isKeyDown(keycache.key[KeyType::LEFT]),
3166 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3167 isKeyDown(KeyType::JUMP),
3168 isKeyDown(KeyType::SPECIAL1),
3169 isKeyDown(KeyType::SNEAK),
3170 isKeyDown(KeyType::ZOOM),
3175 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3176 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3180 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3181 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3182 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3183 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3184 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3185 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3186 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3187 ( (u32)(isLeftPressed() & 0x1) << 7) |
3188 ( (u32)(isRightPressed() & 0x1) << 8
3192 /* For Android, simulate holding down AUX1 (fast move) if the user has
3193 * the fast_move setting toggled on. If there is an aux1 key defined for
3194 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3197 if (m_cache_hold_aux1) {
3198 control.aux1 = control.aux1 ^ true;
3199 keypress_bits ^= ((u32)(1U << 5));
3203 client->setPlayerControl(control);
3204 LocalPlayer *player = client->getEnv().getLocalPlayer();
3205 player->keyPressed = keypress_bits;
3211 inline void Game::step(f32 *dtime)
3213 bool can_be_and_is_paused =
3214 (simple_singleplayer_mode && g_menumgr.pausesGame());
3216 if (can_be_and_is_paused) { // This is for a singleplayer server
3217 *dtime = 0; // No time passes
3219 if (server != NULL) {
3220 //TimeTaker timer("server->step(dtime)");
3221 server->step(*dtime);
3224 //TimeTaker timer("client.step(dtime)");
3225 client->step(*dtime);
3230 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3232 ClientEvent event = client->getClientEvent();
3234 LocalPlayer *player = client->getEnv().getLocalPlayer();
3236 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3238 if (event.type == CE_PLAYER_DAMAGE &&
3239 client->getHP() != 0) {
3240 //u16 damage = event.player_damage.amount;
3241 //infostream<<"Player damage: "<<damage<<std::endl;
3243 *damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3244 *damage_flash = MYMIN(*damage_flash, 127.0);
3246 player->hurt_tilt_timer = 1.5;
3247 player->hurt_tilt_strength =
3248 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3250 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3251 client->event()->put(e);
3252 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3253 cam->camera_yaw = event.player_force_move.yaw;
3254 cam->camera_pitch = event.player_force_move.pitch;
3255 } else if (event.type == CE_DEATHSCREEN) {
3256 show_deathscreen(¤t_formspec, client, texture_src,
3257 device, &input->joystick);
3259 chat_backend->addMessage(L"", L"You died.");
3261 /* Handle visualization */
3263 player->hurt_tilt_timer = 0;
3264 player->hurt_tilt_strength = 0;
3266 } else if (event.type == CE_SHOW_FORMSPEC) {
3267 if (*(event.show_formspec.formspec) == "") {
3268 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3269 current_formspec->quitMenu();
3272 FormspecFormSource *fs_src =
3273 new FormspecFormSource(*(event.show_formspec.formspec));
3274 TextDestPlayerInventory *txt_dst =
3275 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3277 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3279 cur_formname = *(event.show_formspec.formname);
3282 delete(event.show_formspec.formspec);
3283 delete(event.show_formspec.formname);
3284 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3285 (event.type == CE_ADD_PARTICLESPAWNER) ||
3286 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3287 client->getParticleManager()->handleParticleEvent(&event, client,
3289 } else if (event.type == CE_HUDADD) {
3290 u32 id = event.hudadd.id;
3292 LocalPlayer *player = client->getEnv().getLocalPlayer();
3293 HudElement *e = player->getHud(id);
3296 delete event.hudadd.pos;
3297 delete event.hudadd.name;
3298 delete event.hudadd.scale;
3299 delete event.hudadd.text;
3300 delete event.hudadd.align;
3301 delete event.hudadd.offset;
3302 delete event.hudadd.world_pos;
3303 delete event.hudadd.size;
3308 e->type = (HudElementType)event.hudadd.type;
3309 e->pos = *event.hudadd.pos;
3310 e->name = *event.hudadd.name;
3311 e->scale = *event.hudadd.scale;
3312 e->text = *event.hudadd.text;
3313 e->number = event.hudadd.number;
3314 e->item = event.hudadd.item;
3315 e->dir = event.hudadd.dir;
3316 e->align = *event.hudadd.align;
3317 e->offset = *event.hudadd.offset;
3318 e->world_pos = *event.hudadd.world_pos;
3319 e->size = *event.hudadd.size;
3321 u32 new_id = player->addHud(e);
3322 //if this isn't true our huds aren't consistent
3323 sanity_check(new_id == id);
3325 delete event.hudadd.pos;
3326 delete event.hudadd.name;
3327 delete event.hudadd.scale;
3328 delete event.hudadd.text;
3329 delete event.hudadd.align;
3330 delete event.hudadd.offset;
3331 delete event.hudadd.world_pos;
3332 delete event.hudadd.size;
3333 } else if (event.type == CE_HUDRM) {
3334 HudElement *e = player->removeHud(event.hudrm.id);
3338 } else if (event.type == CE_HUDCHANGE) {
3339 u32 id = event.hudchange.id;
3340 HudElement *e = player->getHud(id);
3343 delete event.hudchange.v3fdata;
3344 delete event.hudchange.v2fdata;
3345 delete event.hudchange.sdata;
3346 delete event.hudchange.v2s32data;
3350 switch (event.hudchange.stat) {
3352 e->pos = *event.hudchange.v2fdata;
3356 e->name = *event.hudchange.sdata;
3359 case HUD_STAT_SCALE:
3360 e->scale = *event.hudchange.v2fdata;
3364 e->text = *event.hudchange.sdata;
3367 case HUD_STAT_NUMBER:
3368 e->number = event.hudchange.data;
3372 e->item = event.hudchange.data;
3376 e->dir = event.hudchange.data;
3379 case HUD_STAT_ALIGN:
3380 e->align = *event.hudchange.v2fdata;
3383 case HUD_STAT_OFFSET:
3384 e->offset = *event.hudchange.v2fdata;
3387 case HUD_STAT_WORLD_POS:
3388 e->world_pos = *event.hudchange.v3fdata;
3392 e->size = *event.hudchange.v2s32data;
3396 delete event.hudchange.v3fdata;
3397 delete event.hudchange.v2fdata;
3398 delete event.hudchange.sdata;
3399 delete event.hudchange.v2s32data;
3400 } else if (event.type == CE_SET_SKY) {
3401 sky->setVisible(false);
3408 // Handle according to type
3409 if (*event.set_sky.type == "regular") {
3410 sky->setVisible(true);
3411 } else if (*event.set_sky.type == "skybox" &&
3412 event.set_sky.params->size() == 6) {
3413 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3414 skybox = smgr->addSkyBoxSceneNode(
3415 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3416 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3417 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3418 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3419 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3420 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3422 // Handle everything else as plain color
3424 if (*event.set_sky.type != "plain")
3425 infostream << "Unknown sky type: "
3426 << (*event.set_sky.type) << std::endl;
3428 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3431 delete event.set_sky.bgcolor;
3432 delete event.set_sky.type;
3433 delete event.set_sky.params;
3434 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3435 bool enable = event.override_day_night_ratio.do_override;
3436 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3437 client->getEnv().setDayNightRatioOverride(enable, value);
3443 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3444 f32 dtime, float time_from_last_punch)
3446 LocalPlayer *player = client->getEnv().getLocalPlayer();
3449 For interaction purposes, get info about the held item
3451 - Is it a usable item?
3452 - Can it point to liquids?
3454 ItemStack playeritem;
3456 InventoryList *mlist = local_inventory->getList("main");
3458 if (mlist && client->getPlayerItem() < mlist->getSize())
3459 playeritem = mlist->getItem(client->getPlayerItem());
3461 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3462 InventoryList *hlist = local_inventory->getList("hand");
3464 playeritem = hlist->getItem(0);
3468 ToolCapabilities playeritem_toolcap =
3469 playeritem.getToolCapabilities(itemdef_manager);
3471 v3s16 old_camera_offset = camera->getOffset();
3473 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3474 GenericCAO *playercao = player->getCAO();
3476 // If playercao not loaded, don't change camera
3477 if (playercao == NULL)
3480 camera->toggleCameraMode();
3482 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3483 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3486 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3487 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3489 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3490 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3492 camera->step(dtime);
3494 v3f camera_position = camera->getPosition();
3495 v3f camera_direction = camera->getDirection();
3496 f32 camera_fov = camera->getFovMax();
3497 v3s16 camera_offset = camera->getOffset();
3499 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3501 if (!flags->disable_camera_update) {
3502 client->getEnv().getClientMap().updateCamera(camera_position,
3503 camera_direction, camera_fov, camera_offset);
3505 if (flags->camera_offset_changed) {
3506 client->updateCameraOffset(camera_offset);
3507 client->getEnv().updateCameraOffset(camera_offset);
3510 clouds->updateCameraOffset(camera_offset);
3516 void Game::updateSound(f32 dtime)
3518 // Update sound listener
3519 v3s16 camera_offset = camera->getOffset();
3520 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3521 v3f(0, 0, 0), // velocity
3522 camera->getDirection(),
3523 camera->getCameraNode()->getUpVector());
3524 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3527 // Update sound maker
3528 soundmaker->step(dtime);
3530 LocalPlayer *player = client->getEnv().getLocalPlayer();
3532 ClientMap &map = client->getEnv().getClientMap();
3533 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3534 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3538 void Game::processPlayerInteraction(GameRunData *runData,
3539 f32 dtime, bool show_hud, bool show_debug)
3541 LocalPlayer *player = client->getEnv().getLocalPlayer();
3543 ItemStack playeritem;
3545 InventoryList *mlist = local_inventory->getList("main");
3547 if (mlist && client->getPlayerItem() < mlist->getSize())
3548 playeritem = mlist->getItem(client->getPlayerItem());
3551 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3552 InventoryList *hlist = local_inventory->getList("hand");
3554 playeritem = hlist->getItem(0);
3556 const ItemDefinition &playeritem_def =
3557 playeritem.getDefinition(itemdef_manager);
3559 v3f player_position = player->getPosition();
3560 v3f camera_position = camera->getPosition();
3561 v3f camera_direction = camera->getDirection();
3562 v3s16 camera_offset = camera->getOffset();
3566 Calculate what block is the crosshair pointing to
3569 f32 d = playeritem_def.range; // max. distance
3570 f32 d_hand = itemdef_manager->get("").range;
3572 if (d < 0 && d_hand >= 0)
3577 core::line3d<f32> shootline;
3579 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3580 shootline = core::line3d<f32>(camera_position,
3581 camera_position + camera_direction * BS * d);
3583 // prevent player pointing anything in front-view
3584 shootline = core::line3d<f32>(camera_position,camera_position);
3587 #ifdef HAVE_TOUCHSCREENGUI
3589 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3590 shootline = g_touchscreengui->getShootline();
3591 shootline.start += intToFloat(camera_offset, BS);
3592 shootline.end += intToFloat(camera_offset, BS);
3597 PointedThing pointed = updatePointedThing(shootline,
3598 playeritem_def.liquids_pointable,
3599 !runData->ldown_for_dig,
3602 runData->selected_object);
3604 if (pointed != runData->pointed_old) {
3605 infostream << "Pointing at " << pointed.dump() << std::endl;
3606 hud->updateSelectionMesh(camera_offset);
3611 - releasing left mouse button
3612 - pointing away from node
3614 if (runData->digging) {
3615 if (getLeftReleased()) {
3616 infostream << "Left button released"
3617 << " (stopped digging)" << std::endl;
3618 runData->digging = false;
3619 } else if (pointed != runData->pointed_old) {
3620 if (pointed.type == POINTEDTHING_NODE
3621 && runData->pointed_old.type == POINTEDTHING_NODE
3622 && pointed.node_undersurface
3623 == runData->pointed_old.node_undersurface) {
3624 // Still pointing to the same node, but a different face.
3627 infostream << "Pointing away from node"
3628 << " (stopped digging)" << std::endl;
3629 runData->digging = false;
3630 hud->updateSelectionMesh(camera_offset);
3634 if (!runData->digging) {
3635 client->interact(1, runData->pointed_old);
3636 client->setCrack(-1, v3s16(0, 0, 0));
3637 runData->dig_time = 0.0;
3641 if (!runData->digging && runData->ldown_for_dig && !isLeftPressed()) {
3642 runData->ldown_for_dig = false;
3645 runData->left_punch = false;
3647 soundmaker->m_player_leftpunch_sound.name = "";
3649 if (isRightPressed())
3650 runData->repeat_rightclick_timer += dtime;
3652 runData->repeat_rightclick_timer = 0;
3654 if (playeritem_def.usable && isLeftPressed()) {
3655 if (getLeftClicked())
3656 client->interact(4, pointed);
3657 } else if (pointed.type == POINTEDTHING_NODE) {
3658 ToolCapabilities playeritem_toolcap =
3659 playeritem.getToolCapabilities(itemdef_manager);
3660 handlePointingAtNode(runData, pointed, playeritem_def,
3661 playeritem_toolcap, dtime);
3662 } else if (pointed.type == POINTEDTHING_OBJECT) {
3663 handlePointingAtObject(runData, pointed, playeritem,
3664 player_position, show_debug);
3665 } else if (isLeftPressed()) {
3666 // When button is held down in air, show continuous animation
3667 runData->left_punch = true;
3668 } else if (getRightClicked()) {
3669 handlePointingAtNothing(runData, playeritem);
3672 runData->pointed_old = pointed;
3674 if (runData->left_punch || getLeftClicked())
3675 camera->setDigging(0); // left click animation
3677 input->resetLeftClicked();
3678 input->resetRightClicked();
3680 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3681 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3683 input->resetLeftReleased();
3684 input->resetRightReleased();
3686 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3687 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3691 PointedThing Game::updatePointedThing(
3692 const core::line3d<f32> &shootline,
3693 bool liquids_pointable,
3694 bool look_for_object,
3695 const v3s16 &camera_offset,
3696 ClientActiveObject *&selected_object)
3698 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3699 selectionboxes->clear();
3700 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3701 static const bool show_entity_selectionbox = g_settings->getBool(
3702 "show_entity_selectionbox");
3704 ClientMap &map = client->getEnv().getClientMap();
3705 INodeDefManager *nodedef=client->getNodeDefManager();
3707 selected_object = NULL;
3709 PointedThing result=client->getEnv().getPointedThing(
3710 shootline, liquids_pointable, look_for_object);
3711 if (result.type == POINTEDTHING_OBJECT) {
3712 selected_object = client->getEnv().getActiveObject(result.object_id);
3713 if (show_entity_selectionbox && selected_object->doShowSelectionBox()) {
3714 aabb3f *selection_box = selected_object->getSelectionBox();
3716 // Box should exist because object was
3717 // returned in the first place
3719 assert(selection_box);
3721 v3f pos = selected_object->getPosition();
3722 selectionboxes->push_back(aabb3f(
3723 selection_box->MinEdge, selection_box->MaxEdge));
3724 selectionboxes->push_back(
3725 aabb3f(selection_box->MinEdge, selection_box->MaxEdge));
3726 hud->setSelectionPos(pos, camera_offset);
3728 } else if (result.type == POINTEDTHING_NODE) {
3729 // Update selection boxes
3730 MapNode n = map.getNodeNoEx(result.node_undersurface);
3731 std::vector<aabb3f> boxes;
3732 n.getSelectionBoxes(nodedef, &boxes,
3733 n.getNeighbors(result.node_undersurface, &map));
3736 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3737 i != boxes.end(); ++i) {
3739 box.MinEdge -= v3f(d, d, d);
3740 box.MaxEdge += v3f(d, d, d);
3741 selectionboxes->push_back(box);
3743 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3745 hud->setSelectedFaceNormal(v3f(
3746 result.intersection_normal.X,
3747 result.intersection_normal.Y,
3748 result.intersection_normal.Z));
3751 // Update selection mesh light level and vertex colors
3752 if (selectionboxes->size() > 0) {
3753 v3f pf = hud->getSelectionPos();
3754 v3s16 p = floatToInt(pf, BS);
3756 // Get selection mesh light level
3757 MapNode n = map.getNodeNoEx(p);
3758 u16 node_light = getInteriorLight(n, -1, nodedef);
3759 u16 light_level = node_light;
3761 for (u8 i = 0; i < 6; i++) {
3762 n = map.getNodeNoEx(p + g_6dirs[i]);
3763 node_light = getInteriorLight(n, -1, nodedef);
3764 if (node_light > light_level)
3765 light_level = node_light;
3768 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3770 final_color_blend(&c, light_level, daynight_ratio);
3772 // Modify final color a bit with time
3773 u32 timer = porting::getTimeMs() % 5000;
3774 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3775 float sin_r = 0.08 * sin(timerf);
3776 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3777 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3779 core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3781 core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3783 core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3785 // Set mesh final color
3786 hud->setSelectionMeshColor(c);
3792 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3794 infostream << "Right Clicked in Air" << std::endl;
3795 PointedThing fauxPointed;
3796 fauxPointed.type = POINTEDTHING_NOTHING;
3797 client->interact(5, fauxPointed);
3801 void Game::handlePointingAtNode(GameRunData *runData,
3802 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3803 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3805 v3s16 nodepos = pointed.node_undersurface;
3806 v3s16 neighbourpos = pointed.node_abovesurface;
3809 Check information text of node
3812 ClientMap &map = client->getEnv().getClientMap();
3813 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3816 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3818 MapNode n = map.getNodeNoEx(nodepos);
3820 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3821 infotext = L"Unknown node: ";
3822 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3826 if (runData->nodig_delay_timer <= 0.0 && isLeftPressed()
3827 && client->checkPrivilege("interact")) {
3828 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3831 if ((getRightClicked() ||
3832 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3833 client->checkPrivilege("interact")) {
3834 runData->repeat_rightclick_timer = 0;
3835 infostream << "Ground right-clicked" << std::endl;
3837 if (meta && meta->getString("formspec") != "" && !random_input
3838 && !isKeyDown(KeyType::SNEAK)) {
3839 infostream << "Launching custom inventory view" << std::endl;
3841 InventoryLocation inventoryloc;
3842 inventoryloc.setNodeMeta(nodepos);
3844 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3845 &client->getEnv().getClientMap(), nodepos);
3846 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3848 create_formspec_menu(¤t_formspec, client,
3849 device, &input->joystick, fs_src, txt_dst);
3852 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3854 // Report right click to server
3856 camera->setDigging(1); // right click animation (always shown for feedback)
3858 // If the wielded item has node placement prediction,
3860 bool placed = nodePlacementPrediction(*client,
3862 nodepos, neighbourpos);
3866 client->interact(3, pointed);
3868 soundmaker->m_player_rightpunch_sound =
3869 playeritem_def.sound_place;
3871 soundmaker->m_player_rightpunch_sound =
3874 if (playeritem_def.node_placement_prediction == "" ||
3875 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3876 client->interact(3, pointed); // Report to server
3878 soundmaker->m_player_rightpunch_sound =
3879 playeritem_def.sound_place_failed;
3887 void Game::handlePointingAtObject(GameRunData *runData,
3888 const PointedThing &pointed,
3889 const ItemStack &playeritem,
3890 const v3f &player_position,
3893 infotext = unescape_enriched(
3894 utf8_to_wide(runData->selected_object->infoText()));
3897 if (infotext != L"") {
3900 infotext += unescape_enriched(utf8_to_wide(
3901 runData->selected_object->debugInfoText()));
3904 if (isLeftPressed()) {
3905 bool do_punch = false;
3906 bool do_punch_damage = false;
3908 if (runData->object_hit_delay_timer <= 0.0) {
3910 do_punch_damage = true;
3911 runData->object_hit_delay_timer = object_hit_delay;
3914 if (getLeftClicked())
3918 infostream << "Left-clicked object" << std::endl;
3919 runData->left_punch = true;
3922 if (do_punch_damage) {
3923 // Report direct punch
3924 v3f objpos = runData->selected_object->getPosition();
3925 v3f dir = (objpos - player_position).normalize();
3927 bool disable_send = runData->selected_object->directReportPunch(
3928 dir, &playeritem, runData->time_from_last_punch);
3929 runData->time_from_last_punch = 0;
3932 client->interact(0, pointed);
3934 } else if (getRightClicked()) {
3935 infostream << "Right-clicked object" << std::endl;
3936 client->interact(3, pointed); // place
3941 void Game::handleDigging(GameRunData *runData,
3942 const PointedThing &pointed, const v3s16 &nodepos,
3943 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3945 if (!runData->digging) {
3946 infostream << "Started digging" << std::endl;
3947 client->interact(0, pointed);
3948 runData->digging = true;
3949 runData->ldown_for_dig = true;
3952 LocalPlayer *player = client->getEnv().getLocalPlayer();
3953 ClientMap &map = client->getEnv().getClientMap();
3954 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3956 // NOTE: Similar piece of code exists on the server side for
3958 // Get digging parameters
3959 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3960 &playeritem_toolcap);
3962 // If can't dig, try hand
3963 if (!params.diggable) {
3964 const ItemDefinition &hand = itemdef_manager->get("");
3965 const ToolCapabilities *tp = hand.tool_capabilities;
3968 params = getDigParams(nodedef_manager->get(n).groups, tp);
3971 if (params.diggable == false) {
3972 // I guess nobody will wait for this long
3973 runData->dig_time_complete = 10000000.0;
3975 runData->dig_time_complete = params.time;
3977 if (m_cache_enable_particles) {
3978 const ContentFeatures &features =
3979 client->getNodeDefManager()->get(n);
3980 client->getParticleManager()->addPunchingParticles(client, smgr,
3981 player, nodepos, n, features);
3985 if (runData->dig_time_complete >= 0.001) {
3986 runData->dig_index = (float)crack_animation_length
3988 / runData->dig_time_complete;
3990 // This is for torches
3991 runData->dig_index = crack_animation_length;
3994 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3996 if (sound_dig.exists() && params.diggable) {
3997 if (sound_dig.name == "__group") {
3998 if (params.main_group != "") {
3999 soundmaker->m_player_leftpunch_sound.gain = 0.5;
4000 soundmaker->m_player_leftpunch_sound.name =
4001 std::string("default_dig_") +
4005 soundmaker->m_player_leftpunch_sound = sound_dig;
4009 // Don't show cracks if not diggable
4010 if (runData->dig_time_complete >= 100000.0) {
4011 } else if (runData->dig_index < crack_animation_length) {
4012 //TimeTaker timer("client.setTempMod");
4013 //infostream<<"dig_index="<<dig_index<<std::endl;
4014 client->setCrack(runData->dig_index, nodepos);
4016 infostream << "Digging completed" << std::endl;
4017 client->interact(2, pointed);
4018 client->setCrack(-1, v3s16(0, 0, 0));
4019 bool is_valid_position;
4020 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
4021 if (is_valid_position)
4022 client->removeNode(nodepos);
4024 if (m_cache_enable_particles) {
4025 const ContentFeatures &features =
4026 client->getNodeDefManager()->get(wasnode);
4027 client->getParticleManager()->addDiggingParticles(client, smgr,
4028 player, nodepos, wasnode, features);
4031 runData->dig_time = 0;
4032 runData->digging = false;
4034 runData->nodig_delay_timer =
4035 runData->dig_time_complete / (float)crack_animation_length;
4037 // We don't want a corresponding delay to
4038 // very time consuming nodes
4039 if (runData->nodig_delay_timer > 0.3)
4040 runData->nodig_delay_timer = 0.3;
4042 // We want a slight delay to very little
4043 // time consuming nodes
4044 const float mindelay = 0.15;
4046 if (runData->nodig_delay_timer < mindelay)
4047 runData->nodig_delay_timer = mindelay;
4049 // Send event to trigger sound
4050 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4051 client->event()->put(e);
4054 if (runData->dig_time_complete < 100000.0) {
4055 runData->dig_time += dtime;
4057 runData->dig_time = 0;
4058 client->setCrack(-1, nodepos);
4061 camera->setDigging(0); // left click animation
4065 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
4066 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
4067 const CameraOrientation &cam)
4069 LocalPlayer *player = client->getEnv().getLocalPlayer();
4075 if (draw_control->range_all) {
4076 runData->fog_range = 100000 * BS;
4078 runData->fog_range = draw_control->wanted_range * BS;
4082 Calculate general brightness
4084 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4085 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4086 float direct_brightness;
4089 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4090 direct_brightness = time_brightness;
4091 sunlight_seen = true;
4093 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4094 float old_brightness = sky->getBrightness();
4095 direct_brightness = client->getEnv().getClientMap()
4096 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
4097 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4101 float time_of_day = runData->time_of_day;
4102 float time_of_day_smooth = runData->time_of_day_smooth;
4104 time_of_day = client->getEnv().getTimeOfDayF();
4106 const float maxsm = 0.05;
4107 const float todsm = 0.05;
4109 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4110 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4111 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4112 time_of_day_smooth = time_of_day;
4114 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4115 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4116 + (time_of_day + 1.0) * todsm;
4118 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4119 + time_of_day * todsm;
4121 runData->time_of_day = time_of_day;
4122 runData->time_of_day_smooth = time_of_day_smooth;
4124 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4125 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4126 player->getPitch());
4132 v3f player_position = player->getPosition();
4133 if (sky->getCloudsVisible()) {
4134 clouds->setVisible(true);
4135 clouds->step(dtime);
4136 clouds->update(v2f(player_position.X, player_position.Z),
4137 sky->getCloudColor());
4139 clouds->setVisible(false);
4146 client->getParticleManager()->step(dtime);
4152 if (m_cache_enable_fog && !flags.force_fog_off) {
4155 video::EFT_FOG_LINEAR,
4156 runData->fog_range * m_cache_fog_start,
4157 runData->fog_range * 1.0,
4165 video::EFT_FOG_LINEAR,
4175 Get chat messages from client
4178 v2u32 screensize = driver->getScreenSize();
4180 updateChat(*client, dtime, flags.show_debug, screensize,
4181 flags.show_chat, runData->profiler_current_page,
4182 *chat_backend, guitext_chat);
4188 if (client->getPlayerItem() != runData->new_playeritem)
4189 client->selectPlayerItem(runData->new_playeritem);
4191 // Update local inventory if it has changed
4192 if (client->getLocalInventoryUpdated()) {
4193 //infostream<<"Updating local inventory"<<std::endl;
4194 client->getLocalInventory(*local_inventory);
4195 runData->update_wielded_item_trigger = true;
4198 if (runData->update_wielded_item_trigger) {
4199 // Update wielded tool
4200 InventoryList *mlist = local_inventory->getList("main");
4202 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4203 ItemStack item = mlist->getItem(client->getPlayerItem());
4204 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4205 InventoryList *hlist = local_inventory->getList("hand");
4207 item = hlist->getItem(0);
4209 camera->wield(item);
4212 runData->update_wielded_item_trigger = false;
4216 Update block draw list every 200ms or when camera direction has
4219 runData->update_draw_list_timer += dtime;
4221 v3f camera_direction = camera->getDirection();
4222 if (runData->update_draw_list_timer >= 0.2
4223 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4224 || flags.camera_offset_changed) {
4225 runData->update_draw_list_timer = 0;
4226 client->getEnv().getClientMap().updateDrawList(driver);
4227 runData->update_draw_list_last_cam_dir = camera_direction;
4230 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4233 make sure menu is on top
4234 1. Delete formspec menu reference if menu was removed
4235 2. Else, make sure formspec menu is on top
4237 if (current_formspec) {
4238 if (current_formspec->getReferenceCount() == 1) {
4239 current_formspec->drop();
4240 current_formspec = NULL;
4241 } else if (!noMenuActive()) {
4242 guiroot->bringToFront(current_formspec);
4250 video::SColor skycolor = sky->getSkyColor();
4252 TimeTaker tt_draw("mainloop: draw");
4254 TimeTaker timer("beginScene");
4255 driver->beginScene(true, true, skycolor);
4256 stats->beginscenetime = timer.stop(true);
4259 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4260 guienv, screensize, skycolor, flags.show_hud,
4261 flags.show_minimap);
4266 if (flags.show_profiler_graph)
4267 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4272 if (runData->damage_flash > 0.0) {
4273 video::SColor color(runData->damage_flash, 180, 0, 0);
4274 driver->draw2DRectangle(color,
4275 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4278 runData->damage_flash -= 100.0 * dtime;
4284 if (player->hurt_tilt_timer > 0.0) {
4285 player->hurt_tilt_timer -= dtime * 5;
4287 if (player->hurt_tilt_timer < 0)
4288 player->hurt_tilt_strength = 0;
4292 Update minimap pos and rotation
4294 if (flags.show_minimap && flags.show_hud) {
4295 mapper->setPos(floatToInt(player->getPosition(), BS));
4296 mapper->setAngle(player->getYaw());
4303 TimeTaker timer("endScene");
4305 stats->endscenetime = timer.stop(true);
4308 stats->drawtime = tt_draw.stop(true);
4309 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4313 inline static const char *yawToDirectionString(int yaw)
4315 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4317 yaw = wrapDegrees_0_360(yaw);
4318 yaw = (yaw + 45) % 360 / 90;
4320 return direction[yaw];
4324 void Game::updateGui(float *statustext_time, const RunStats &stats,
4325 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4326 const CameraOrientation &cam)
4328 v2u32 screensize = driver->getScreenSize();
4329 LocalPlayer *player = client->getEnv().getLocalPlayer();
4330 v3f player_position = player->getPosition();
4332 if (flags.show_debug) {
4333 static float drawtime_avg = 0;
4334 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4336 u16 fps = 1.0 / stats.dtime_jitter.avg;
4337 //s32 fps = driver->getFPS();
4339 std::ostringstream os(std::ios_base::binary);
4341 << PROJECT_NAME_C " " << g_version_hash
4343 << " (R: range_all=" << draw_control->range_all << ")"
4344 << std::setprecision(0)
4345 << " drawtime = " << drawtime_avg
4346 << std::setprecision(1)
4347 << ", dtime_jitter = "
4348 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4349 << std::setprecision(1)
4350 << ", v_range = " << draw_control->wanted_range
4351 << std::setprecision(3)
4352 << ", RTT = " << client->getRTT();
4353 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4354 guitext->setVisible(true);
4356 guitext->setVisible(false);
4359 if (guitext->isVisible()) {
4360 core::rect<s32> rect(
4362 screensize.X, 5 + g_fontengine->getTextHeight()
4364 guitext->setRelativePosition(rect);
4367 if (flags.show_debug) {
4368 std::ostringstream os(std::ios_base::binary);
4369 os << std::setprecision(1) << std::fixed
4370 << "(" << (player_position.X / BS)
4371 << ", " << (player_position.Y / BS)
4372 << ", " << (player_position.Z / BS)
4373 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4374 << " " << yawToDirectionString(cam.camera_yaw)
4375 << ") (seed = " << ((u64)client->getMapSeed())
4378 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4379 ClientMap &map = client->getEnv().getClientMap();
4380 const INodeDefManager *nodedef = client->getNodeDefManager();
4381 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4382 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4383 const ContentFeatures &features = nodedef->get(n);
4384 os << " (pointing_at = " << nodedef->get(n).name
4385 << " - " << features.tiledef[0].name.c_str()
4390 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4391 guitext2->setVisible(true);
4393 core::rect<s32> rect(
4394 5, 5 + g_fontengine->getTextHeight(),
4395 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4397 guitext2->setRelativePosition(rect);
4399 guitext2->setVisible(false);
4402 setStaticText(guitext_info, infotext.c_str());
4403 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4405 float statustext_time_max = 1.5;
4407 if (!statustext.empty()) {
4408 *statustext_time += dtime;
4410 if (*statustext_time >= statustext_time_max) {
4412 *statustext_time = 0;
4416 setStaticText(guitext_status, statustext.c_str());
4417 guitext_status->setVisible(!statustext.empty());
4419 if (!statustext.empty()) {
4420 s32 status_width = guitext_status->getTextWidth();
4421 s32 status_height = guitext_status->getTextHeight();
4422 s32 status_y = screensize.Y - 150;
4423 s32 status_x = (screensize.X - status_width) / 2;
4424 core::rect<s32> rect(
4425 status_x , status_y - status_height,
4426 status_x + status_width, status_y
4428 guitext_status->setRelativePosition(rect);
4431 video::SColor initial_color(255, 0, 0, 0);
4433 if (guienv->getSkin())
4434 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4436 video::SColor final_color = initial_color;
4437 final_color.setAlpha(0);
4438 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4439 initial_color, final_color,
4440 pow(*statustext_time / statustext_time_max, 2.0f));
4441 guitext_status->setOverrideColor(fade_color);
4442 guitext_status->enableOverrideColor(true);
4447 /* Log times and stuff for visualization */
4448 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4450 Profiler::GraphValues values;
4451 g_profiler->graphGet(values);
4457 /****************************************************************************
4459 ****************************************************************************/
4461 /* On some computers framerate doesn't seem to be automatically limited
4463 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4465 // not using getRealTime is necessary for wine
4466 device->getTimer()->tick(); // Maker sure device time is up-to-date
4467 u32 time = device->getTimer()->getTime();
4468 u32 last_time = fps_timings->last_time;
4470 if (time > last_time) // Make sure time hasn't overflowed
4471 fps_timings->busy_time = time - last_time;
4473 fps_timings->busy_time = 0;
4475 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4476 ? g_settings->getFloat("pause_fps_max")
4477 : g_settings->getFloat("fps_max"));
4479 if (fps_timings->busy_time < frametime_min) {
4480 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4481 device->sleep(fps_timings->sleep_time);
4483 fps_timings->sleep_time = 0;
4486 /* Get the new value of the device timer. Note that device->sleep() may
4487 * not sleep for the entire requested time as sleep may be interrupted and
4488 * therefore it is arguably more accurate to get the new time from the
4489 * device rather than calculating it by adding sleep_time to time.
4492 device->getTimer()->tick(); // Update device timer
4493 time = device->getTimer()->getTime();
4495 if (time > last_time) // Make sure last_time hasn't overflowed
4496 *dtime = (time - last_time) / 1000.0;
4500 fps_timings->last_time = time;
4503 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4504 // pass a copy of it to this function
4505 // Note: \p msg must be allocated using new (not malloc())
4506 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4507 int percent, bool draw_clouds)
4509 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4513 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4515 ((Game *)data)->readSettings();
4518 void Game::readSettings()
4520 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4521 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4522 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4523 m_cache_enable_particles = g_settings->getBool("enable_particles");
4524 m_cache_enable_fog = g_settings->getBool("enable_fog");
4525 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4526 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4527 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4529 m_cache_enable_noclip = g_settings->getBool("noclip");
4530 m_cache_enable_free_move = g_settings->getBool("free_move");
4532 m_cache_fog_start = g_settings->getFloat("fog_start");
4534 m_cache_cam_smoothing = 0;
4535 if (g_settings->getBool("cinematic"))
4536 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4538 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4540 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4541 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4542 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4546 /****************************************************************************/
4547 /****************************************************************************
4549 ****************************************************************************/
4550 /****************************************************************************/
4552 void Game::extendedResourceCleanup()
4554 // Extended resource accounting
4555 infostream << "Irrlicht resources after cleanup:" << std::endl;
4556 infostream << "\tRemaining meshes : "
4557 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4558 infostream << "\tRemaining textures : "
4559 << driver->getTextureCount() << std::endl;
4561 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4562 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4563 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4567 clearTextureNameCache();
4568 infostream << "\tRemaining materials: "
4569 << driver-> getMaterialRendererCount()
4570 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4574 /****************************************************************************/
4575 /****************************************************************************
4576 extern function for launching the game
4577 ****************************************************************************/
4578 /****************************************************************************/
4580 void the_game(bool *kill,
4582 InputHandler *input,
4583 IrrlichtDevice *device,
4585 const std::string &map_dir,
4586 const std::string &playername,
4587 const std::string &password,
4588 const std::string &address, // If empty local server is created
4591 std::string &error_message,
4592 ChatBackend &chat_backend,
4593 bool *reconnect_requested,
4594 const SubgameSpec &gamespec, // Used for local game
4595 bool simple_singleplayer_mode)
4599 /* Make a copy of the server address because if a local singleplayer server
4600 * is created then this is updated and we don't want to change the value
4601 * passed to us by the calling function
4603 std::string server_address = address;
4607 if (game.startup(kill, random_input, input, device, map_dir,
4608 playername, password, &server_address, port, error_message,
4609 reconnect_requested, &chat_backend, gamespec,
4610 simple_singleplayer_mode)) {
4615 } catch (SerializationError &e) {
4616 error_message = std::string("A serialization error occurred:\n")
4617 + e.what() + "\n\nThe server is probably "
4618 " running a different version of " PROJECT_NAME_C ".";
4619 errorstream << error_message << std::endl;
4620 } catch (ServerError &e) {
4621 error_message = e.what();
4622 errorstream << "ServerError: " << error_message << std::endl;
4623 } catch (ModError &e) {
4624 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4625 errorstream << "ModError: " << error_message << std::endl;