3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include "client/tile.h" // For TextureSource
26 #include "client/keys.h"
27 #include "client/joystick_controller.h"
28 #include "clientmap.h"
31 #include "content_cao.h"
32 #include "drawscene.h"
33 #include "event_manager.h"
34 #include "fontengine.h"
39 #include "guiChatConsole.h"
40 #include "guiFormSpecMenu.h"
41 #include "guiKeyChangeMenu.h"
42 #include "guiPasswordChange.h"
43 #include "guiVolumeChange.h"
44 #include "mainmenumanager.h"
46 #include "nodedef.h" // Needed for determining pointing to nodes
47 #include "nodemetadata.h"
48 #include "particles.h"
50 #include "quicktune_shortcutter.h"
53 #include "shader.h" // For ShaderSource
57 #include "util/directiontables.h"
58 #include "util/pointedthing.h"
59 #include "irrlicht_changes/static_text.h"
62 #include "mapblock_mesh.h"
63 #include "script/scripting_client.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
84 TextDestNodeMetadata(v3s16 p, Client *client)
89 // This is deprecated I guess? -celeron55
90 void gotText(const std::wstring &text)
92 std::string ntext = wide_to_utf8(text);
93 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
94 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
96 fields["text"] = ntext;
97 m_client->sendNodemetaFields(m_p, "", fields);
99 void gotText(const StringMap &fields)
101 m_client->sendNodemetaFields(m_p, "", fields);
108 struct TextDestPlayerInventory : public TextDest
110 TextDestPlayerInventory(Client *client)
115 TextDestPlayerInventory(Client *client, const std::string &formname)
118 m_formname = formname;
120 void gotText(const StringMap &fields)
122 m_client->sendInventoryFields(m_formname, fields);
128 struct LocalFormspecHandler : public TextDest
130 LocalFormspecHandler(const std::string &formname):
133 m_formname = formname;
136 LocalFormspecHandler(const std::string &formname, Client *client):
139 m_formname = formname;
142 void gotText(const StringMap &fields)
144 if (m_formname == "MT_PAUSE_MENU") {
145 if (fields.find("btn_sound") != fields.end()) {
146 g_gamecallback->changeVolume();
150 if (fields.find("btn_key_config") != fields.end()) {
151 g_gamecallback->keyConfig();
155 if (fields.find("btn_exit_menu") != fields.end()) {
156 g_gamecallback->disconnect();
160 if (fields.find("btn_exit_os") != fields.end()) {
161 g_gamecallback->exitToOS();
165 if (fields.find("btn_change_password") != fields.end()) {
166 g_gamecallback->changePassword();
170 if (fields.find("quit") != fields.end()) {
174 if (fields.find("btn_continue") != fields.end()) {
179 // Don't disable this part when modding is disabled, it's used in builtin
180 m_client->getScript()->on_formspec_input(m_formname, fields);
186 /* Form update callback */
188 class NodeMetadataFormSource: public IFormSource
191 NodeMetadataFormSource(ClientMap *map, v3s16 p):
196 std::string getForm()
198 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
203 return meta->getString("formspec");
206 virtual std::string resolveText(const std::string &str)
208 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
213 return meta->resolveString(str);
220 class PlayerInventoryFormSource: public IFormSource
223 PlayerInventoryFormSource(Client *client):
227 std::string getForm()
229 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
230 return player->inventory_formspec;
236 /* Profiler display */
238 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
239 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
241 if (show_profiler == 0) {
242 guitext_profiler->setVisible(false);
245 std::ostringstream os(std::ios_base::binary);
246 g_profiler->printPage(os, show_profiler, show_profiler_max);
247 std::wstring text = utf8_to_wide(os.str());
248 setStaticText(guitext_profiler, text.c_str());
249 guitext_profiler->setVisible(true);
251 s32 w = fe->getTextWidth(text.c_str());
256 unsigned text_height = fe->getTextHeight();
258 core::position2di upper_left, lower_right;
261 upper_left.Y = (text_height + 5) * 2;
262 lower_right.X = 12 + w;
263 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
265 if (lower_right.Y > screen_height * 2 / 3)
266 lower_right.Y = screen_height * 2 / 3;
268 core::rect<s32> rect(upper_left, lower_right);
270 guitext_profiler->setRelativePosition(rect);
271 guitext_profiler->setVisible(true);
279 Profiler::GraphValues values;
285 Meta(float initial = 0,
286 video::SColor color = video::SColor(255, 255, 255, 255)):
292 std::deque<Piece> m_log;
300 void put(const Profiler::GraphValues &values)
303 piece.values = values;
304 m_log.push_back(piece);
306 while (m_log.size() > m_log_max_size)
307 m_log.erase(m_log.begin());
310 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
311 gui::IGUIFont *font) const
313 // Do *not* use UNORDERED_MAP here as the order needs
314 // to be the same for each call to prevent flickering
315 std::map<std::string, Meta> m_meta;
317 for (std::deque<Piece>::const_iterator k = m_log.begin();
318 k != m_log.end(); ++k) {
319 const Piece &piece = *k;
321 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
322 i != piece.values.end(); ++i) {
323 const std::string &id = i->first;
324 const float &value = i->second;
325 std::map<std::string, Meta>::iterator j = m_meta.find(id);
327 if (j == m_meta.end()) {
328 m_meta[id] = Meta(value);
332 if (value < j->second.min)
333 j->second.min = value;
335 if (value > j->second.max)
336 j->second.max = value;
341 static const video::SColor usable_colors[] = {
342 video::SColor(255, 255, 100, 100),
343 video::SColor(255, 90, 225, 90),
344 video::SColor(255, 100, 100, 255),
345 video::SColor(255, 255, 150, 50),
346 video::SColor(255, 220, 220, 100)
348 static const u32 usable_colors_count =
349 sizeof(usable_colors) / sizeof(*usable_colors);
350 u32 next_color_i = 0;
352 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
353 i != m_meta.end(); ++i) {
354 Meta &meta = i->second;
355 video::SColor color(255, 200, 200, 200);
357 if (next_color_i < usable_colors_count)
358 color = usable_colors[next_color_i++];
364 s32 textx = x_left + m_log_max_size + 15;
365 s32 textx2 = textx + 200 - 15;
368 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
369 i != m_meta.end(); ++i) {
370 const std::string &id = i->first;
371 const Meta &meta = i->second;
373 s32 y = y_bottom - meta_i * 50;
374 float show_min = meta.min;
375 float show_max = meta.max;
377 if (show_min >= -0.0001 && show_max >= -0.0001) {
378 if (show_min <= show_max * 0.5)
384 snprintf(buf, 10, "%.3g", show_max);
385 font->draw(utf8_to_wide(buf).c_str(),
386 core::rect<s32>(textx, y - graphh,
387 textx2, y - graphh + texth),
389 snprintf(buf, 10, "%.3g", show_min);
390 font->draw(utf8_to_wide(buf).c_str(),
391 core::rect<s32>(textx, y - texth,
394 font->draw(utf8_to_wide(id).c_str(),
395 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
396 textx2, y - graphh / 2 + texth / 2),
399 s32 graph1h = graphh;
400 bool relativegraph = (show_min != 0 && show_min != show_max);
401 float lastscaledvalue = 0.0;
402 bool lastscaledvalue_exists = false;
404 for (std::deque<Piece>::const_iterator j = m_log.begin();
405 j != m_log.end(); ++j) {
406 const Piece &piece = *j;
408 bool value_exists = false;
409 Profiler::GraphValues::const_iterator k =
410 piece.values.find(id);
412 if (k != piece.values.end()) {
419 lastscaledvalue_exists = false;
423 float scaledvalue = 1.0;
425 if (show_max != show_min)
426 scaledvalue = (value - show_min) / (show_max - show_min);
428 if (scaledvalue == 1.0 && value == 0) {
430 lastscaledvalue_exists = false;
435 if (lastscaledvalue_exists) {
436 s32 ivalue1 = lastscaledvalue * graph1h;
437 s32 ivalue2 = scaledvalue * graph1h;
438 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
439 v2s32(x, graph1y - ivalue2), meta.color);
442 lastscaledvalue = scaledvalue;
443 lastscaledvalue_exists = true;
445 s32 ivalue = scaledvalue * graph1h;
446 driver->draw2DLine(v2s32(x, graph1y),
447 v2s32(x, graph1y - ivalue), meta.color);
458 class NodeDugEvent: public MtEvent
464 NodeDugEvent(v3s16 p, MapNode n):
468 const char *getType() const
476 ISoundManager *m_sound;
477 INodeDefManager *m_ndef;
479 bool makes_footstep_sound;
480 float m_player_step_timer;
482 SimpleSoundSpec m_player_step_sound;
483 SimpleSoundSpec m_player_leftpunch_sound;
484 SimpleSoundSpec m_player_rightpunch_sound;
486 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
489 makes_footstep_sound(true),
490 m_player_step_timer(0)
494 void playPlayerStep()
496 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
497 m_player_step_timer = 0.03;
498 if (makes_footstep_sound)
499 m_sound->playSound(m_player_step_sound, false);
503 static void viewBobbingStep(MtEvent *e, void *data)
505 SoundMaker *sm = (SoundMaker *)data;
506 sm->playPlayerStep();
509 static void playerRegainGround(MtEvent *e, void *data)
511 SoundMaker *sm = (SoundMaker *)data;
512 sm->playPlayerStep();
515 static void playerJump(MtEvent *e, void *data)
517 //SoundMaker *sm = (SoundMaker*)data;
520 static void cameraPunchLeft(MtEvent *e, void *data)
522 SoundMaker *sm = (SoundMaker *)data;
523 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
526 static void cameraPunchRight(MtEvent *e, void *data)
528 SoundMaker *sm = (SoundMaker *)data;
529 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
532 static void nodeDug(MtEvent *e, void *data)
534 SoundMaker *sm = (SoundMaker *)data;
535 NodeDugEvent *nde = (NodeDugEvent *)e;
536 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
539 static void playerDamage(MtEvent *e, void *data)
541 SoundMaker *sm = (SoundMaker *)data;
542 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
545 static void playerFallingDamage(MtEvent *e, void *data)
547 SoundMaker *sm = (SoundMaker *)data;
548 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
551 void registerReceiver(MtEventManager *mgr)
553 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
554 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
555 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
556 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
557 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
558 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
559 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
560 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
563 void step(float dtime)
565 m_player_step_timer -= dtime;
569 // Locally stored sounds don't need to be preloaded because of this
570 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
572 std::set<std::string> m_fetched;
574 void paths_insert(std::set<std::string> &dst_paths,
575 const std::string &base,
576 const std::string &name)
578 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
579 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
580 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
581 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
582 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
583 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
584 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
585 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
586 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
587 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
588 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
591 void fetchSounds(const std::string &name,
592 std::set<std::string> &dst_paths,
593 std::set<std::string> &dst_datas)
595 if (m_fetched.count(name))
598 m_fetched.insert(name);
600 paths_insert(dst_paths, porting::path_share, name);
601 paths_insert(dst_paths, porting::path_user, name);
606 // before 1.8 there isn't a "integer interface", only float
607 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
608 typedef f32 SamplerLayer_t;
610 typedef s32 SamplerLayer_t;
614 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
617 bool *m_force_fog_off;
620 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
621 CachedPixelShaderSetting<float> m_fog_distance;
622 CachedVertexShaderSetting<float> m_animation_timer_vertex;
623 CachedPixelShaderSetting<float> m_animation_timer_pixel;
624 CachedPixelShaderSetting<float, 3> m_day_light;
625 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
626 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
627 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
628 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
629 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
630 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
634 void onSettingsChange(const std::string &name)
636 if (name == "enable_fog")
637 m_fog_enabled = g_settings->getBool("enable_fog");
640 static void settingsCallback(const std::string &name, void *userdata)
642 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
645 void setSky(Sky *sky) { m_sky = sky; }
647 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
648 f32 *fog_range, Client *client) :
650 m_force_fog_off(force_fog_off),
651 m_fog_range(fog_range),
652 m_sky_bg_color("skyBgColor"),
653 m_fog_distance("fogDistance"),
654 m_animation_timer_vertex("animationTimer"),
655 m_animation_timer_pixel("animationTimer"),
656 m_day_light("dayLight"),
657 m_eye_position_pixel("eyePosition"),
658 m_eye_position_vertex("eyePosition"),
659 m_minimap_yaw("yawVec"),
660 m_base_texture("baseTexture"),
661 m_normal_texture("normalTexture"),
662 m_texture_flags("textureFlags"),
665 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
666 m_fog_enabled = g_settings->getBool("enable_fog");
669 ~GameGlobalShaderConstantSetter()
671 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
674 virtual void onSetConstants(video::IMaterialRendererServices *services,
681 video::SColor bgcolor = m_sky->getBgColor();
682 video::SColorf bgcolorf(bgcolor);
683 float bgcolorfa[4] = {
689 m_sky_bg_color.set(bgcolorfa, services);
692 float fog_distance = 10000 * BS;
694 if (m_fog_enabled && !*m_force_fog_off)
695 fog_distance = *m_fog_range;
697 m_fog_distance.set(&fog_distance, services);
699 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
700 video::SColorf sunlight;
701 get_sunlight_color(&sunlight, daynight_ratio);
706 m_day_light.set(dnc, services);
708 u32 animation_timer = porting::getTimeMs() % 100000;
709 float animation_timer_f = (float)animation_timer / 100000.f;
710 m_animation_timer_vertex.set(&animation_timer_f, services);
711 m_animation_timer_pixel.set(&animation_timer_f, services);
713 float eye_position_array[3];
714 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
715 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
716 eye_position_array[0] = epos.X;
717 eye_position_array[1] = epos.Y;
718 eye_position_array[2] = epos.Z;
720 epos.getAs3Values(eye_position_array);
722 m_eye_position_pixel.set(eye_position_array, services);
723 m_eye_position_vertex.set(eye_position_array, services);
725 float minimap_yaw_array[3];
726 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
727 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
728 minimap_yaw_array[0] = minimap_yaw.X;
729 minimap_yaw_array[1] = minimap_yaw.Y;
730 minimap_yaw_array[2] = minimap_yaw.Z;
732 minimap_yaw.getAs3Values(minimap_yaw_array);
734 m_minimap_yaw.set(minimap_yaw_array, services);
736 SamplerLayer_t base_tex = 0,
739 m_base_texture.set(&base_tex, services);
740 m_normal_texture.set(&normal_tex, services);
741 m_texture_flags.set(&flags_tex, services);
746 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
749 bool *m_force_fog_off;
752 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
754 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
755 f32 *fog_range, Client *client) :
757 m_force_fog_off(force_fog_off),
758 m_fog_range(fog_range),
762 void setSky(Sky *sky) {
764 for (size_t i = 0; i < created_nosky.size(); ++i) {
765 created_nosky[i]->setSky(m_sky);
767 created_nosky.clear();
770 virtual IShaderConstantSetter* create()
772 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
773 m_sky, m_force_fog_off, m_fog_range, m_client);
775 created_nosky.push_back(scs);
781 bool nodePlacementPrediction(Client &client,
782 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
784 std::string prediction = playeritem_def.node_placement_prediction;
785 INodeDefManager *nodedef = client.ndef();
786 ClientMap &map = client.getEnv().getClientMap();
788 bool is_valid_position;
790 node = map.getNodeNoEx(nodepos, &is_valid_position);
791 if (!is_valid_position)
794 if (prediction != "" && !nodedef->get(node).rightclickable) {
795 verbosestream << "Node placement prediction for "
796 << playeritem_def.name << " is "
797 << prediction << std::endl;
798 v3s16 p = neighbourpos;
800 // Place inside node itself if buildable_to
801 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
802 if (is_valid_position)
804 if (nodedef->get(n_under).buildable_to)
807 node = map.getNodeNoEx(p, &is_valid_position);
808 if (is_valid_position &&!nodedef->get(node).buildable_to)
813 // Find id of predicted node
815 bool found = nodedef->getId(prediction, id);
818 errorstream << "Node placement prediction failed for "
819 << playeritem_def.name << " (places "
821 << ") - Name not known" << std::endl;
825 // Predict param2 for facedir and wallmounted nodes
828 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
829 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED) {
830 v3s16 dir = nodepos - neighbourpos;
832 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
833 param2 = dir.Y < 0 ? 1 : 0;
834 } else if (abs(dir.X) > abs(dir.Z)) {
835 param2 = dir.X < 0 ? 3 : 2;
837 param2 = dir.Z < 0 ? 5 : 4;
841 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR ||
842 nodedef->get(id).param_type_2 == CPT2_COLORED_FACEDIR) {
843 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
845 if (abs(dir.X) > abs(dir.Z)) {
846 param2 = dir.X < 0 ? 3 : 1;
848 param2 = dir.Z < 0 ? 2 : 0;
854 //Check attachment if node is in group attached_node
855 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
856 static v3s16 wallmounted_dirs[8] = {
866 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
867 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED)
868 pp = p + wallmounted_dirs[param2];
870 pp = p + v3s16(0, -1, 0);
872 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
876 // Add node to client map
877 MapNode n(id, 0, param2);
880 LocalPlayer *player = client.getEnv().getLocalPlayer();
882 // Dont place node when player would be inside new node
883 // NOTE: This is to be eventually implemented by a mod as client-side Lua
884 if (!nodedef->get(n).walkable ||
885 g_settings->getBool("enable_build_where_you_stand") ||
886 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
887 (nodedef->get(n).walkable &&
888 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
889 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
891 // This triggers the required mesh update too
892 client.addNode(p, n);
895 } catch (InvalidPositionException &e) {
896 errorstream << "Node placement prediction failed for "
897 << playeritem_def.name << " (places "
899 << ") - Position not loaded" << std::endl;
906 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
907 Client *client, IrrlichtDevice *device, JoystickController *joystick,
908 IFormSource *fs_src, TextDest *txt_dest)
911 if (*cur_formspec == 0) {
912 *cur_formspec = new GUIFormSpecMenu(device, joystick,
913 guiroot, -1, &g_menumgr, client, client->getTextureSource(),
915 (*cur_formspec)->doPause = false;
918 Caution: do not call (*cur_formspec)->drop() here --
919 the reference might outlive the menu, so we will
920 periodically check if *cur_formspec is the only
921 remaining reference (i.e. the menu was removed)
922 and delete it in that case.
926 (*cur_formspec)->setFormSource(fs_src);
927 (*cur_formspec)->setTextDest(txt_dest);
933 #define SIZE_TAG "size[11,5.5]"
935 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
938 /******************************************************************************/
939 static void updateChat(Client &client, f32 dtime, bool show_debug,
940 const v2u32 &screensize, bool show_chat, u32 show_profiler,
941 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
943 // Add chat log output for errors to be shown in chat
944 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
946 // Get new messages from error log buffer
947 while (!chat_log_error_buf.empty()) {
948 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
949 if (!g_settings->getBool("disable_escape_sequences")) {
950 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
952 chat_backend.addMessage(L"", error_message);
955 // Get new messages from client
956 std::wstring message;
958 while (client.getChatMessage(message)) {
959 chat_backend.addUnparsedMessage(message);
962 // Remove old messages
963 chat_backend.step(dtime);
965 // Display all messages in a static text element
966 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
967 EnrichedString recent_chat = chat_backend.getRecentChat();
968 unsigned int line_height = g_fontengine->getLineHeight();
970 setStaticText(guitext_chat, recent_chat);
972 // Update gui element size and position
976 chat_y += 2 * line_height;
978 // first pass to calculate height of text to be set
979 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
980 porting::getWindowSize().X - 20);
981 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
982 guitext_chat->setRelativePosition(rect);
984 //now use real height of text and adjust rect according to this size
985 rect = core::rect<s32>(10, chat_y, width,
986 chat_y + guitext_chat->getTextHeight());
989 guitext_chat->setRelativePosition(rect);
990 // Don't show chat if disabled or empty or profiler is enabled
991 guitext_chat->setVisible(
992 show_chat && recent_chat_count != 0 && !show_profiler);
996 /****************************************************************************
997 Fast key cache for main game loop
998 ****************************************************************************/
1000 /* This is faster than using getKeySetting with the tradeoff that functions
1001 * using it must make sure that it's initialised before using it and there is
1002 * no error handling (for example bounds checking). This is really intended for
1003 * use only in the main running loop of the client (the_game()) where the faster
1004 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1005 * (e.g. formspecs) should continue using getKeySetting().
1013 populate_nonchanging();
1018 // Keys that are not settings dependent
1019 void populate_nonchanging();
1021 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1022 InputHandler *handler;
1025 void KeyCache::populate_nonchanging()
1027 key[KeyType::ESC] = EscapeKey;
1030 void KeyCache::populate()
1032 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1033 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1034 key[KeyType::LEFT] = getKeySetting("keymap_left");
1035 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1036 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1037 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1038 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1040 key[KeyType::AUTORUN] = getKeySetting("keymap_autorun");
1042 key[KeyType::DROP] = getKeySetting("keymap_drop");
1043 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1044 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1045 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1046 key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
1047 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1048 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1049 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1050 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1051 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1052 key[KeyType::HOTBAR_PREV] = getKeySetting("keymap_hotbar_previous");
1053 key[KeyType::HOTBAR_NEXT] = getKeySetting("keymap_hotbar_next");
1054 key[KeyType::MUTE] = getKeySetting("keymap_mute");
1055 key[KeyType::INC_VOLUME] = getKeySetting("keymap_increase_volume");
1056 key[KeyType::DEC_VOLUME] = getKeySetting("keymap_decrease_volume");
1057 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1058 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1059 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1060 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1061 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1062 = getKeySetting("keymap_toggle_force_fog_off");
1063 key[KeyType::TOGGLE_UPDATE_CAMERA]
1064 = getKeySetting("keymap_toggle_update_camera");
1065 key[KeyType::TOGGLE_DEBUG]
1066 = getKeySetting("keymap_toggle_debug");
1067 key[KeyType::TOGGLE_PROFILER]
1068 = getKeySetting("keymap_toggle_profiler");
1069 key[KeyType::CAMERA_MODE]
1070 = getKeySetting("keymap_camera_mode");
1071 key[KeyType::INCREASE_VIEWING_RANGE]
1072 = getKeySetting("keymap_increase_viewing_range_min");
1073 key[KeyType::DECREASE_VIEWING_RANGE]
1074 = getKeySetting("keymap_decrease_viewing_range_min");
1075 key[KeyType::RANGESELECT]
1076 = getKeySetting("keymap_rangeselect");
1077 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1079 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1080 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1081 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1082 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1084 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1087 // First clear all keys, then re-add the ones we listen for
1088 handler->dontListenForKeys();
1089 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1090 handler->listenForKey(key[i]);
1092 handler->listenForKey(EscapeKey);
1093 handler->listenForKey(CancelKey);
1094 for (size_t i = 0; i < 10; i++) {
1095 handler->listenForKey(NumberKey[i]);
1101 /****************************************************************************
1103 ****************************************************************************/
1105 const float object_hit_delay = 0.2;
1108 u32 last_time, busy_time, sleep_time;
1112 /* The reason the following structs are not anonymous structs within the
1113 * class is that they are not used by the majority of member functions and
1114 * many functions that do require objects of thse types do not modify them
1115 * (so they can be passed as a const qualified parameter)
1117 struct CameraOrientation {
1118 f32 camera_yaw; // "right/left"
1119 f32 camera_pitch; // "up/down"
1122 struct GameRunData {
1125 PointedThing pointed_old;
1130 bool update_wielded_item_trigger;
1131 bool reset_jump_timer;
1132 float nodig_delay_timer;
1134 float dig_time_complete;
1135 float repeat_rightclick_timer;
1136 float object_hit_delay_timer;
1137 float time_from_last_punch;
1138 ClientActiveObject *selected_object;
1142 float update_draw_list_timer;
1143 float statustext_time;
1147 v3f update_draw_list_last_cam_dir;
1149 u32 profiler_current_page;
1150 u32 profiler_max_page; // Number of pages
1153 float time_of_day_smooth;
1157 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1163 Jitter dtime_jitter, busy_time_jitter;
1166 /****************************************************************************
1168 ****************************************************************************/
1170 /* This is not intended to be a public class. If a public class becomes
1171 * desirable then it may be better to create another 'wrapper' class that
1172 * hides most of the stuff in this class (nothing in this class is required
1173 * by any other file) but exposes the public methods/data only.
1180 bool startup(bool *kill,
1182 InputHandler *input,
1183 IrrlichtDevice *device,
1184 const std::string &map_dir,
1185 const std::string &playername,
1186 const std::string &password,
1187 // If address is "", local server is used and address is updated
1188 std::string *address,
1190 std::string &error_message,
1192 ChatBackend *chat_backend,
1193 const SubgameSpec &gamespec, // Used for local game
1194 bool simple_singleplayer_mode);
1201 void extendedResourceCleanup();
1203 // Basic initialisation
1204 bool init(const std::string &map_dir, std::string *address,
1206 const SubgameSpec &gamespec);
1208 bool createSingleplayerServer(const std::string &map_dir,
1209 const SubgameSpec &gamespec, u16 port, std::string *address);
1212 bool createClient(const std::string &playername,
1213 const std::string &password, std::string *address, u16 port);
1216 // Client connection
1217 bool connectToServer(const std::string &playername,
1218 const std::string &password, std::string *address, u16 port,
1219 bool *connect_ok, bool *aborted);
1220 bool getServerContent(bool *aborted);
1224 void updateInteractTimers(f32 dtime);
1225 bool checkConnection();
1226 bool handleCallbacks();
1227 void processQueues();
1228 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1229 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1230 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1233 void processUserInput(f32 dtime);
1234 void processKeyInput();
1235 void processItemSelection(u16 *new_playeritem);
1237 void dropSelectedItem();
1238 void openInventory();
1239 void openConsole(float scale, const wchar_t *line=NULL);
1240 void toggleFreeMove();
1241 void toggleFreeMoveAlt();
1243 void toggleNoClip();
1244 void toggleCinematic();
1245 void toggleAutorun();
1249 void toggleMinimap(bool shift_pressed);
1252 void toggleUpdateCamera();
1253 void toggleProfiler();
1255 void increaseViewRange();
1256 void decreaseViewRange();
1257 void toggleFullViewRange();
1259 void updateCameraDirection(CameraOrientation *cam, float dtime);
1260 void updateCameraOrientation(CameraOrientation *cam, float dtime);
1261 void updatePlayerControl(const CameraOrientation &cam);
1262 void step(f32 *dtime);
1263 void processClientEvents(CameraOrientation *cam);
1264 void updateCamera(u32 busy_time, f32 dtime);
1265 void updateSound(f32 dtime);
1266 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
1268 * Returns the object or node the player is pointing at.
1269 * Also updates the selected thing in the Hud.
1271 * @param[in] shootline the shootline, starting from
1272 * the camera position. This also gives the maximal distance
1274 * @param[in] liquids_pointable if false, liquids are ignored
1275 * @param[in] look_for_object if false, objects are ignored
1276 * @param[in] camera_offset offset of the camera
1277 * @param[out] selected_object the selected object or
1280 PointedThing updatePointedThing(
1281 const core::line3d<f32> &shootline, bool liquids_pointable,
1282 bool look_for_object, const v3s16 &camera_offset);
1283 void handlePointingAtNothing(const ItemStack &playerItem);
1284 void handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
1285 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1286 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
1287 const v3f &player_position, bool show_debug);
1288 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
1289 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1290 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
1291 const CameraOrientation &cam);
1292 void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
1293 void updateProfilerGraphs(ProfilerGraph *graph);
1296 void limitFps(FpsControl *fps_timings, f32 *dtime);
1298 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1299 bool draw_clouds = true);
1301 static void settingChangedCallback(const std::string &setting_name, void *data);
1302 void readSettings();
1304 inline bool getLeftClicked()
1306 return input->getLeftClicked() ||
1307 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1309 inline bool getRightClicked()
1311 return input->getRightClicked() ||
1312 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1314 inline bool isLeftPressed()
1316 return input->getLeftState() ||
1317 input->joystick.isKeyDown(KeyType::MOUSE_L);
1319 inline bool isRightPressed()
1321 return input->getRightState() ||
1322 input->joystick.isKeyDown(KeyType::MOUSE_R);
1324 inline bool getLeftReleased()
1326 return input->getLeftReleased() ||
1327 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1330 inline bool isKeyDown(GameKeyType k)
1332 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1334 inline bool wasKeyDown(GameKeyType k)
1336 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1340 void handleAndroidChatInput();
1344 void showPauseMenu();
1346 InputHandler *input;
1351 IWritableTextureSource *texture_src;
1352 IWritableShaderSource *shader_src;
1354 // When created, these will be filled with data received from the server
1355 IWritableItemDefManager *itemdef_manager;
1356 IWritableNodeDefManager *nodedef_manager;
1358 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1359 ISoundManager *sound;
1360 bool sound_is_dummy;
1361 SoundMaker *soundmaker;
1363 ChatBackend *chat_backend;
1365 GUIFormSpecMenu *current_formspec;
1366 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1367 std::string cur_formname;
1369 EventManager *eventmgr;
1370 QuicktuneShortcutter *quicktune;
1372 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1373 MapDrawControl *draw_control;
1375 Clouds *clouds; // Free using ->Drop()
1376 Sky *sky; // Free using ->Drop()
1377 Inventory *local_inventory;
1381 GameRunData runData;
1385 This class does take ownership/responsibily for cleaning up etc of any of
1386 these items (e.g. device)
1388 IrrlichtDevice *device;
1389 video::IVideoDriver *driver;
1390 scene::ISceneManager *smgr;
1392 std::string *error_message;
1393 bool *reconnect_requested;
1394 scene::ISceneNode *skybox;
1397 bool simple_singleplayer_mode;
1400 /* Pre-calculated values
1402 int crack_animation_length;
1406 gui::IGUIStaticText *guitext; // First line of debug text
1407 gui::IGUIStaticText *guitext2; // Second line of debug text
1408 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1409 gui::IGUIStaticText *guitext_status;
1410 gui::IGUIStaticText *guitext_chat; // Chat text
1411 gui::IGUIStaticText *guitext_profiler; // Profiler text
1413 std::wstring infotext;
1414 std::wstring m_statustext;
1418 IntervalLimiter profiler_interval;
1421 * TODO: Local caching of settings is not optimal and should at some stage
1422 * be updated to use a global settings object for getting thse values
1423 * (as opposed to the this local caching). This can be addressed in
1426 bool m_cache_doubletap_jump;
1427 bool m_cache_enable_clouds;
1428 bool m_cache_enable_joysticks;
1429 bool m_cache_enable_particles;
1430 bool m_cache_enable_fog;
1431 bool m_cache_enable_noclip;
1432 bool m_cache_enable_free_move;
1433 f32 m_cache_mouse_sensitivity;
1434 f32 m_cache_joystick_frustum_sensitivity;
1435 f32 m_repeat_right_click_time;
1436 f32 m_cache_cam_smoothing;
1437 f32 m_cache_fog_start;
1439 bool m_invert_mouse;
1440 bool m_first_loop_after_window_activation;
1441 bool m_camera_offset_changed;
1444 bool m_cache_hold_aux1;
1445 bool m_android_chat_open;
1454 itemdef_manager(NULL),
1455 nodedef_manager(NULL),
1457 sound_is_dummy(false),
1460 current_formspec(NULL),
1464 gui_chat_console(NULL),
1469 local_inventory(NULL),
1472 m_invert_mouse(false),
1473 m_first_loop_after_window_activation(false),
1474 m_camera_offset_changed(false)
1476 g_settings->registerChangedCallback("doubletap_jump",
1477 &settingChangedCallback, this);
1478 g_settings->registerChangedCallback("enable_clouds",
1479 &settingChangedCallback, this);
1480 g_settings->registerChangedCallback("doubletap_joysticks",
1481 &settingChangedCallback, this);
1482 g_settings->registerChangedCallback("enable_particles",
1483 &settingChangedCallback, this);
1484 g_settings->registerChangedCallback("enable_fog",
1485 &settingChangedCallback, this);
1486 g_settings->registerChangedCallback("mouse_sensitivity",
1487 &settingChangedCallback, this);
1488 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1489 &settingChangedCallback, this);
1490 g_settings->registerChangedCallback("repeat_rightclick_time",
1491 &settingChangedCallback, this);
1492 g_settings->registerChangedCallback("noclip",
1493 &settingChangedCallback, this);
1494 g_settings->registerChangedCallback("free_move",
1495 &settingChangedCallback, this);
1496 g_settings->registerChangedCallback("cinematic",
1497 &settingChangedCallback, this);
1498 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1499 &settingChangedCallback, this);
1500 g_settings->registerChangedCallback("camera_smoothing",
1501 &settingChangedCallback, this);
1506 m_cache_hold_aux1 = false; // This is initialised properly later
1513 /****************************************************************************
1515 ****************************************************************************/
1521 if (!sound_is_dummy)
1524 delete server; // deleted first to stop all server threads
1527 delete local_inventory;
1533 delete nodedef_manager;
1534 delete itemdef_manager;
1535 delete draw_control;
1537 extendedResourceCleanup();
1539 g_settings->deregisterChangedCallback("doubletap_jump",
1540 &settingChangedCallback, this);
1541 g_settings->deregisterChangedCallback("enable_clouds",
1542 &settingChangedCallback, this);
1543 g_settings->deregisterChangedCallback("enable_particles",
1544 &settingChangedCallback, this);
1545 g_settings->deregisterChangedCallback("enable_fog",
1546 &settingChangedCallback, this);
1547 g_settings->deregisterChangedCallback("mouse_sensitivity",
1548 &settingChangedCallback, this);
1549 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1550 &settingChangedCallback, this);
1551 g_settings->deregisterChangedCallback("noclip",
1552 &settingChangedCallback, this);
1553 g_settings->deregisterChangedCallback("free_move",
1554 &settingChangedCallback, this);
1555 g_settings->deregisterChangedCallback("cinematic",
1556 &settingChangedCallback, this);
1557 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1558 &settingChangedCallback, this);
1559 g_settings->deregisterChangedCallback("camera_smoothing",
1560 &settingChangedCallback, this);
1563 bool Game::startup(bool *kill,
1565 InputHandler *input,
1566 IrrlichtDevice *device,
1567 const std::string &map_dir,
1568 const std::string &playername,
1569 const std::string &password,
1570 std::string *address, // can change if simple_singleplayer_mode
1572 std::string &error_message,
1574 ChatBackend *chat_backend,
1575 const SubgameSpec &gamespec,
1576 bool simple_singleplayer_mode)
1579 this->device = device;
1581 this->error_message = &error_message;
1582 this->reconnect_requested = reconnect;
1583 this->random_input = random_input;
1584 this->input = input;
1585 this->chat_backend = chat_backend;
1586 this->simple_singleplayer_mode = simple_singleplayer_mode;
1588 keycache.handler = input;
1589 keycache.populate();
1591 driver = device->getVideoDriver();
1592 smgr = device->getSceneManager();
1594 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1596 memset(&runData, 0, sizeof(runData));
1597 runData.time_from_last_punch = 10.0;
1598 runData.profiler_max_page = 3;
1599 runData.update_wielded_item_trigger = true;
1601 memset(&flags, 0, sizeof(flags));
1602 flags.show_chat = true;
1603 flags.show_hud = true;
1604 flags.show_debug = g_settings->getBool("show_debug");
1605 m_invert_mouse = g_settings->getBool("invert_mouse");
1606 m_first_loop_after_window_activation = true;
1608 if (!init(map_dir, address, port, gamespec))
1611 if (!createClient(playername, password, address, port))
1620 ProfilerGraph graph;
1621 RunStats stats = { 0 };
1622 CameraOrientation cam_view_target = { 0 };
1623 CameraOrientation cam_view = { 0 };
1624 FpsControl draw_times = { 0 };
1625 f32 dtime; // in seconds
1627 /* Clear the profiler */
1628 Profiler::GraphValues dummyvalues;
1629 g_profiler->graphGet(dummyvalues);
1631 draw_times.last_time = device->getTimer()->getTime();
1633 set_light_table(g_settings->getFloat("display_gamma"));
1636 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1637 && client->checkPrivilege("fast");
1640 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screenW"),
1641 g_settings->getU16("screenH"));
1643 while (device->run()
1644 && !(*kill || g_gamecallback->shutdown_requested
1645 || (server && server->getShutdownRequested()))) {
1647 const irr::core::dimension2d<u32> ¤t_screen_size =
1648 device->getVideoDriver()->getScreenSize();
1649 // Verify if window size has changed and save it if it's the case
1650 // Ensure evaluating settings->getBool after verifying screensize
1651 // First condition is cheaper
1652 if (previous_screen_size != current_screen_size &&
1653 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1654 g_settings->getBool("autosave_screensize")) {
1655 g_settings->setU16("screenW", current_screen_size.Width);
1656 g_settings->setU16("screenH", current_screen_size.Height);
1657 previous_screen_size = current_screen_size;
1660 /* Must be called immediately after a device->run() call because it
1661 * uses device->getTimer()->getTime()
1663 limitFps(&draw_times, &dtime);
1665 updateStats(&stats, draw_times, dtime);
1666 updateInteractTimers(dtime);
1668 if (!checkConnection())
1670 if (!handleCallbacks())
1676 hud->resizeHotbar();
1678 updateProfilers(stats, draw_times, dtime);
1679 processUserInput(dtime);
1680 // Update camera before player movement to avoid camera lag of one frame
1681 updateCameraDirection(&cam_view_target, dtime);
1682 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1683 cam_view.camera_yaw) * m_cache_cam_smoothing;
1684 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1685 cam_view.camera_pitch) * m_cache_cam_smoothing;
1686 updatePlayerControl(cam_view);
1688 processClientEvents(&cam_view_target);
1689 updateCamera(draw_times.busy_time, dtime);
1691 processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
1692 updateFrame(&graph, &stats, dtime, cam_view);
1693 updateProfilerGraphs(&graph);
1695 // Update if minimap has been disabled by the server
1696 flags.show_minimap &= client->shouldShowMinimap();
1701 void Game::shutdown()
1703 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1704 if (g_settings->get("3d_mode") == "pageflip") {
1705 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1709 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1714 if (gui_chat_console)
1715 gui_chat_console->drop();
1721 while (g_menumgr.menuCount() > 0) {
1722 g_menumgr.m_stack.front()->setVisible(false);
1723 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1726 if (current_formspec) {
1727 current_formspec->drop();
1728 current_formspec = NULL;
1731 chat_backend->addMessage(L"", L"# Disconnected.");
1732 chat_backend->addMessage(L"", L"");
1736 while (!client->isShutdown()) {
1737 assert(texture_src != NULL);
1738 assert(shader_src != NULL);
1739 texture_src->processQueue();
1740 shader_src->processQueue();
1747 /****************************************************************************/
1748 /****************************************************************************
1750 ****************************************************************************/
1751 /****************************************************************************/
1754 const std::string &map_dir,
1755 std::string *address,
1757 const SubgameSpec &gamespec)
1759 texture_src = createTextureSource(device);
1761 showOverlayMessage(wgettext("Loading..."), 0, 0);
1763 shader_src = createShaderSource(device);
1765 itemdef_manager = createItemDefManager();
1766 nodedef_manager = createNodeDefManager();
1768 eventmgr = new EventManager();
1769 quicktune = new QuicktuneShortcutter();
1771 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1772 && eventmgr && quicktune))
1778 // Create a server if not connecting to an existing one
1779 if (*address == "") {
1780 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1787 bool Game::initSound()
1790 if (g_settings->getBool("enable_sound")) {
1791 infostream << "Attempting to use OpenAL audio" << std::endl;
1792 sound = createOpenALSoundManager(&soundfetcher);
1794 infostream << "Failed to initialize OpenAL audio" << std::endl;
1796 infostream << "Sound disabled." << std::endl;
1800 infostream << "Using dummy audio." << std::endl;
1801 sound = &dummySoundManager;
1802 sound_is_dummy = true;
1805 soundmaker = new SoundMaker(sound, nodedef_manager);
1809 soundmaker->registerReceiver(eventmgr);
1814 bool Game::createSingleplayerServer(const std::string &map_dir,
1815 const SubgameSpec &gamespec, u16 port, std::string *address)
1817 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1819 std::string bind_str = g_settings->get("bind_address");
1820 Address bind_addr(0, 0, 0, 0, port);
1822 if (g_settings->getBool("ipv6_server")) {
1823 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1827 bind_addr.Resolve(bind_str.c_str());
1828 } catch (ResolveError &e) {
1829 infostream << "Resolving bind address \"" << bind_str
1830 << "\" failed: " << e.what()
1831 << " -- Listening on all addresses." << std::endl;
1834 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1835 *error_message = "Unable to listen on " +
1836 bind_addr.serializeString() +
1837 " because IPv6 is disabled";
1838 errorstream << *error_message << std::endl;
1842 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1843 bind_addr.isIPv6(), false);
1845 server->start(bind_addr);
1850 bool Game::createClient(const std::string &playername,
1851 const std::string &password, std::string *address, u16 port)
1853 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1855 draw_control = new MapDrawControl;
1859 bool could_connect, connect_aborted;
1861 if (!connectToServer(playername, password, address, port,
1862 &could_connect, &connect_aborted))
1865 if (!could_connect) {
1866 if (error_message->empty() && !connect_aborted) {
1867 // Should not happen if error messages are set properly
1868 *error_message = "Connection failed for unknown reason";
1869 errorstream << *error_message << std::endl;
1874 if (!getServerContent(&connect_aborted)) {
1875 if (error_message->empty() && !connect_aborted) {
1876 // Should not happen if error messages are set properly
1877 *error_message = "Connection failed for unknown reason";
1878 errorstream << *error_message << std::endl;
1883 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1884 &flags.force_fog_off, &runData.fog_range, client);
1885 shader_src->addShaderConstantSetterFactory(scsf);
1887 // Update cached textures, meshes and materials
1888 client->afterContentReceived(device);
1892 camera = new Camera(smgr, *draw_control, client);
1893 if (!camera || !camera->successfullyCreated(*error_message))
1895 client->setCamera(camera);
1899 if (m_cache_enable_clouds) {
1900 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1902 *error_message = "Memory allocation error (clouds)";
1903 errorstream << *error_message << std::endl;
1910 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
1912 skybox = NULL; // This is used/set later on in the main run loop
1914 local_inventory = new Inventory(itemdef_manager);
1916 if (!(sky && local_inventory)) {
1917 *error_message = "Memory allocation error (sky or local inventory)";
1918 errorstream << *error_message << std::endl;
1922 /* Pre-calculated values
1924 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1926 v2u32 size = t->getOriginalSize();
1927 crack_animation_length = size.Y / size.X;
1929 crack_animation_length = 5;
1935 /* Set window caption
1937 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1939 str += utf8_to_wide(g_version_hash);
1941 str += driver->getName();
1943 device->setWindowCaption(str.c_str());
1945 LocalPlayer *player = client->getEnv().getLocalPlayer();
1946 player->hurt_tilt_timer = 0;
1947 player->hurt_tilt_strength = 0;
1949 hud = new Hud(driver, smgr, guienv, client, player, local_inventory);
1952 *error_message = "Memory error: could not create HUD";
1953 errorstream << *error_message << std::endl;
1957 mapper = client->getMinimap();
1958 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1963 bool Game::initGui()
1965 // First line of debug text
1966 guitext = addStaticText(guienv,
1967 utf8_to_wide(PROJECT_NAME_C).c_str(),
1968 core::rect<s32>(0, 0, 0, 0),
1969 false, false, guiroot);
1971 // Second line of debug text
1972 guitext2 = addStaticText(guienv,
1974 core::rect<s32>(0, 0, 0, 0),
1975 false, false, guiroot);
1977 // At the middle of the screen
1978 // Object infos are shown in this
1979 guitext_info = addStaticText(guienv,
1981 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
1982 false, true, guiroot);
1984 // Status text (displays info when showing and hiding GUI stuff, etc.)
1985 guitext_status = addStaticText(guienv,
1987 core::rect<s32>(0, 0, 0, 0),
1988 false, false, guiroot);
1989 guitext_status->setVisible(false);
1992 guitext_chat = addStaticText(
1995 core::rect<s32>(0, 0, 0, 0),
1996 //false, false); // Disable word wrap as of now
1997 false, true, guiroot);
1999 // Remove stale "recent" chat messages from previous connections
2000 chat_backend->clearRecentChat();
2002 // Chat backend and console
2003 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2004 -1, chat_backend, client, &g_menumgr);
2005 if (!gui_chat_console) {
2006 *error_message = "Could not allocate memory for chat console";
2007 errorstream << *error_message << std::endl;
2011 // Profiler text (size is updated when text is updated)
2012 guitext_profiler = addStaticText(guienv,
2014 core::rect<s32>(0, 0, 0, 0),
2015 false, false, guiroot);
2016 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2017 guitext_profiler->setVisible(false);
2018 guitext_profiler->setWordWrap(true);
2020 #ifdef HAVE_TOUCHSCREENGUI
2022 if (g_touchscreengui)
2023 g_touchscreengui->init(texture_src);
2030 bool Game::connectToServer(const std::string &playername,
2031 const std::string &password, std::string *address, u16 port,
2032 bool *connect_ok, bool *aborted)
2034 *connect_ok = false; // Let's not be overly optimistic
2036 bool local_server_mode = false;
2038 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2040 Address connect_address(0, 0, 0, 0, port);
2043 connect_address.Resolve(address->c_str());
2045 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2046 //connect_address.Resolve("localhost");
2047 if (connect_address.isIPv6()) {
2048 IPv6AddressBytes addr_bytes;
2049 addr_bytes.bytes[15] = 1;
2050 connect_address.setAddress(&addr_bytes);
2052 connect_address.setAddress(127, 0, 0, 1);
2054 local_server_mode = true;
2056 } catch (ResolveError &e) {
2057 *error_message = std::string("Couldn't resolve address: ") + e.what();
2058 errorstream << *error_message << std::endl;
2062 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2063 *error_message = "Unable to connect to " +
2064 connect_address.serializeString() +
2065 " because IPv6 is disabled";
2066 errorstream << *error_message << std::endl;
2070 client = new Client(device,
2071 playername.c_str(), password, *address,
2072 *draw_control, texture_src, shader_src,
2073 itemdef_manager, nodedef_manager, sound, eventmgr,
2074 connect_address.isIPv6(), &flags);
2079 infostream << "Connecting to server at ";
2080 connect_address.print(&infostream);
2081 infostream << std::endl;
2083 client->connect(connect_address,
2084 simple_singleplayer_mode || local_server_mode);
2087 Wait for server to accept connection
2093 FpsControl fps_control = { 0 };
2095 f32 wait_time = 0; // in seconds
2097 fps_control.last_time = device->getTimer()->getTime();
2101 while (device->run()) {
2103 limitFps(&fps_control, &dtime);
2105 // Update client and server
2106 client->step(dtime);
2109 server->step(dtime);
2112 if (client->getState() == LC_Init) {
2118 if (client->accessDenied()) {
2119 *error_message = "Access denied. Reason: "
2120 + client->accessDeniedReason();
2121 *reconnect_requested = client->reconnectRequested();
2122 errorstream << *error_message << std::endl;
2126 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2128 infostream << "Connect aborted [Escape]" << std::endl;
2133 // Only time out if we aren't waiting for the server we started
2134 if ((*address != "") && (wait_time > 10)) {
2135 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2136 // If no pre v25 init was sent, and no answer was received,
2137 // but the low level connection could be established
2138 // (meaning that we have a peer id), then we probably wanted
2139 // to connect to a legacy server. In this case, tell the user
2140 // to enable the option to be able to connect.
2141 if (!sent_old_init &&
2142 (client->getProtoVersion() == 0) &&
2143 client->connectedToServer()) {
2144 *error_message = "Connection failure: init packet not "
2145 "recognized by server.\n"
2146 "Most likely the server uses an old protocol version (<v25).\n"
2147 "Please ask the server owner to update to 0.4.13 or later.\n"
2148 "To still connect to the server in the meantime,\n"
2149 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2150 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2151 "entry in the advanced settings menu.";
2153 *error_message = "Connection timed out.";
2155 errorstream << *error_message << std::endl;
2160 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2162 } catch (con::PeerNotFoundException &e) {
2163 // TODO: Should something be done here? At least an info/error
2171 bool Game::getServerContent(bool *aborted)
2175 FpsControl fps_control = { 0 };
2176 f32 dtime; // in seconds
2178 fps_control.last_time = device->getTimer()->getTime();
2180 while (device->run()) {
2182 limitFps(&fps_control, &dtime);
2184 // Update client and server
2185 client->step(dtime);
2188 server->step(dtime);
2191 if (client->mediaReceived() && client->itemdefReceived() &&
2192 client->nodedefReceived()) {
2197 if (!checkConnection())
2200 if (client->getState() < LC_Init) {
2201 *error_message = "Client disconnected";
2202 errorstream << *error_message << std::endl;
2206 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2208 infostream << "Connect aborted [Escape]" << std::endl;
2215 if (!client->itemdefReceived()) {
2216 const wchar_t *text = wgettext("Item definitions...");
2218 draw_load_screen(text, device, guienv, texture_src,
2221 } else if (!client->nodedefReceived()) {
2222 const wchar_t *text = wgettext("Node definitions...");
2224 draw_load_screen(text, device, guienv, texture_src,
2228 std::stringstream message;
2229 std::fixed(message);
2230 message.precision(0);
2231 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2232 message.precision(2);
2234 if ((USE_CURL == 0) ||
2235 (!g_settings->getBool("enable_remote_media_server"))) {
2236 float cur = client->getCurRate();
2237 std::string cur_unit = gettext("KiB/s");
2241 cur_unit = gettext("MiB/s");
2244 message << " (" << cur << ' ' << cur_unit << ")";
2247 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2248 draw_load_screen(utf8_to_wide(message.str()), device,
2249 guienv, texture_src, dtime, progress);
2257 /****************************************************************************/
2258 /****************************************************************************
2260 ****************************************************************************/
2261 /****************************************************************************/
2263 inline void Game::updateInteractTimers(f32 dtime)
2265 if (runData.nodig_delay_timer >= 0)
2266 runData.nodig_delay_timer -= dtime;
2268 if (runData.object_hit_delay_timer >= 0)
2269 runData.object_hit_delay_timer -= dtime;
2271 runData.time_from_last_punch += dtime;
2275 /* returns false if game should exit, otherwise true
2277 inline bool Game::checkConnection()
2279 if (client->accessDenied()) {
2280 *error_message = "Access denied. Reason: "
2281 + client->accessDeniedReason();
2282 *reconnect_requested = client->reconnectRequested();
2283 errorstream << *error_message << std::endl;
2291 /* returns false if game should exit, otherwise true
2293 inline bool Game::handleCallbacks()
2295 if (g_gamecallback->disconnect_requested) {
2296 g_gamecallback->disconnect_requested = false;
2300 if (g_gamecallback->changepassword_requested) {
2301 (new GUIPasswordChange(guienv, guiroot, -1,
2302 &g_menumgr, client))->drop();
2303 g_gamecallback->changepassword_requested = false;
2306 if (g_gamecallback->changevolume_requested) {
2307 (new GUIVolumeChange(guienv, guiroot, -1,
2308 &g_menumgr))->drop();
2309 g_gamecallback->changevolume_requested = false;
2312 if (g_gamecallback->keyconfig_requested) {
2313 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2314 &g_menumgr))->drop();
2315 g_gamecallback->keyconfig_requested = false;
2318 if (g_gamecallback->keyconfig_changed) {
2319 keycache.populate(); // update the cache with new settings
2320 g_gamecallback->keyconfig_changed = false;
2327 void Game::processQueues()
2329 texture_src->processQueue();
2330 itemdef_manager->processQueue(client);
2331 shader_src->processQueue();
2335 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2337 float profiler_print_interval =
2338 g_settings->getFloat("profiler_print_interval");
2339 bool print_to_log = true;
2341 if (profiler_print_interval == 0) {
2342 print_to_log = false;
2343 profiler_print_interval = 5;
2346 if (profiler_interval.step(dtime, profiler_print_interval)) {
2348 infostream << "Profiler:" << std::endl;
2349 g_profiler->print(infostream);
2352 update_profiler_gui(guitext_profiler, g_fontengine,
2353 runData.profiler_current_page, runData.profiler_max_page,
2354 driver->getScreenSize().Height);
2356 g_profiler->clear();
2359 addProfilerGraphs(stats, draw_times, dtime);
2363 void Game::addProfilerGraphs(const RunStats &stats,
2364 const FpsControl &draw_times, f32 dtime)
2366 g_profiler->graphAdd("mainloop_other",
2367 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2369 if (draw_times.sleep_time != 0)
2370 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2371 g_profiler->graphAdd("mainloop_dtime", dtime);
2373 g_profiler->add("Elapsed time", dtime);
2374 g_profiler->avg("FPS", 1. / dtime);
2378 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2385 /* Time average and jitter calculation
2387 jp = &stats->dtime_jitter;
2388 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2390 jitter = dtime - jp->avg;
2392 if (jitter > jp->max)
2395 jp->counter += dtime;
2397 if (jp->counter > 0.0) {
2399 jp->max_sample = jp->max;
2400 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2404 /* Busytime average and jitter calculation
2406 jp = &stats->busy_time_jitter;
2407 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2409 jitter = draw_times.busy_time - jp->avg;
2411 if (jitter > jp->max)
2413 if (jitter < jp->min)
2416 jp->counter += dtime;
2418 if (jp->counter > 0.0) {
2420 jp->max_sample = jp->max;
2421 jp->min_sample = jp->min;
2429 /****************************************************************************
2431 ****************************************************************************/
2433 void Game::processUserInput(f32 dtime)
2435 // Reset input if window not active or some menu is active
2436 if (!device->isWindowActive() || !noMenuActive() || guienv->hasFocus(gui_chat_console)) {
2438 #ifdef HAVE_TOUCHSCREENGUI
2439 g_touchscreengui->hide();
2442 #ifdef HAVE_TOUCHSCREENGUI
2443 else if (g_touchscreengui) {
2444 /* on touchscreengui step may generate own input events which ain't
2445 * what we want in case we just did clear them */
2446 g_touchscreengui->step(dtime);
2450 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2451 gui_chat_console->closeConsoleAtOnce();
2454 // Input handler step() (used by the random input generator)
2458 if (current_formspec != NULL)
2459 current_formspec->getAndroidUIInput();
2461 handleAndroidChatInput();
2464 // Increase timer for double tap of "keymap_jump"
2465 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2466 runData.jump_timer += dtime;
2469 processItemSelection(&runData.new_playeritem);
2473 void Game::processKeyInput()
2475 if (wasKeyDown(KeyType::DROP)) {
2477 } else if (wasKeyDown(KeyType::AUTORUN)) {
2479 } else if (wasKeyDown(KeyType::INVENTORY)) {
2481 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2482 if (!gui_chat_console->isOpenInhibited()) {
2485 } else if (wasKeyDown(KeyType::CHAT)) {
2486 openConsole(0.2, L"");
2487 } else if (wasKeyDown(KeyType::CMD)) {
2488 openConsole(0.2, L"/");
2489 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2490 openConsole(0.2, L".");
2491 } else if (wasKeyDown(KeyType::CONSOLE)) {
2492 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2493 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2495 } else if (wasKeyDown(KeyType::JUMP)) {
2496 toggleFreeMoveAlt();
2497 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2499 } else if (wasKeyDown(KeyType::NOCLIP)) {
2501 } else if (wasKeyDown(KeyType::MUTE)) {
2502 float volume = g_settings->getFloat("sound_volume");
2503 if (volume < 0.001f) {
2504 g_settings->setFloat("sound_volume", 1.0f);
2505 m_statustext = narrow_to_wide(gettext("Volume changed to 100%"));
2507 g_settings->setFloat("sound_volume", 0.0f);
2508 m_statustext = narrow_to_wide(gettext("Volume changed to 0%"));
2510 runData.statustext_time = 0;
2511 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
2512 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
2514 g_settings->setFloat("sound_volume", new_volume);
2515 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2516 m_statustext = narrow_to_wide(buf);
2517 runData.statustext_time = 0;
2518 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
2519 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
2521 g_settings->setFloat("sound_volume", new_volume);
2522 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2523 m_statustext = narrow_to_wide(buf);
2524 runData.statustext_time = 0;
2525 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2527 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2528 client->makeScreenshot(device);
2529 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2531 } else if (wasKeyDown(KeyType::MINIMAP)) {
2532 toggleMinimap(isKeyDown(KeyType::SNEAK));
2533 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2535 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2537 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2538 toggleUpdateCamera();
2539 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2541 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2543 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2544 increaseViewRange();
2545 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2546 decreaseViewRange();
2547 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2548 toggleFullViewRange();
2549 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2551 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2553 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2555 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2557 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2558 // Print debug stacks
2559 dstream << "-----------------------------------------"
2561 dstream << "Printing debug stacks:" << std::endl;
2562 dstream << "-----------------------------------------"
2564 debug_stacks_print();
2567 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2568 runData.reset_jump_timer = false;
2569 runData.jump_timer = 0.0f;
2572 if (quicktune->hasMessage()) {
2573 m_statustext = utf8_to_wide(quicktune->getMessage());
2574 runData.statustext_time = 0.0f;
2578 void Game::processItemSelection(u16 *new_playeritem)
2580 LocalPlayer *player = client->getEnv().getLocalPlayer();
2582 /* Item selection using mouse wheel
2584 *new_playeritem = client->getPlayerItem();
2586 s32 wheel = input->getMouseWheel();
2587 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2588 player->hud_hotbar_itemcount - 1);
2592 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2593 wasKeyDown(KeyType::HOTBAR_NEXT)) {
2597 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2598 wasKeyDown(KeyType::HOTBAR_PREV)) {
2603 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2605 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2608 /* Item selection using keyboard
2610 for (u16 i = 0; i < 10; i++) {
2611 static const KeyPress *item_keys[10] = {
2612 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2613 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2614 NumberKey + 9, NumberKey + 0,
2617 if (input->wasKeyDown(*item_keys[i])) {
2618 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2619 *new_playeritem = i;
2620 infostream << "Selected item: " << new_playeritem << std::endl;
2628 void Game::dropSelectedItem()
2630 IDropAction *a = new IDropAction();
2632 a->from_inv.setCurrentPlayer();
2633 a->from_list = "main";
2634 a->from_i = client->getPlayerItem();
2635 client->inventoryAction(a);
2639 void Game::openInventory()
2642 * Don't permit to open inventory is CAO or player doesn't exists.
2643 * This prevent showing an empty inventory at player load
2646 LocalPlayer *player = client->getEnv().getLocalPlayer();
2647 if (player == NULL || player->getCAO() == NULL)
2650 infostream << "the_game: " << "Launching inventory" << std::endl;
2652 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2653 TextDest *txt_dst = new TextDestPlayerInventory(client);
2655 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
2658 InventoryLocation inventoryloc;
2659 inventoryloc.setCurrentPlayer();
2660 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2664 void Game::openConsole(float scale, const wchar_t *line)
2666 assert(scale > 0.0f && scale <= 1.0f);
2669 porting::showInputDialog(gettext("ok"), "", "", 2);
2670 m_android_chat_open = true;
2672 if (gui_chat_console->isOpenInhibited())
2674 gui_chat_console->openConsole(scale);
2676 gui_chat_console->setCloseOnEnter(true);
2677 gui_chat_console->replaceAndAddToHistory(line);
2683 void Game::handleAndroidChatInput()
2685 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2686 std::string text = porting::getInputDialogValue();
2687 client->typeChatMessage(utf8_to_wide(text));
2693 void Game::toggleFreeMove()
2695 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2697 bool free_move = !g_settings->getBool("free_move");
2698 g_settings->set("free_move", bool_to_cstr(free_move));
2700 runData.statustext_time = 0;
2701 m_statustext = msg[free_move];
2702 if (free_move && !client->checkPrivilege("fly"))
2703 m_statustext += L" (note: no 'fly' privilege)";
2707 void Game::toggleFreeMoveAlt()
2709 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2712 runData.reset_jump_timer = true;
2716 void Game::toggleFast()
2718 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2719 bool fast_move = !g_settings->getBool("fast_move");
2720 g_settings->set("fast_move", bool_to_cstr(fast_move));
2722 runData.statustext_time = 0;
2723 m_statustext = msg[fast_move];
2725 bool has_fast_privs = client->checkPrivilege("fast");
2727 if (fast_move && !has_fast_privs)
2728 m_statustext += L" (note: no 'fast' privilege)";
2731 m_cache_hold_aux1 = fast_move && has_fast_privs;
2736 void Game::toggleNoClip()
2738 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2739 bool noclip = !g_settings->getBool("noclip");
2740 g_settings->set("noclip", bool_to_cstr(noclip));
2742 runData.statustext_time = 0;
2743 m_statustext = msg[noclip];
2745 if (noclip && !client->checkPrivilege("noclip"))
2746 m_statustext += L" (note: no 'noclip' privilege)";
2749 void Game::toggleCinematic()
2751 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2752 bool cinematic = !g_settings->getBool("cinematic");
2753 g_settings->set("cinematic", bool_to_cstr(cinematic));
2755 runData.statustext_time = 0;
2756 m_statustext = msg[cinematic];
2759 // Add WoW-style autorun by toggling continuous forward.
2760 void Game::toggleAutorun()
2762 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2763 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2764 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2766 runData.statustext_time = 0;
2767 m_statustext = msg[autorun_enabled ? 1 : 0];
2770 void Game::toggleChat()
2772 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2774 flags.show_chat = !flags.show_chat;
2775 runData.statustext_time = 0;
2776 m_statustext = msg[flags.show_chat];
2780 void Game::toggleHud()
2782 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2784 flags.show_hud = !flags.show_hud;
2785 runData.statustext_time = 0;
2786 m_statustext = msg[flags.show_hud];
2789 void Game::toggleMinimap(bool shift_pressed)
2791 if (!flags.show_hud || !g_settings->getBool("enable_minimap"))
2794 if (shift_pressed) {
2795 mapper->toggleMinimapShape();
2799 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2801 MinimapMode mode = MINIMAP_MODE_OFF;
2802 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2803 mode = mapper->getMinimapMode();
2804 mode = (MinimapMode)((int)mode + 1);
2807 flags.show_minimap = true;
2809 case MINIMAP_MODE_SURFACEx1:
2810 m_statustext = L"Minimap in surface mode, Zoom x1";
2812 case MINIMAP_MODE_SURFACEx2:
2813 m_statustext = L"Minimap in surface mode, Zoom x2";
2815 case MINIMAP_MODE_SURFACEx4:
2816 m_statustext = L"Minimap in surface mode, Zoom x4";
2818 case MINIMAP_MODE_RADARx1:
2819 m_statustext = L"Minimap in radar mode, Zoom x1";
2821 case MINIMAP_MODE_RADARx2:
2822 m_statustext = L"Minimap in radar mode, Zoom x2";
2824 case MINIMAP_MODE_RADARx4:
2825 m_statustext = L"Minimap in radar mode, Zoom x4";
2828 mode = MINIMAP_MODE_OFF;
2829 flags.show_minimap = false;
2830 m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2831 L"Minimap hidden" : L"Minimap disabled by server";
2834 runData.statustext_time = 0;
2835 mapper->setMinimapMode(mode);
2838 void Game::toggleFog()
2840 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2842 flags.force_fog_off = !flags.force_fog_off;
2843 runData.statustext_time = 0;
2844 m_statustext = msg[flags.force_fog_off];
2848 void Game::toggleDebug()
2850 // Initial / 4x toggle: Chat only
2851 // 1x toggle: Debug text with chat
2852 // 2x toggle: Debug text with profiler graph
2853 // 3x toggle: Debug text and wireframe
2854 if (!flags.show_debug) {
2855 flags.show_debug = true;
2856 flags.show_profiler_graph = false;
2857 draw_control->show_wireframe = false;
2858 m_statustext = L"Debug info shown";
2859 } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2860 flags.show_profiler_graph = true;
2861 m_statustext = L"Profiler graph shown";
2862 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2863 flags.show_profiler_graph = false;
2864 draw_control->show_wireframe = true;
2865 m_statustext = L"Wireframe shown";
2867 flags.show_debug = false;
2868 flags.show_profiler_graph = false;
2869 draw_control->show_wireframe = false;
2870 if (client->checkPrivilege("debug")) {
2871 m_statustext = L"Debug info, profiler graph, and wireframe hidden";
2873 m_statustext = L"Debug info and profiler graph hidden";
2876 runData.statustext_time = 0;
2880 void Game::toggleUpdateCamera()
2882 static const wchar_t *msg[] = {
2883 L"Camera update enabled",
2884 L"Camera update disabled"
2887 flags.disable_camera_update = !flags.disable_camera_update;
2888 runData.statustext_time = 0;
2889 m_statustext = msg[flags.disable_camera_update];
2893 void Game::toggleProfiler()
2895 runData.profiler_current_page =
2896 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2898 // FIXME: This updates the profiler with incomplete values
2899 update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2900 runData.profiler_max_page, driver->getScreenSize().Height);
2902 if (runData.profiler_current_page != 0) {
2903 std::wstringstream sstr;
2904 sstr << "Profiler shown (page " << runData.profiler_current_page
2905 << " of " << runData.profiler_max_page << ")";
2906 m_statustext = sstr.str();
2908 m_statustext = L"Profiler hidden";
2910 runData.statustext_time = 0;
2914 void Game::increaseViewRange()
2916 s16 range = g_settings->getS16("viewing_range");
2917 s16 range_new = range + 10;
2919 if (range_new > 4000) {
2921 m_statustext = utf8_to_wide("Viewing range is at maximum: "
2924 m_statustext = utf8_to_wide("Viewing range changed to "
2927 g_settings->set("viewing_range", itos(range_new));
2928 runData.statustext_time = 0;
2932 void Game::decreaseViewRange()
2934 s16 range = g_settings->getS16("viewing_range");
2935 s16 range_new = range - 10;
2937 if (range_new < 20) {
2939 m_statustext = utf8_to_wide("Viewing range is at minimum: "
2942 m_statustext = utf8_to_wide("Viewing range changed to "
2945 g_settings->set("viewing_range", itos(range_new));
2946 runData.statustext_time = 0;
2950 void Game::toggleFullViewRange()
2952 static const wchar_t *msg[] = {
2953 L"Disabled full viewing range",
2954 L"Enabled full viewing range"
2957 draw_control->range_all = !draw_control->range_all;
2958 infostream << msg[draw_control->range_all] << std::endl;
2959 m_statustext = msg[draw_control->range_all];
2960 runData.statustext_time = 0;
2964 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2966 if ((device->isWindowActive() && noMenuActive()) || random_input) {
2969 if (!random_input) {
2970 // Mac OSX gets upset if this is set every frame
2971 if (device->getCursorControl()->isVisible())
2972 device->getCursorControl()->setVisible(false);
2976 if (m_first_loop_after_window_activation)
2977 m_first_loop_after_window_activation = false;
2979 updateCameraOrientation(cam, dtime);
2981 input->setMousePos((driver->getScreenSize().Width / 2),
2982 (driver->getScreenSize().Height / 2));
2986 // Mac OSX gets upset if this is set every frame
2987 if (!device->getCursorControl()->isVisible())
2988 device->getCursorControl()->setVisible(true);
2991 if (!m_first_loop_after_window_activation)
2992 m_first_loop_after_window_activation = true;
2997 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2999 #ifdef HAVE_TOUCHSCREENGUI
3000 if (g_touchscreengui) {
3001 cam->camera_yaw += g_touchscreengui->getYawChange();
3002 cam->camera_pitch = g_touchscreengui->getPitch();
3006 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3007 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3009 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3013 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3014 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3016 #ifdef HAVE_TOUCHSCREENGUI
3020 if (m_cache_enable_joysticks) {
3021 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3022 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
3023 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
3026 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3030 void Game::updatePlayerControl(const CameraOrientation &cam)
3032 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3034 // DO NOT use the isKeyDown method for the forward, backward, left, right
3035 // buttons, as the code that uses the controls needs to be able to
3036 // distinguish between the two in order to know when to use joysticks.
3038 PlayerControl control(
3039 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3040 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3041 input->isKeyDown(keycache.key[KeyType::LEFT]),
3042 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3043 isKeyDown(KeyType::JUMP),
3044 isKeyDown(KeyType::SPECIAL1),
3045 isKeyDown(KeyType::SNEAK),
3046 isKeyDown(KeyType::ZOOM),
3051 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3052 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3056 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3057 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3058 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3059 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3060 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3061 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3062 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3063 ( (u32)(isLeftPressed() & 0x1) << 7) |
3064 ( (u32)(isRightPressed() & 0x1) << 8
3068 /* For Android, simulate holding down AUX1 (fast move) if the user has
3069 * the fast_move setting toggled on. If there is an aux1 key defined for
3070 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3073 if (m_cache_hold_aux1) {
3074 control.aux1 = control.aux1 ^ true;
3075 keypress_bits ^= ((u32)(1U << 5));
3079 client->setPlayerControl(control);
3080 LocalPlayer *player = client->getEnv().getLocalPlayer();
3081 player->keyPressed = keypress_bits;
3087 inline void Game::step(f32 *dtime)
3089 bool can_be_and_is_paused =
3090 (simple_singleplayer_mode && g_menumgr.pausesGame());
3092 if (can_be_and_is_paused) { // This is for a singleplayer server
3093 *dtime = 0; // No time passes
3095 if (server != NULL) {
3096 //TimeTaker timer("server->step(dtime)");
3097 server->step(*dtime);
3100 //TimeTaker timer("client.step(dtime)");
3101 client->step(*dtime);
3106 void Game::processClientEvents(CameraOrientation *cam)
3108 LocalPlayer *player = client->getEnv().getLocalPlayer();
3110 while (client->hasClientEvents()) {
3111 ClientEvent event = client->getClientEvent();
3113 switch (event.type) {
3114 case CE_PLAYER_DAMAGE:
3115 if (client->getHP() == 0)
3117 if (client->moddingEnabled()) {
3118 client->getScript()->on_damage_taken(event.player_damage.amount);
3121 runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3122 runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3124 player->hurt_tilt_timer = 1.5;
3125 player->hurt_tilt_strength =
3126 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3128 client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3131 case CE_PLAYER_FORCE_MOVE:
3132 cam->camera_yaw = event.player_force_move.yaw;
3133 cam->camera_pitch = event.player_force_move.pitch;
3136 case CE_DEATHSCREEN:
3137 // This should be enabled for death formspec in builtin
3138 client->getScript()->on_death();
3140 /* Handle visualization */
3141 runData.damage_flash = 0;
3142 player->hurt_tilt_timer = 0;
3143 player->hurt_tilt_strength = 0;
3146 case CE_SHOW_FORMSPEC:
3147 if (*(event.show_formspec.formspec) == "") {
3148 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3149 current_formspec->quitMenu();
3152 FormspecFormSource *fs_src =
3153 new FormspecFormSource(*(event.show_formspec.formspec));
3154 TextDestPlayerInventory *txt_dst =
3155 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3157 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3159 cur_formname = *(event.show_formspec.formname);
3162 delete event.show_formspec.formspec;
3163 delete event.show_formspec.formname;
3166 case CE_SHOW_LOCAL_FORMSPEC:
3168 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3169 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3170 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3173 delete event.show_formspec.formspec;
3174 delete event.show_formspec.formname;
3177 case CE_SPAWN_PARTICLE:
3178 case CE_ADD_PARTICLESPAWNER:
3179 case CE_DELETE_PARTICLESPAWNER:
3180 client->getParticleManager()->handleParticleEvent(&event, client,
3186 u32 id = event.hudadd.id;
3188 HudElement *e = player->getHud(id);
3191 delete event.hudadd.pos;
3192 delete event.hudadd.name;
3193 delete event.hudadd.scale;
3194 delete event.hudadd.text;
3195 delete event.hudadd.align;
3196 delete event.hudadd.offset;
3197 delete event.hudadd.world_pos;
3198 delete event.hudadd.size;
3203 e->type = (HudElementType)event.hudadd.type;
3204 e->pos = *event.hudadd.pos;
3205 e->name = *event.hudadd.name;
3206 e->scale = *event.hudadd.scale;
3207 e->text = *event.hudadd.text;
3208 e->number = event.hudadd.number;
3209 e->item = event.hudadd.item;
3210 e->dir = event.hudadd.dir;
3211 e->align = *event.hudadd.align;
3212 e->offset = *event.hudadd.offset;
3213 e->world_pos = *event.hudadd.world_pos;
3214 e->size = *event.hudadd.size;
3216 u32 new_id = player->addHud(e);
3217 //if this isn't true our huds aren't consistent
3218 sanity_check(new_id == id);
3221 delete event.hudadd.pos;
3222 delete event.hudadd.name;
3223 delete event.hudadd.scale;
3224 delete event.hudadd.text;
3225 delete event.hudadd.align;
3226 delete event.hudadd.offset;
3227 delete event.hudadd.world_pos;
3228 delete event.hudadd.size;
3233 HudElement *e = player->removeHud(event.hudrm.id);
3242 u32 id = event.hudchange.id;
3243 HudElement *e = player->getHud(id);
3246 delete event.hudchange.v3fdata;
3247 delete event.hudchange.v2fdata;
3248 delete event.hudchange.sdata;
3249 delete event.hudchange.v2s32data;
3253 switch (event.hudchange.stat) {
3255 e->pos = *event.hudchange.v2fdata;
3259 e->name = *event.hudchange.sdata;
3262 case HUD_STAT_SCALE:
3263 e->scale = *event.hudchange.v2fdata;
3267 e->text = *event.hudchange.sdata;
3270 case HUD_STAT_NUMBER:
3271 e->number = event.hudchange.data;
3275 e->item = event.hudchange.data;
3279 e->dir = event.hudchange.data;
3282 case HUD_STAT_ALIGN:
3283 e->align = *event.hudchange.v2fdata;
3286 case HUD_STAT_OFFSET:
3287 e->offset = *event.hudchange.v2fdata;
3290 case HUD_STAT_WORLD_POS:
3291 e->world_pos = *event.hudchange.v3fdata;
3295 e->size = *event.hudchange.v2s32data;
3300 delete event.hudchange.v3fdata;
3301 delete event.hudchange.v2fdata;
3302 delete event.hudchange.sdata;
3303 delete event.hudchange.v2s32data;
3307 sky->setVisible(false);
3308 // Whether clouds are visible in front of a custom skybox
3309 sky->setCloudsEnabled(event.set_sky.clouds);
3316 // Handle according to type
3317 if (*event.set_sky.type == "regular") {
3318 sky->setVisible(true);
3319 sky->setCloudsEnabled(true);
3320 } else if (*event.set_sky.type == "skybox" &&
3321 event.set_sky.params->size() == 6) {
3322 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3323 skybox = smgr->addSkyBoxSceneNode(
3324 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3325 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3326 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3327 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3328 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3329 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3331 // Handle everything else as plain color
3333 if (*event.set_sky.type != "plain")
3334 infostream << "Unknown sky type: "
3335 << (*event.set_sky.type) << std::endl;
3337 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3340 delete event.set_sky.bgcolor;
3341 delete event.set_sky.type;
3342 delete event.set_sky.params;
3345 case CE_OVERRIDE_DAY_NIGHT_RATIO:
3346 client->getEnv().setDayNightRatioOverride(
3347 event.override_day_night_ratio.do_override,
3348 event.override_day_night_ratio.ratio_f * 1000);
3351 case CE_CLOUD_PARAMS:
3353 clouds->setDensity(event.cloud_params.density);
3354 clouds->setColorBright(video::SColor(event.cloud_params.color_bright));
3355 clouds->setColorAmbient(video::SColor(event.cloud_params.color_ambient));
3356 clouds->setHeight(event.cloud_params.height);
3357 clouds->setThickness(event.cloud_params.thickness);
3358 clouds->setSpeed(v2f(
3359 event.cloud_params.speed_x,
3360 event.cloud_params.speed_y));
3365 // unknown or unhandled type
3373 void Game::updateCamera(u32 busy_time, f32 dtime)
3375 LocalPlayer *player = client->getEnv().getLocalPlayer();
3378 For interaction purposes, get info about the held item
3380 - Is it a usable item?
3381 - Can it point to liquids?
3383 ItemStack playeritem;
3385 InventoryList *mlist = local_inventory->getList("main");
3387 if (mlist && client->getPlayerItem() < mlist->getSize())
3388 playeritem = mlist->getItem(client->getPlayerItem());
3391 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3392 InventoryList *hlist = local_inventory->getList("hand");
3394 playeritem = hlist->getItem(0);
3398 ToolCapabilities playeritem_toolcap =
3399 playeritem.getToolCapabilities(itemdef_manager);
3401 v3s16 old_camera_offset = camera->getOffset();
3403 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3404 GenericCAO *playercao = player->getCAO();
3406 // If playercao not loaded, don't change camera
3407 if (playercao == NULL)
3410 camera->toggleCameraMode();
3412 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3413 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3416 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3417 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3419 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3420 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3422 camera->step(dtime);
3424 v3f camera_position = camera->getPosition();
3425 v3f camera_direction = camera->getDirection();
3426 f32 camera_fov = camera->getFovMax();
3427 v3s16 camera_offset = camera->getOffset();
3429 m_camera_offset_changed = (camera_offset != old_camera_offset);
3431 if (!flags.disable_camera_update) {
3432 client->getEnv().getClientMap().updateCamera(camera_position,
3433 camera_direction, camera_fov, camera_offset);
3435 if (m_camera_offset_changed) {
3436 client->updateCameraOffset(camera_offset);
3437 client->getEnv().updateCameraOffset(camera_offset);
3440 clouds->updateCameraOffset(camera_offset);
3446 void Game::updateSound(f32 dtime)
3448 // Update sound listener
3449 v3s16 camera_offset = camera->getOffset();
3450 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3451 v3f(0, 0, 0), // velocity
3452 camera->getDirection(),
3453 camera->getCameraNode()->getUpVector());
3454 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3456 LocalPlayer *player = client->getEnv().getLocalPlayer();
3458 // Tell the sound maker whether to make footstep sounds
3459 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3461 // Update sound maker
3462 if (player->makes_footstep_sound)
3463 soundmaker->step(dtime);
3465 ClientMap &map = client->getEnv().getClientMap();
3466 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3467 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3471 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3473 LocalPlayer *player = client->getEnv().getLocalPlayer();
3475 ItemStack playeritem;
3477 InventoryList *mlist = local_inventory->getList("main");
3479 if (mlist && client->getPlayerItem() < mlist->getSize())
3480 playeritem = mlist->getItem(client->getPlayerItem());
3483 const ItemDefinition &playeritem_def =
3484 playeritem.getDefinition(itemdef_manager);
3485 InventoryList *hlist = local_inventory->getList("hand");
3486 const ItemDefinition &hand_def =
3487 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3489 v3f player_position = player->getPosition();
3490 v3f camera_position = camera->getPosition();
3491 v3f camera_direction = camera->getDirection();
3492 v3s16 camera_offset = camera->getOffset();
3496 Calculate what block is the crosshair pointing to
3499 f32 d = playeritem_def.range; // max. distance
3500 f32 d_hand = hand_def.range;
3502 if (d < 0 && d_hand >= 0)
3507 core::line3d<f32> shootline;
3509 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3510 shootline = core::line3d<f32>(camera_position,
3511 camera_position + camera_direction * BS * d);
3513 // prevent player pointing anything in front-view
3514 shootline = core::line3d<f32>(camera_position,camera_position);
3517 #ifdef HAVE_TOUCHSCREENGUI
3519 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3520 shootline = g_touchscreengui->getShootline();
3521 shootline.start += intToFloat(camera_offset, BS);
3522 shootline.end += intToFloat(camera_offset, BS);
3527 PointedThing pointed = updatePointedThing(shootline,
3528 playeritem_def.liquids_pointable,
3529 !runData.ldown_for_dig,
3532 if (pointed != runData.pointed_old) {
3533 infostream << "Pointing at " << pointed.dump() << std::endl;
3534 hud->updateSelectionMesh(camera_offset);
3539 - releasing left mouse button
3540 - pointing away from node
3542 if (runData.digging) {
3543 if (getLeftReleased()) {
3544 infostream << "Left button released"
3545 << " (stopped digging)" << std::endl;
3546 runData.digging = false;
3547 } else if (pointed != runData.pointed_old) {
3548 if (pointed.type == POINTEDTHING_NODE
3549 && runData.pointed_old.type == POINTEDTHING_NODE
3550 && pointed.node_undersurface
3551 == runData.pointed_old.node_undersurface) {
3552 // Still pointing to the same node, but a different face.
3555 infostream << "Pointing away from node"
3556 << " (stopped digging)" << std::endl;
3557 runData.digging = false;
3558 hud->updateSelectionMesh(camera_offset);
3562 if (!runData.digging) {
3563 client->interact(1, runData.pointed_old);
3564 client->setCrack(-1, v3s16(0, 0, 0));
3565 runData.dig_time = 0.0;
3567 } else if (runData.dig_instantly && getLeftReleased()) {
3568 // Remove e.g. torches faster when clicking instead of holding LMB
3569 runData.nodig_delay_timer = 0;
3570 runData.dig_instantly = false;
3573 if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3574 runData.ldown_for_dig = false;
3577 runData.left_punch = false;
3579 soundmaker->m_player_leftpunch_sound.name = "";
3581 if (isRightPressed())
3582 runData.repeat_rightclick_timer += dtime;
3584 runData.repeat_rightclick_timer = 0;
3586 if (playeritem_def.usable && isLeftPressed()) {
3587 if (getLeftClicked() && (!client->moddingEnabled()
3588 || !client->getScript()->on_item_use(playeritem, pointed)))
3589 client->interact(4, pointed);
3590 } else if (pointed.type == POINTEDTHING_NODE) {
3591 ToolCapabilities playeritem_toolcap =
3592 playeritem.getToolCapabilities(itemdef_manager);
3593 if (playeritem.name.empty()) {
3594 playeritem_toolcap = *hand_def.tool_capabilities;
3596 handlePointingAtNode(pointed, playeritem_def, playeritem_toolcap, dtime);
3597 } else if (pointed.type == POINTEDTHING_OBJECT) {
3598 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3599 } else if (isLeftPressed()) {
3600 // When button is held down in air, show continuous animation
3601 runData.left_punch = true;
3602 } else if (getRightClicked()) {
3603 handlePointingAtNothing(playeritem);
3606 runData.pointed_old = pointed;
3608 if (runData.left_punch || getLeftClicked())
3609 camera->setDigging(0); // left click animation
3611 input->resetLeftClicked();
3612 input->resetRightClicked();
3614 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3615 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3617 input->resetLeftReleased();
3618 input->resetRightReleased();
3620 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3621 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3625 PointedThing Game::updatePointedThing(
3626 const core::line3d<f32> &shootline,
3627 bool liquids_pointable,
3628 bool look_for_object,
3629 const v3s16 &camera_offset)
3631 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3632 selectionboxes->clear();
3633 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3634 static const bool show_entity_selectionbox = g_settings->getBool(
3635 "show_entity_selectionbox");
3637 ClientMap &map = client->getEnv().getClientMap();
3638 INodeDefManager *nodedef=client->getNodeDefManager();
3640 runData.selected_object = NULL;
3642 PointedThing result=client->getEnv().getPointedThing(
3643 shootline, liquids_pointable, look_for_object);
3644 if (result.type == POINTEDTHING_OBJECT) {
3645 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3646 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox()) {
3647 aabb3f *selection_box = runData.selected_object->getSelectionBox();
3649 // Box should exist because object was
3650 // returned in the first place
3652 assert(selection_box);
3654 v3f pos = runData.selected_object->getPosition();
3655 selectionboxes->push_back(aabb3f(
3656 selection_box->MinEdge, selection_box->MaxEdge));
3657 selectionboxes->push_back(
3658 aabb3f(selection_box->MinEdge, selection_box->MaxEdge));
3659 hud->setSelectionPos(pos, camera_offset);
3661 } else if (result.type == POINTEDTHING_NODE) {
3662 // Update selection boxes
3663 MapNode n = map.getNodeNoEx(result.node_undersurface);
3664 std::vector<aabb3f> boxes;
3665 n.getSelectionBoxes(nodedef, &boxes,
3666 n.getNeighbors(result.node_undersurface, &map));
3669 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3670 i != boxes.end(); ++i) {
3672 box.MinEdge -= v3f(d, d, d);
3673 box.MaxEdge += v3f(d, d, d);
3674 selectionboxes->push_back(box);
3676 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3678 hud->setSelectedFaceNormal(v3f(
3679 result.intersection_normal.X,
3680 result.intersection_normal.Y,
3681 result.intersection_normal.Z));
3684 // Update selection mesh light level and vertex colors
3685 if (selectionboxes->size() > 0) {
3686 v3f pf = hud->getSelectionPos();
3687 v3s16 p = floatToInt(pf, BS);
3689 // Get selection mesh light level
3690 MapNode n = map.getNodeNoEx(p);
3691 u16 node_light = getInteriorLight(n, -1, nodedef);
3692 u16 light_level = node_light;
3694 for (u8 i = 0; i < 6; i++) {
3695 n = map.getNodeNoEx(p + g_6dirs[i]);
3696 node_light = getInteriorLight(n, -1, nodedef);
3697 if (node_light > light_level)
3698 light_level = node_light;
3701 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3703 final_color_blend(&c, light_level, daynight_ratio);
3705 // Modify final color a bit with time
3706 u32 timer = porting::getTimeMs() % 5000;
3707 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3708 float sin_r = 0.08 * sin(timerf);
3709 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3710 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3712 core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3714 core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3716 core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3718 // Set mesh final color
3719 hud->setSelectionMeshColor(c);
3725 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3727 infostream << "Right Clicked in Air" << std::endl;
3728 PointedThing fauxPointed;
3729 fauxPointed.type = POINTEDTHING_NOTHING;
3730 client->interact(5, fauxPointed);
3734 void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
3735 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3737 v3s16 nodepos = pointed.node_undersurface;
3738 v3s16 neighbourpos = pointed.node_abovesurface;
3741 Check information text of node
3744 ClientMap &map = client->getEnv().getClientMap();
3745 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3748 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3750 MapNode n = map.getNodeNoEx(nodepos);
3752 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3753 infotext = L"Unknown node: ";
3754 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3758 if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3759 && client->checkPrivilege("interact")) {
3760 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3763 if ((getRightClicked() ||
3764 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3765 client->checkPrivilege("interact")) {
3766 runData.repeat_rightclick_timer = 0;
3767 infostream << "Ground right-clicked" << std::endl;
3769 if (meta && meta->getString("formspec") != "" && !random_input
3770 && !isKeyDown(KeyType::SNEAK)) {
3771 infostream << "Launching custom inventory view" << std::endl;
3773 InventoryLocation inventoryloc;
3774 inventoryloc.setNodeMeta(nodepos);
3776 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3777 &client->getEnv().getClientMap(), nodepos);
3778 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3780 create_formspec_menu(¤t_formspec, client,
3781 device, &input->joystick, fs_src, txt_dst);
3784 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3786 // Report right click to server
3788 camera->setDigging(1); // right click animation (always shown for feedback)
3790 // If the wielded item has node placement prediction,
3792 bool placed = nodePlacementPrediction(*client,
3794 nodepos, neighbourpos);
3798 client->interact(3, pointed);
3800 soundmaker->m_player_rightpunch_sound =
3801 playeritem_def.sound_place;
3803 if (client->moddingEnabled())
3804 client->getScript()->on_placenode(pointed, playeritem_def);
3806 soundmaker->m_player_rightpunch_sound =
3809 if (playeritem_def.node_placement_prediction == "" ||
3810 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3811 client->interact(3, pointed); // Report to server
3813 soundmaker->m_player_rightpunch_sound =
3814 playeritem_def.sound_place_failed;
3822 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3823 const v3f &player_position, bool show_debug)
3825 infotext = unescape_enriched(
3826 utf8_to_wide(runData.selected_object->infoText()));
3829 if (infotext != L"") {
3832 infotext += unescape_enriched(utf8_to_wide(
3833 runData.selected_object->debugInfoText()));
3836 if (isLeftPressed()) {
3837 bool do_punch = false;
3838 bool do_punch_damage = false;
3840 if (runData.object_hit_delay_timer <= 0.0) {
3842 do_punch_damage = true;
3843 runData.object_hit_delay_timer = object_hit_delay;
3846 if (getLeftClicked())
3850 infostream << "Left-clicked object" << std::endl;
3851 runData.left_punch = true;
3854 if (do_punch_damage) {
3855 // Report direct punch
3856 v3f objpos = runData.selected_object->getPosition();
3857 v3f dir = (objpos - player_position).normalize();
3858 ItemStack item = playeritem;
3859 if (playeritem.name.empty()) {
3860 InventoryList *hlist = local_inventory->getList("hand");
3862 item = hlist->getItem(0);
3866 bool disable_send = runData.selected_object->directReportPunch(
3867 dir, &item, runData.time_from_last_punch);
3868 runData.time_from_last_punch = 0;
3871 client->interact(0, pointed);
3873 } else if (getRightClicked()) {
3874 infostream << "Right-clicked object" << std::endl;
3875 client->interact(3, pointed); // place
3880 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3881 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3883 LocalPlayer *player = client->getEnv().getLocalPlayer();
3884 ClientMap &map = client->getEnv().getClientMap();
3885 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3887 // NOTE: Similar piece of code exists on the server side for
3889 // Get digging parameters
3890 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3891 &playeritem_toolcap);
3893 // If can't dig, try hand
3894 if (!params.diggable) {
3895 InventoryList *hlist = local_inventory->getList("hand");
3896 const ItemDefinition &hand =
3897 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3898 const ToolCapabilities *tp = hand.tool_capabilities;
3901 params = getDigParams(nodedef_manager->get(n).groups, tp);
3904 if (!runData.digging) {
3905 infostream << "Started digging" << std::endl;
3906 runData.dig_instantly = params.time == 0;
3907 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3909 client->interact(0, pointed);
3910 runData.digging = true;
3911 runData.ldown_for_dig = true;
3914 if (!params.diggable) {
3915 // I guess nobody will wait for this long
3916 runData.dig_time_complete = 10000000.0;
3918 runData.dig_time_complete = params.time;
3920 if (m_cache_enable_particles) {
3921 const ContentFeatures &features =
3922 client->getNodeDefManager()->get(n);
3923 client->getParticleManager()->addPunchingParticles(client, smgr,
3924 player, nodepos, n, features);
3928 if (!runData.dig_instantly) {
3929 runData.dig_index = (float)crack_animation_length
3931 / runData.dig_time_complete;
3933 // This is for e.g. torches
3934 runData.dig_index = crack_animation_length;
3937 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3939 if (sound_dig.exists() && params.diggable) {
3940 if (sound_dig.name == "__group") {
3941 if (params.main_group != "") {
3942 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3943 soundmaker->m_player_leftpunch_sound.name =
3944 std::string("default_dig_") +
3948 soundmaker->m_player_leftpunch_sound = sound_dig;
3952 // Don't show cracks if not diggable
3953 if (runData.dig_time_complete >= 100000.0) {
3954 } else if (runData.dig_index < crack_animation_length) {
3955 //TimeTaker timer("client.setTempMod");
3956 //infostream<<"dig_index="<<dig_index<<std::endl;
3957 client->setCrack(runData.dig_index, nodepos);
3959 infostream << "Digging completed" << std::endl;
3960 client->setCrack(-1, v3s16(0, 0, 0));
3962 runData.dig_time = 0;
3963 runData.digging = false;
3965 runData.nodig_delay_timer =
3966 runData.dig_time_complete / (float)crack_animation_length;
3968 // We don't want a corresponding delay to very time consuming nodes
3969 // and nodes without digging time (e.g. torches) get a fixed delay.
3970 if (runData.nodig_delay_timer > 0.3)
3971 runData.nodig_delay_timer = 0.3;
3972 else if (runData.dig_instantly)
3973 runData.nodig_delay_timer = 0.15;
3975 bool is_valid_position;
3976 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3977 if (is_valid_position) {
3978 if (client->moddingEnabled()) {
3979 if (client->getScript()->on_dignode(nodepos, wasnode)) {
3983 client->removeNode(nodepos);
3986 client->interact(2, pointed);
3988 if (m_cache_enable_particles) {
3989 const ContentFeatures &features =
3990 client->getNodeDefManager()->get(wasnode);
3991 client->getParticleManager()->addDiggingParticles(client, smgr,
3992 player, nodepos, wasnode, features);
3996 // Send event to trigger sound
3997 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3998 client->event()->put(e);
4001 if (runData.dig_time_complete < 100000.0) {
4002 runData.dig_time += dtime;
4004 runData.dig_time = 0;
4005 client->setCrack(-1, nodepos);
4008 camera->setDigging(0); // left click animation
4012 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
4013 const CameraOrientation &cam)
4015 LocalPlayer *player = client->getEnv().getLocalPlayer();
4021 if (draw_control->range_all) {
4022 runData.fog_range = 100000 * BS;
4024 runData.fog_range = draw_control->wanted_range * BS;
4028 Calculate general brightness
4030 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4031 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4032 float direct_brightness;
4035 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4036 direct_brightness = time_brightness;
4037 sunlight_seen = true;
4039 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4040 float old_brightness = sky->getBrightness();
4041 direct_brightness = client->getEnv().getClientMap()
4042 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
4043 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4047 float time_of_day_smooth = runData.time_of_day_smooth;
4048 float time_of_day = client->getEnv().getTimeOfDayF();
4050 static const float maxsm = 0.05;
4051 static const float todsm = 0.05;
4053 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4054 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4055 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4056 time_of_day_smooth = time_of_day;
4058 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4059 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4060 + (time_of_day + 1.0) * todsm;
4062 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4063 + time_of_day * todsm;
4065 runData.time_of_day = time_of_day;
4066 runData.time_of_day_smooth = time_of_day_smooth;
4068 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4069 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4070 player->getPitch());
4076 v3f player_position = player->getPosition();
4077 if (sky->getCloudsVisible()) {
4078 clouds->setVisible(true);
4079 clouds->step(dtime);
4080 clouds->update(v2f(player_position.X, player_position.Z),
4081 sky->getCloudColor());
4083 clouds->setVisible(false);
4090 client->getParticleManager()->step(dtime);
4096 if (m_cache_enable_fog && !flags.force_fog_off) {
4099 video::EFT_FOG_LINEAR,
4100 runData.fog_range * m_cache_fog_start,
4101 runData.fog_range * 1.0,
4109 video::EFT_FOG_LINEAR,
4119 Get chat messages from client
4122 v2u32 screensize = driver->getScreenSize();
4124 updateChat(*client, dtime, flags.show_debug, screensize,
4125 flags.show_chat, runData.profiler_current_page,
4126 *chat_backend, guitext_chat);
4132 if (client->getPlayerItem() != runData.new_playeritem)
4133 client->selectPlayerItem(runData.new_playeritem);
4135 // Update local inventory if it has changed
4136 if (client->getLocalInventoryUpdated()) {
4137 //infostream<<"Updating local inventory"<<std::endl;
4138 client->getLocalInventory(*local_inventory);
4139 runData.update_wielded_item_trigger = true;
4142 if (runData.update_wielded_item_trigger) {
4143 // Update wielded tool
4144 InventoryList *mlist = local_inventory->getList("main");
4146 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4147 ItemStack item = mlist->getItem(client->getPlayerItem());
4148 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4149 InventoryList *hlist = local_inventory->getList("hand");
4151 item = hlist->getItem(0);
4153 camera->wield(item);
4156 runData.update_wielded_item_trigger = false;
4160 Update block draw list every 200ms or when camera direction has
4163 runData.update_draw_list_timer += dtime;
4165 v3f camera_direction = camera->getDirection();
4166 if (runData.update_draw_list_timer >= 0.2
4167 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4168 || m_camera_offset_changed) {
4169 runData.update_draw_list_timer = 0;
4170 client->getEnv().getClientMap().updateDrawList(driver);
4171 runData.update_draw_list_last_cam_dir = camera_direction;
4174 updateGui(*stats, dtime, cam);
4177 make sure menu is on top
4178 1. Delete formspec menu reference if menu was removed
4179 2. Else, make sure formspec menu is on top
4181 if (current_formspec) {
4182 if (current_formspec->getReferenceCount() == 1) {
4183 current_formspec->drop();
4184 current_formspec = NULL;
4185 } else if (!noMenuActive()) {
4186 guiroot->bringToFront(current_formspec);
4194 const video::SColor &skycolor = sky->getSkyColor();
4196 TimeTaker tt_draw("mainloop: draw");
4197 driver->beginScene(true, true, skycolor);
4199 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4200 guienv, screensize, skycolor, flags.show_hud,
4201 flags.show_minimap);
4206 if (flags.show_profiler_graph)
4207 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4212 if (runData.damage_flash > 0.0) {
4213 video::SColor color(runData.damage_flash, 180, 0, 0);
4214 driver->draw2DRectangle(color,
4215 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4218 runData.damage_flash -= 100.0 * dtime;
4224 if (player->hurt_tilt_timer > 0.0) {
4225 player->hurt_tilt_timer -= dtime * 5;
4227 if (player->hurt_tilt_timer < 0)
4228 player->hurt_tilt_strength = 0;
4232 Update minimap pos and rotation
4234 if (flags.show_minimap && flags.show_hud) {
4235 mapper->setPos(floatToInt(player->getPosition(), BS));
4236 mapper->setAngle(player->getYaw());
4244 stats->drawtime = tt_draw.stop(true);
4245 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4249 inline static const char *yawToDirectionString(int yaw)
4251 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4253 yaw = wrapDegrees_0_360(yaw);
4254 yaw = (yaw + 45) % 360 / 90;
4256 return direction[yaw];
4260 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4262 v2u32 screensize = driver->getScreenSize();
4263 LocalPlayer *player = client->getEnv().getLocalPlayer();
4264 v3f player_position = player->getPosition();
4266 if (flags.show_debug) {
4267 static float drawtime_avg = 0;
4268 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4270 u16 fps = 1.0 / stats.dtime_jitter.avg;
4272 std::ostringstream os(std::ios_base::binary);
4274 << PROJECT_NAME_C " " << g_version_hash
4276 << " (R: range_all=" << draw_control->range_all << ")"
4277 << std::setprecision(0)
4278 << " drawtime = " << drawtime_avg
4279 << std::setprecision(1)
4280 << ", dtime_jitter = "
4281 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4282 << std::setprecision(1)
4283 << ", v_range = " << draw_control->wanted_range
4284 << std::setprecision(3)
4285 << ", RTT = " << client->getRTT();
4286 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4287 guitext->setVisible(true);
4289 guitext->setVisible(false);
4292 if (guitext->isVisible()) {
4293 core::rect<s32> rect(
4295 screensize.X, 5 + g_fontengine->getTextHeight()
4297 guitext->setRelativePosition(rect);
4300 if (flags.show_debug) {
4301 std::ostringstream os(std::ios_base::binary);
4302 os << std::setprecision(1) << std::fixed
4303 << "(" << (player_position.X / BS)
4304 << ", " << (player_position.Y / BS)
4305 << ", " << (player_position.Z / BS)
4306 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4307 << " " << yawToDirectionString(cam.camera_yaw)
4308 << ") (seed = " << ((u64)client->getMapSeed())
4311 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4312 ClientMap &map = client->getEnv().getClientMap();
4313 const INodeDefManager *nodedef = client->getNodeDefManager();
4314 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4315 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4316 const ContentFeatures &features = nodedef->get(n);
4317 os << " (pointing_at = " << nodedef->get(n).name
4318 << " - " << features.tiledef[0].name.c_str()
4323 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4324 guitext2->setVisible(true);
4326 core::rect<s32> rect(
4327 5, 5 + g_fontengine->getTextHeight(),
4328 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4330 guitext2->setRelativePosition(rect);
4332 guitext2->setVisible(false);
4335 setStaticText(guitext_info, infotext.c_str());
4336 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4338 float statustext_time_max = 1.5;
4340 if (!m_statustext.empty()) {
4341 runData.statustext_time += dtime;
4343 if (runData.statustext_time >= statustext_time_max) {
4345 runData.statustext_time = 0;
4349 setStaticText(guitext_status, m_statustext.c_str());
4350 guitext_status->setVisible(!m_statustext.empty());
4352 if (!m_statustext.empty()) {
4353 s32 status_width = guitext_status->getTextWidth();
4354 s32 status_height = guitext_status->getTextHeight();
4355 s32 status_y = screensize.Y - 150;
4356 s32 status_x = (screensize.X - status_width) / 2;
4357 core::rect<s32> rect(
4358 status_x , status_y - status_height,
4359 status_x + status_width, status_y
4361 guitext_status->setRelativePosition(rect);
4364 video::SColor initial_color(255, 0, 0, 0);
4366 if (guienv->getSkin())
4367 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4369 video::SColor final_color = initial_color;
4370 final_color.setAlpha(0);
4371 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4372 initial_color, final_color,
4373 pow(runData.statustext_time / statustext_time_max, 2.0f));
4374 guitext_status->setOverrideColor(fade_color);
4375 guitext_status->enableOverrideColor(true);
4380 /* Log times and stuff for visualization */
4381 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4383 Profiler::GraphValues values;
4384 g_profiler->graphGet(values);
4390 /****************************************************************************
4392 ****************************************************************************/
4394 /* On some computers framerate doesn't seem to be automatically limited
4396 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4398 // not using getRealTime is necessary for wine
4399 device->getTimer()->tick(); // Maker sure device time is up-to-date
4400 u32 time = device->getTimer()->getTime();
4401 u32 last_time = fps_timings->last_time;
4403 if (time > last_time) // Make sure time hasn't overflowed
4404 fps_timings->busy_time = time - last_time;
4406 fps_timings->busy_time = 0;
4408 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4409 ? g_settings->getFloat("pause_fps_max")
4410 : g_settings->getFloat("fps_max"));
4412 if (fps_timings->busy_time < frametime_min) {
4413 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4414 device->sleep(fps_timings->sleep_time);
4416 fps_timings->sleep_time = 0;
4419 /* Get the new value of the device timer. Note that device->sleep() may
4420 * not sleep for the entire requested time as sleep may be interrupted and
4421 * therefore it is arguably more accurate to get the new time from the
4422 * device rather than calculating it by adding sleep_time to time.
4425 device->getTimer()->tick(); // Update device timer
4426 time = device->getTimer()->getTime();
4428 if (time > last_time) // Make sure last_time hasn't overflowed
4429 *dtime = (time - last_time) / 1000.0;
4433 fps_timings->last_time = time;
4436 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4437 // pass a copy of it to this function
4438 // Note: \p msg must be allocated using new (not malloc())
4439 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4440 int percent, bool draw_clouds)
4442 draw_load_screen(msg, device, guienv, texture_src, dtime, percent,
4447 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4449 ((Game *)data)->readSettings();
4452 void Game::readSettings()
4454 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4455 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4456 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4457 m_cache_enable_particles = g_settings->getBool("enable_particles");
4458 m_cache_enable_fog = g_settings->getBool("enable_fog");
4459 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4460 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4461 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4463 m_cache_enable_noclip = g_settings->getBool("noclip");
4464 m_cache_enable_free_move = g_settings->getBool("free_move");
4466 m_cache_fog_start = g_settings->getFloat("fog_start");
4468 m_cache_cam_smoothing = 0;
4469 if (g_settings->getBool("cinematic"))
4470 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4472 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4474 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4475 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4476 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4480 /****************************************************************************/
4481 /****************************************************************************
4483 ****************************************************************************/
4484 /****************************************************************************/
4486 void Game::extendedResourceCleanup()
4488 // Extended resource accounting
4489 infostream << "Irrlicht resources after cleanup:" << std::endl;
4490 infostream << "\tRemaining meshes : "
4491 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4492 infostream << "\tRemaining textures : "
4493 << driver->getTextureCount() << std::endl;
4495 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4496 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4497 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4501 clearTextureNameCache();
4502 infostream << "\tRemaining materials: "
4503 << driver-> getMaterialRendererCount()
4504 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4507 void Game::showPauseMenu()
4510 static const std::string control_text = strgettext("Default Controls:\n"
4511 "No menu visible:\n"
4512 "- single tap: button activate\n"
4513 "- double tap: place/use\n"
4514 "- slide finger: look around\n"
4515 "Menu/Inventory visible:\n"
4516 "- double tap (outside):\n"
4518 "- touch stack, touch slot:\n"
4520 "- touch&drag, tap 2nd finger\n"
4521 " --> place single item to slot\n"
4524 static const std::string control_text = strgettext("Default Controls:\n"
4526 "- Space: jump/climb\n"
4527 "- Shift: sneak/go down\n"
4530 "- Mouse: turn/look\n"
4531 "- Mouse left: dig/punch\n"
4532 "- Mouse right: place/use\n"
4533 "- Mouse wheel: select item\n"
4538 float ypos = simple_singleplayer_mode ? 0.5 : 0.1;
4539 std::ostringstream os;
4541 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4542 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4543 << strgettext("Continue") << "]";
4545 if (!simple_singleplayer_mode) {
4546 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4547 << strgettext("Change Password") << "]";
4551 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4552 << strgettext("Sound Volume") << "]";
4553 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4554 << strgettext("Change Keys") << "]";
4556 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4557 << strgettext("Exit to Menu") << "]";
4558 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4559 << strgettext("Exit to OS") << "]"
4560 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4561 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
4562 << g_build_info << "\n"
4563 << "path_user = " << wrap_rows(porting::path_user, 20)
4567 /* Note: FormspecFormSource and LocalFormspecHandler *
4568 * are deleted by guiFormSpecMenu */
4569 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4570 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4572 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
4573 current_formspec->setFocus("btn_continue");
4574 current_formspec->doPause = true;
4577 /****************************************************************************/
4578 /****************************************************************************
4579 extern function for launching the game
4580 ****************************************************************************/
4581 /****************************************************************************/
4583 void the_game(bool *kill,
4585 InputHandler *input,
4586 IrrlichtDevice *device,
4588 const std::string &map_dir,
4589 const std::string &playername,
4590 const std::string &password,
4591 const std::string &address, // If empty local server is created
4594 std::string &error_message,
4595 ChatBackend &chat_backend,
4596 bool *reconnect_requested,
4597 const SubgameSpec &gamespec, // Used for local game
4598 bool simple_singleplayer_mode)
4602 /* Make a copy of the server address because if a local singleplayer server
4603 * is created then this is updated and we don't want to change the value
4604 * passed to us by the calling function
4606 std::string server_address = address;
4610 if (game.startup(kill, random_input, input, device, map_dir,
4611 playername, password, &server_address, port, error_message,
4612 reconnect_requested, &chat_backend, gamespec,
4613 simple_singleplayer_mode)) {
4618 } catch (SerializationError &e) {
4619 error_message = std::string("A serialization error occurred:\n")
4620 + e.what() + "\n\nThe server is probably "
4621 " running a different version of " PROJECT_NAME_C ".";
4622 errorstream << error_message << std::endl;
4623 } catch (ServerError &e) {
4624 error_message = e.what();
4625 errorstream << "ServerError: " << error_message << std::endl;
4626 } catch (ModError &e) {
4627 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4628 errorstream << "ModError: " << error_message << std::endl;