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 float m_player_step_timer;
481 SimpleSoundSpec m_player_step_sound;
482 SimpleSoundSpec m_player_leftpunch_sound;
483 SimpleSoundSpec m_player_rightpunch_sound;
485 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
488 m_player_step_timer(0)
492 void playPlayerStep()
494 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
495 m_player_step_timer = 0.03;
496 m_sound->playSound(m_player_step_sound, false);
500 static void viewBobbingStep(MtEvent *e, void *data)
502 SoundMaker *sm = (SoundMaker *)data;
503 sm->playPlayerStep();
506 static void playerRegainGround(MtEvent *e, void *data)
508 SoundMaker *sm = (SoundMaker *)data;
509 sm->playPlayerStep();
512 static void playerJump(MtEvent *e, void *data)
514 //SoundMaker *sm = (SoundMaker*)data;
517 static void cameraPunchLeft(MtEvent *e, void *data)
519 SoundMaker *sm = (SoundMaker *)data;
520 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
523 static void cameraPunchRight(MtEvent *e, void *data)
525 SoundMaker *sm = (SoundMaker *)data;
526 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
529 static void nodeDug(MtEvent *e, void *data)
531 SoundMaker *sm = (SoundMaker *)data;
532 NodeDugEvent *nde = (NodeDugEvent *)e;
533 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
536 static void playerDamage(MtEvent *e, void *data)
538 SoundMaker *sm = (SoundMaker *)data;
539 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
542 static void playerFallingDamage(MtEvent *e, void *data)
544 SoundMaker *sm = (SoundMaker *)data;
545 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
548 void registerReceiver(MtEventManager *mgr)
550 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
551 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
552 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
553 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
554 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
555 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
556 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
557 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
560 void step(float dtime)
562 m_player_step_timer -= dtime;
566 // Locally stored sounds don't need to be preloaded because of this
567 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
569 std::set<std::string> m_fetched;
571 void paths_insert(std::set<std::string> &dst_paths,
572 const std::string &base,
573 const std::string &name)
575 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
576 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
577 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
578 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
579 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
580 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
581 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
582 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
583 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
584 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
585 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
588 void fetchSounds(const std::string &name,
589 std::set<std::string> &dst_paths,
590 std::set<std::string> &dst_datas)
592 if (m_fetched.count(name))
595 m_fetched.insert(name);
597 paths_insert(dst_paths, porting::path_share, name);
598 paths_insert(dst_paths, porting::path_user, name);
603 // before 1.8 there isn't a "integer interface", only float
604 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
605 typedef f32 SamplerLayer_t;
607 typedef s32 SamplerLayer_t;
611 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
614 bool *m_force_fog_off;
617 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
618 CachedPixelShaderSetting<float> m_fog_distance;
619 CachedVertexShaderSetting<float> m_animation_timer_vertex;
620 CachedPixelShaderSetting<float> m_animation_timer_pixel;
621 CachedPixelShaderSetting<float, 3> m_day_light;
622 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
623 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
624 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
625 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
626 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
627 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
631 void onSettingsChange(const std::string &name)
633 if (name == "enable_fog")
634 m_fog_enabled = g_settings->getBool("enable_fog");
637 static void settingsCallback(const std::string &name, void *userdata)
639 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
642 void setSky(Sky *sky) { m_sky = sky; }
644 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
645 f32 *fog_range, Client *client) :
647 m_force_fog_off(force_fog_off),
648 m_fog_range(fog_range),
649 m_sky_bg_color("skyBgColor"),
650 m_fog_distance("fogDistance"),
651 m_animation_timer_vertex("animationTimer"),
652 m_animation_timer_pixel("animationTimer"),
653 m_day_light("dayLight"),
654 m_eye_position_pixel("eyePosition"),
655 m_eye_position_vertex("eyePosition"),
656 m_minimap_yaw("yawVec"),
657 m_base_texture("baseTexture"),
658 m_normal_texture("normalTexture"),
659 m_texture_flags("textureFlags"),
662 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
663 m_fog_enabled = g_settings->getBool("enable_fog");
666 ~GameGlobalShaderConstantSetter()
668 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
671 virtual void onSetConstants(video::IMaterialRendererServices *services,
678 video::SColor bgcolor = m_sky->getBgColor();
679 video::SColorf bgcolorf(bgcolor);
680 float bgcolorfa[4] = {
686 m_sky_bg_color.set(bgcolorfa, services);
689 float fog_distance = 10000 * BS;
691 if (m_fog_enabled && !*m_force_fog_off)
692 fog_distance = *m_fog_range;
694 m_fog_distance.set(&fog_distance, services);
696 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
697 video::SColorf sunlight;
698 get_sunlight_color(&sunlight, daynight_ratio);
703 m_day_light.set(dnc, services);
705 u32 animation_timer = porting::getTimeMs() % 100000;
706 float animation_timer_f = (float)animation_timer / 100000.f;
707 m_animation_timer_vertex.set(&animation_timer_f, services);
708 m_animation_timer_pixel.set(&animation_timer_f, services);
710 float eye_position_array[3];
711 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
712 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
713 eye_position_array[0] = epos.X;
714 eye_position_array[1] = epos.Y;
715 eye_position_array[2] = epos.Z;
717 epos.getAs3Values(eye_position_array);
719 m_eye_position_pixel.set(eye_position_array, services);
720 m_eye_position_vertex.set(eye_position_array, services);
722 float minimap_yaw_array[3];
723 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
724 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
725 minimap_yaw_array[0] = minimap_yaw.X;
726 minimap_yaw_array[1] = minimap_yaw.Y;
727 minimap_yaw_array[2] = minimap_yaw.Z;
729 minimap_yaw.getAs3Values(minimap_yaw_array);
731 m_minimap_yaw.set(minimap_yaw_array, services);
733 SamplerLayer_t base_tex = 0,
736 m_base_texture.set(&base_tex, services);
737 m_normal_texture.set(&normal_tex, services);
738 m_texture_flags.set(&flags_tex, services);
743 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
746 bool *m_force_fog_off;
749 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
751 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
752 f32 *fog_range, Client *client) :
754 m_force_fog_off(force_fog_off),
755 m_fog_range(fog_range),
759 void setSky(Sky *sky) {
761 for (size_t i = 0; i < created_nosky.size(); ++i) {
762 created_nosky[i]->setSky(m_sky);
764 created_nosky.clear();
767 virtual IShaderConstantSetter* create()
769 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
770 m_sky, m_force_fog_off, m_fog_range, m_client);
772 created_nosky.push_back(scs);
778 bool nodePlacementPrediction(Client &client,
779 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
781 std::string prediction = playeritem_def.node_placement_prediction;
782 INodeDefManager *nodedef = client.ndef();
783 ClientMap &map = client.getEnv().getClientMap();
785 bool is_valid_position;
787 node = map.getNodeNoEx(nodepos, &is_valid_position);
788 if (!is_valid_position)
791 if (prediction != "" && !nodedef->get(node).rightclickable) {
792 verbosestream << "Node placement prediction for "
793 << playeritem_def.name << " is "
794 << prediction << std::endl;
795 v3s16 p = neighbourpos;
797 // Place inside node itself if buildable_to
798 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
799 if (is_valid_position)
801 if (nodedef->get(n_under).buildable_to)
804 node = map.getNodeNoEx(p, &is_valid_position);
805 if (is_valid_position &&!nodedef->get(node).buildable_to)
810 // Find id of predicted node
812 bool found = nodedef->getId(prediction, id);
815 errorstream << "Node placement prediction failed for "
816 << playeritem_def.name << " (places "
818 << ") - Name not known" << std::endl;
822 // Predict param2 for facedir and wallmounted nodes
825 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
826 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED) {
827 v3s16 dir = nodepos - neighbourpos;
829 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
830 param2 = dir.Y < 0 ? 1 : 0;
831 } else if (abs(dir.X) > abs(dir.Z)) {
832 param2 = dir.X < 0 ? 3 : 2;
834 param2 = dir.Z < 0 ? 5 : 4;
838 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR ||
839 nodedef->get(id).param_type_2 == CPT2_COLORED_FACEDIR) {
840 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
842 if (abs(dir.X) > abs(dir.Z)) {
843 param2 = dir.X < 0 ? 3 : 1;
845 param2 = dir.Z < 0 ? 2 : 0;
851 //Check attachment if node is in group attached_node
852 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
853 static v3s16 wallmounted_dirs[8] = {
863 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
864 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED)
865 pp = p + wallmounted_dirs[param2];
867 pp = p + v3s16(0, -1, 0);
869 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
873 // Add node to client map
874 MapNode n(id, 0, param2);
877 LocalPlayer *player = client.getEnv().getLocalPlayer();
879 // Dont place node when player would be inside new node
880 // NOTE: This is to be eventually implemented by a mod as client-side Lua
881 if (!nodedef->get(n).walkable ||
882 g_settings->getBool("enable_build_where_you_stand") ||
883 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
884 (nodedef->get(n).walkable &&
885 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
886 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
888 // This triggers the required mesh update too
889 client.addNode(p, n);
892 } catch (InvalidPositionException &e) {
893 errorstream << "Node placement prediction failed for "
894 << playeritem_def.name << " (places "
896 << ") - Position not loaded" << std::endl;
903 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
904 Client *client, IrrlichtDevice *device, JoystickController *joystick,
905 IFormSource *fs_src, TextDest *txt_dest)
908 if (*cur_formspec == 0) {
909 *cur_formspec = new GUIFormSpecMenu(device, joystick,
910 guiroot, -1, &g_menumgr, client, client->getTextureSource(),
912 (*cur_formspec)->doPause = false;
915 Caution: do not call (*cur_formspec)->drop() here --
916 the reference might outlive the menu, so we will
917 periodically check if *cur_formspec is the only
918 remaining reference (i.e. the menu was removed)
919 and delete it in that case.
923 (*cur_formspec)->setFormSource(fs_src);
924 (*cur_formspec)->setTextDest(txt_dest);
930 #define SIZE_TAG "size[11,5.5]"
932 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
935 /******************************************************************************/
936 static void updateChat(Client &client, f32 dtime, bool show_debug,
937 const v2u32 &screensize, bool show_chat, u32 show_profiler,
938 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
940 // Add chat log output for errors to be shown in chat
941 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
943 // Get new messages from error log buffer
944 while (!chat_log_error_buf.empty()) {
945 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
946 if (!g_settings->getBool("disable_escape_sequences")) {
947 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
949 chat_backend.addMessage(L"", error_message);
952 // Get new messages from client
953 std::wstring message;
955 while (client.getChatMessage(message)) {
956 chat_backend.addUnparsedMessage(message);
959 // Remove old messages
960 chat_backend.step(dtime);
962 // Display all messages in a static text element
963 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
964 EnrichedString recent_chat = chat_backend.getRecentChat();
965 unsigned int line_height = g_fontengine->getLineHeight();
967 setStaticText(guitext_chat, recent_chat);
969 // Update gui element size and position
973 chat_y += 2 * line_height;
975 // first pass to calculate height of text to be set
976 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
977 porting::getWindowSize().X - 20);
978 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
979 guitext_chat->setRelativePosition(rect);
981 //now use real height of text and adjust rect according to this size
982 rect = core::rect<s32>(10, chat_y, width,
983 chat_y + guitext_chat->getTextHeight());
986 guitext_chat->setRelativePosition(rect);
987 // Don't show chat if disabled or empty or profiler is enabled
988 guitext_chat->setVisible(
989 show_chat && recent_chat_count != 0 && !show_profiler);
993 /****************************************************************************
994 Fast key cache for main game loop
995 ****************************************************************************/
997 /* This is faster than using getKeySetting with the tradeoff that functions
998 * using it must make sure that it's initialised before using it and there is
999 * no error handling (for example bounds checking). This is really intended for
1000 * use only in the main running loop of the client (the_game()) where the faster
1001 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1002 * (e.g. formspecs) should continue using getKeySetting().
1010 populate_nonchanging();
1015 // Keys that are not settings dependent
1016 void populate_nonchanging();
1018 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1019 InputHandler *handler;
1022 void KeyCache::populate_nonchanging()
1024 key[KeyType::ESC] = EscapeKey;
1027 void KeyCache::populate()
1029 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1030 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1031 key[KeyType::LEFT] = getKeySetting("keymap_left");
1032 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1033 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1034 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1035 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1037 key[KeyType::AUTORUN] = getKeySetting("keymap_autorun");
1039 key[KeyType::DROP] = getKeySetting("keymap_drop");
1040 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1041 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1042 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1043 key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
1044 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1045 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1046 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1047 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1048 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1049 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1050 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1051 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1052 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1053 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1054 = getKeySetting("keymap_toggle_force_fog_off");
1055 key[KeyType::TOGGLE_UPDATE_CAMERA]
1056 = getKeySetting("keymap_toggle_update_camera");
1057 key[KeyType::TOGGLE_DEBUG]
1058 = getKeySetting("keymap_toggle_debug");
1059 key[KeyType::TOGGLE_PROFILER]
1060 = getKeySetting("keymap_toggle_profiler");
1061 key[KeyType::CAMERA_MODE]
1062 = getKeySetting("keymap_camera_mode");
1063 key[KeyType::INCREASE_VIEWING_RANGE]
1064 = getKeySetting("keymap_increase_viewing_range_min");
1065 key[KeyType::DECREASE_VIEWING_RANGE]
1066 = getKeySetting("keymap_decrease_viewing_range_min");
1067 key[KeyType::RANGESELECT]
1068 = getKeySetting("keymap_rangeselect");
1069 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1071 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1072 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1073 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1074 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1076 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1079 // First clear all keys, then re-add the ones we listen for
1080 handler->dontListenForKeys();
1081 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1082 handler->listenForKey(key[i]);
1084 handler->listenForKey(EscapeKey);
1085 handler->listenForKey(CancelKey);
1086 for (size_t i = 0; i < 10; i++) {
1087 handler->listenForKey(NumberKey[i]);
1093 /****************************************************************************
1095 ****************************************************************************/
1097 const float object_hit_delay = 0.2;
1100 u32 last_time, busy_time, sleep_time;
1104 /* The reason the following structs are not anonymous structs within the
1105 * class is that they are not used by the majority of member functions and
1106 * many functions that do require objects of thse types do not modify them
1107 * (so they can be passed as a const qualified parameter)
1109 struct CameraOrientation {
1110 f32 camera_yaw; // "right/left"
1111 f32 camera_pitch; // "up/down"
1114 struct GameRunData {
1117 PointedThing pointed_old;
1122 bool update_wielded_item_trigger;
1123 bool reset_jump_timer;
1124 float nodig_delay_timer;
1126 float dig_time_complete;
1127 float repeat_rightclick_timer;
1128 float object_hit_delay_timer;
1129 float time_from_last_punch;
1130 ClientActiveObject *selected_object;
1134 float update_draw_list_timer;
1135 float statustext_time;
1139 v3f update_draw_list_last_cam_dir;
1141 u32 profiler_current_page;
1142 u32 profiler_max_page; // Number of pages
1145 float time_of_day_smooth;
1149 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1155 Jitter dtime_jitter, busy_time_jitter;
1158 /****************************************************************************
1160 ****************************************************************************/
1162 /* This is not intended to be a public class. If a public class becomes
1163 * desirable then it may be better to create another 'wrapper' class that
1164 * hides most of the stuff in this class (nothing in this class is required
1165 * by any other file) but exposes the public methods/data only.
1172 bool startup(bool *kill,
1174 InputHandler *input,
1175 IrrlichtDevice *device,
1176 const std::string &map_dir,
1177 const std::string &playername,
1178 const std::string &password,
1179 // If address is "", local server is used and address is updated
1180 std::string *address,
1182 std::string &error_message,
1184 ChatBackend *chat_backend,
1185 const SubgameSpec &gamespec, // Used for local game
1186 bool simple_singleplayer_mode);
1193 void extendedResourceCleanup();
1195 // Basic initialisation
1196 bool init(const std::string &map_dir, std::string *address,
1198 const SubgameSpec &gamespec);
1200 bool createSingleplayerServer(const std::string &map_dir,
1201 const SubgameSpec &gamespec, u16 port, std::string *address);
1204 bool createClient(const std::string &playername,
1205 const std::string &password, std::string *address, u16 port);
1208 // Client connection
1209 bool connectToServer(const std::string &playername,
1210 const std::string &password, std::string *address, u16 port,
1211 bool *connect_ok, bool *aborted);
1212 bool getServerContent(bool *aborted);
1216 void updateInteractTimers(f32 dtime);
1217 bool checkConnection();
1218 bool handleCallbacks();
1219 void processQueues();
1220 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1221 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1222 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1225 void processUserInput(f32 dtime);
1226 void processKeyInput();
1227 void processItemSelection(u16 *new_playeritem);
1229 void dropSelectedItem();
1230 void openInventory();
1231 void openConsole(float scale, const wchar_t *line=NULL);
1232 void toggleFreeMove();
1233 void toggleFreeMoveAlt();
1235 void toggleNoClip();
1236 void toggleCinematic();
1237 void toggleAutorun();
1241 void toggleMinimap(bool shift_pressed);
1244 void toggleUpdateCamera();
1245 void toggleProfiler();
1247 void increaseViewRange();
1248 void decreaseViewRange();
1249 void toggleFullViewRange();
1251 void updateCameraDirection(CameraOrientation *cam, float dtime);
1252 void updateCameraOrientation(CameraOrientation *cam, float dtime);
1253 void updatePlayerControl(const CameraOrientation &cam);
1254 void step(f32 *dtime);
1255 void processClientEvents(CameraOrientation *cam);
1256 void updateCamera(u32 busy_time, f32 dtime);
1257 void updateSound(f32 dtime);
1258 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
1260 * Returns the object or node the player is pointing at.
1261 * Also updates the selected thing in the Hud.
1263 * @param[in] shootline the shootline, starting from
1264 * the camera position. This also gives the maximal distance
1266 * @param[in] liquids_pointable if false, liquids are ignored
1267 * @param[in] look_for_object if false, objects are ignored
1268 * @param[in] camera_offset offset of the camera
1269 * @param[out] selected_object the selected object or
1272 PointedThing updatePointedThing(
1273 const core::line3d<f32> &shootline, bool liquids_pointable,
1274 bool look_for_object, const v3s16 &camera_offset);
1275 void handlePointingAtNothing(const ItemStack &playerItem);
1276 void handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
1277 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1278 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
1279 const v3f &player_position, bool show_debug);
1280 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
1281 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1282 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
1283 const CameraOrientation &cam);
1284 void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
1285 void updateProfilerGraphs(ProfilerGraph *graph);
1288 void limitFps(FpsControl *fps_timings, f32 *dtime);
1290 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1291 bool draw_clouds = true);
1293 static void settingChangedCallback(const std::string &setting_name, void *data);
1294 void readSettings();
1296 inline bool getLeftClicked()
1298 return input->getLeftClicked() ||
1299 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1301 inline bool getRightClicked()
1303 return input->getRightClicked() ||
1304 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1306 inline bool isLeftPressed()
1308 return input->getLeftState() ||
1309 input->joystick.isKeyDown(KeyType::MOUSE_L);
1311 inline bool isRightPressed()
1313 return input->getRightState() ||
1314 input->joystick.isKeyDown(KeyType::MOUSE_R);
1316 inline bool getLeftReleased()
1318 return input->getLeftReleased() ||
1319 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1322 inline bool isKeyDown(GameKeyType k)
1324 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1326 inline bool wasKeyDown(GameKeyType k)
1328 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1332 void handleAndroidChatInput();
1336 void showPauseMenu();
1338 InputHandler *input;
1343 IWritableTextureSource *texture_src;
1344 IWritableShaderSource *shader_src;
1346 // When created, these will be filled with data received from the server
1347 IWritableItemDefManager *itemdef_manager;
1348 IWritableNodeDefManager *nodedef_manager;
1350 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1351 ISoundManager *sound;
1352 bool sound_is_dummy;
1353 SoundMaker *soundmaker;
1355 ChatBackend *chat_backend;
1357 GUIFormSpecMenu *current_formspec;
1358 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1359 std::string cur_formname;
1361 EventManager *eventmgr;
1362 QuicktuneShortcutter *quicktune;
1364 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1365 MapDrawControl *draw_control;
1367 Clouds *clouds; // Free using ->Drop()
1368 Sky *sky; // Free using ->Drop()
1369 Inventory *local_inventory;
1373 GameRunData runData;
1377 This class does take ownership/responsibily for cleaning up etc of any of
1378 these items (e.g. device)
1380 IrrlichtDevice *device;
1381 video::IVideoDriver *driver;
1382 scene::ISceneManager *smgr;
1384 std::string *error_message;
1385 bool *reconnect_requested;
1386 scene::ISceneNode *skybox;
1389 bool simple_singleplayer_mode;
1392 /* Pre-calculated values
1394 int crack_animation_length;
1398 gui::IGUIStaticText *guitext; // First line of debug text
1399 gui::IGUIStaticText *guitext2; // Second line of debug text
1400 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1401 gui::IGUIStaticText *guitext_status;
1402 gui::IGUIStaticText *guitext_chat; // Chat text
1403 gui::IGUIStaticText *guitext_profiler; // Profiler text
1405 std::wstring infotext;
1406 std::wstring m_statustext;
1410 IntervalLimiter profiler_interval;
1413 * TODO: Local caching of settings is not optimal and should at some stage
1414 * be updated to use a global settings object for getting thse values
1415 * (as opposed to the this local caching). This can be addressed in
1418 bool m_cache_doubletap_jump;
1419 bool m_cache_enable_clouds;
1420 bool m_cache_enable_joysticks;
1421 bool m_cache_enable_particles;
1422 bool m_cache_enable_fog;
1423 bool m_cache_enable_noclip;
1424 bool m_cache_enable_free_move;
1425 f32 m_cache_mouse_sensitivity;
1426 f32 m_cache_joystick_frustum_sensitivity;
1427 f32 m_repeat_right_click_time;
1428 f32 m_cache_cam_smoothing;
1429 f32 m_cache_fog_start;
1431 bool m_invert_mouse;
1432 bool m_first_loop_after_window_activation;
1433 bool m_camera_offset_changed;
1436 bool m_cache_hold_aux1;
1437 bool m_android_chat_open;
1446 itemdef_manager(NULL),
1447 nodedef_manager(NULL),
1449 sound_is_dummy(false),
1452 current_formspec(NULL),
1456 gui_chat_console(NULL),
1461 local_inventory(NULL),
1464 m_invert_mouse(false),
1465 m_first_loop_after_window_activation(false),
1466 m_camera_offset_changed(false)
1468 g_settings->registerChangedCallback("doubletap_jump",
1469 &settingChangedCallback, this);
1470 g_settings->registerChangedCallback("enable_clouds",
1471 &settingChangedCallback, this);
1472 g_settings->registerChangedCallback("doubletap_joysticks",
1473 &settingChangedCallback, this);
1474 g_settings->registerChangedCallback("enable_particles",
1475 &settingChangedCallback, this);
1476 g_settings->registerChangedCallback("enable_fog",
1477 &settingChangedCallback, this);
1478 g_settings->registerChangedCallback("mouse_sensitivity",
1479 &settingChangedCallback, this);
1480 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1481 &settingChangedCallback, this);
1482 g_settings->registerChangedCallback("repeat_rightclick_time",
1483 &settingChangedCallback, this);
1484 g_settings->registerChangedCallback("noclip",
1485 &settingChangedCallback, this);
1486 g_settings->registerChangedCallback("free_move",
1487 &settingChangedCallback, this);
1488 g_settings->registerChangedCallback("cinematic",
1489 &settingChangedCallback, this);
1490 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1491 &settingChangedCallback, this);
1492 g_settings->registerChangedCallback("camera_smoothing",
1493 &settingChangedCallback, this);
1498 m_cache_hold_aux1 = false; // This is initialised properly later
1505 /****************************************************************************
1507 ****************************************************************************/
1513 if (!sound_is_dummy)
1516 delete server; // deleted first to stop all server threads
1519 delete local_inventory;
1525 delete nodedef_manager;
1526 delete itemdef_manager;
1527 delete draw_control;
1529 extendedResourceCleanup();
1531 g_settings->deregisterChangedCallback("doubletap_jump",
1532 &settingChangedCallback, this);
1533 g_settings->deregisterChangedCallback("enable_clouds",
1534 &settingChangedCallback, this);
1535 g_settings->deregisterChangedCallback("enable_particles",
1536 &settingChangedCallback, this);
1537 g_settings->deregisterChangedCallback("enable_fog",
1538 &settingChangedCallback, this);
1539 g_settings->deregisterChangedCallback("mouse_sensitivity",
1540 &settingChangedCallback, this);
1541 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1542 &settingChangedCallback, this);
1543 g_settings->deregisterChangedCallback("noclip",
1544 &settingChangedCallback, this);
1545 g_settings->deregisterChangedCallback("free_move",
1546 &settingChangedCallback, this);
1547 g_settings->deregisterChangedCallback("cinematic",
1548 &settingChangedCallback, this);
1549 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1550 &settingChangedCallback, this);
1551 g_settings->deregisterChangedCallback("camera_smoothing",
1552 &settingChangedCallback, this);
1555 bool Game::startup(bool *kill,
1557 InputHandler *input,
1558 IrrlichtDevice *device,
1559 const std::string &map_dir,
1560 const std::string &playername,
1561 const std::string &password,
1562 std::string *address, // can change if simple_singleplayer_mode
1564 std::string &error_message,
1566 ChatBackend *chat_backend,
1567 const SubgameSpec &gamespec,
1568 bool simple_singleplayer_mode)
1571 this->device = device;
1573 this->error_message = &error_message;
1574 this->reconnect_requested = reconnect;
1575 this->random_input = random_input;
1576 this->input = input;
1577 this->chat_backend = chat_backend;
1578 this->simple_singleplayer_mode = simple_singleplayer_mode;
1580 keycache.handler = input;
1581 keycache.populate();
1583 driver = device->getVideoDriver();
1584 smgr = device->getSceneManager();
1586 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1588 memset(&runData, 0, sizeof(runData));
1589 runData.time_from_last_punch = 10.0;
1590 runData.profiler_max_page = 3;
1591 runData.update_wielded_item_trigger = true;
1593 memset(&flags, 0, sizeof(flags));
1594 flags.show_chat = true;
1595 flags.show_hud = true;
1596 flags.show_debug = g_settings->getBool("show_debug");
1597 m_invert_mouse = g_settings->getBool("invert_mouse");
1598 m_first_loop_after_window_activation = true;
1600 if (!init(map_dir, address, port, gamespec))
1603 if (!createClient(playername, password, address, port))
1612 ProfilerGraph graph;
1613 RunStats stats = { 0 };
1614 CameraOrientation cam_view_target = { 0 };
1615 CameraOrientation cam_view = { 0 };
1616 FpsControl draw_times = { 0 };
1617 f32 dtime; // in seconds
1619 /* Clear the profiler */
1620 Profiler::GraphValues dummyvalues;
1621 g_profiler->graphGet(dummyvalues);
1623 draw_times.last_time = device->getTimer()->getTime();
1625 set_light_table(g_settings->getFloat("display_gamma"));
1628 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1629 && client->checkPrivilege("fast");
1632 while (device->run()
1633 && !(*kill || g_gamecallback->shutdown_requested
1634 || (server && server->getShutdownRequested()))) {
1636 /* Must be called immediately after a device->run() call because it
1637 * uses device->getTimer()->getTime()
1639 limitFps(&draw_times, &dtime);
1641 updateStats(&stats, draw_times, dtime);
1642 updateInteractTimers(dtime);
1644 if (!checkConnection())
1646 if (!handleCallbacks())
1652 hud->resizeHotbar();
1654 updateProfilers(stats, draw_times, dtime);
1655 processUserInput(dtime);
1656 // Update camera before player movement to avoid camera lag of one frame
1657 updateCameraDirection(&cam_view_target, dtime);
1658 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1659 cam_view.camera_yaw) * m_cache_cam_smoothing;
1660 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1661 cam_view.camera_pitch) * m_cache_cam_smoothing;
1662 updatePlayerControl(cam_view);
1664 processClientEvents(&cam_view_target);
1665 updateCamera(draw_times.busy_time, dtime);
1667 processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
1668 updateFrame(&graph, &stats, dtime, cam_view);
1669 updateProfilerGraphs(&graph);
1671 // Update if minimap has been disabled by the server
1672 flags.show_minimap &= client->shouldShowMinimap();
1677 void Game::shutdown()
1679 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1680 if (g_settings->get("3d_mode") == "pageflip") {
1681 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1685 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1690 if (gui_chat_console)
1691 gui_chat_console->drop();
1697 while (g_menumgr.menuCount() > 0) {
1698 g_menumgr.m_stack.front()->setVisible(false);
1699 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1702 if (current_formspec) {
1703 current_formspec->drop();
1704 current_formspec = NULL;
1707 chat_backend->addMessage(L"", L"# Disconnected.");
1708 chat_backend->addMessage(L"", L"");
1712 while (!client->isShutdown()) {
1713 assert(texture_src != NULL);
1714 assert(shader_src != NULL);
1715 texture_src->processQueue();
1716 shader_src->processQueue();
1723 /****************************************************************************/
1724 /****************************************************************************
1726 ****************************************************************************/
1727 /****************************************************************************/
1730 const std::string &map_dir,
1731 std::string *address,
1733 const SubgameSpec &gamespec)
1735 texture_src = createTextureSource(device);
1737 showOverlayMessage(wgettext("Loading..."), 0, 0);
1739 shader_src = createShaderSource(device);
1741 itemdef_manager = createItemDefManager();
1742 nodedef_manager = createNodeDefManager();
1744 eventmgr = new EventManager();
1745 quicktune = new QuicktuneShortcutter();
1747 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1748 && eventmgr && quicktune))
1754 // Create a server if not connecting to an existing one
1755 if (*address == "") {
1756 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1763 bool Game::initSound()
1766 if (g_settings->getBool("enable_sound")) {
1767 infostream << "Attempting to use OpenAL audio" << std::endl;
1768 sound = createOpenALSoundManager(&soundfetcher);
1770 infostream << "Failed to initialize OpenAL audio" << std::endl;
1772 infostream << "Sound disabled." << std::endl;
1776 infostream << "Using dummy audio." << std::endl;
1777 sound = &dummySoundManager;
1778 sound_is_dummy = true;
1781 soundmaker = new SoundMaker(sound, nodedef_manager);
1785 soundmaker->registerReceiver(eventmgr);
1790 bool Game::createSingleplayerServer(const std::string &map_dir,
1791 const SubgameSpec &gamespec, u16 port, std::string *address)
1793 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1795 std::string bind_str = g_settings->get("bind_address");
1796 Address bind_addr(0, 0, 0, 0, port);
1798 if (g_settings->getBool("ipv6_server")) {
1799 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1803 bind_addr.Resolve(bind_str.c_str());
1804 } catch (ResolveError &e) {
1805 infostream << "Resolving bind address \"" << bind_str
1806 << "\" failed: " << e.what()
1807 << " -- Listening on all addresses." << std::endl;
1810 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1811 *error_message = "Unable to listen on " +
1812 bind_addr.serializeString() +
1813 " because IPv6 is disabled";
1814 errorstream << *error_message << std::endl;
1818 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1819 bind_addr.isIPv6(), false);
1821 server->start(bind_addr);
1826 bool Game::createClient(const std::string &playername,
1827 const std::string &password, std::string *address, u16 port)
1829 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1831 draw_control = new MapDrawControl;
1835 bool could_connect, connect_aborted;
1837 if (!connectToServer(playername, password, address, port,
1838 &could_connect, &connect_aborted))
1841 if (!could_connect) {
1842 if (error_message->empty() && !connect_aborted) {
1843 // Should not happen if error messages are set properly
1844 *error_message = "Connection failed for unknown reason";
1845 errorstream << *error_message << std::endl;
1850 if (!getServerContent(&connect_aborted)) {
1851 if (error_message->empty() && !connect_aborted) {
1852 // Should not happen if error messages are set properly
1853 *error_message = "Connection failed for unknown reason";
1854 errorstream << *error_message << std::endl;
1859 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1860 &flags.force_fog_off, &runData.fog_range, client);
1861 shader_src->addShaderConstantSetterFactory(scsf);
1863 // Update cached textures, meshes and materials
1864 client->afterContentReceived(device);
1868 camera = new Camera(smgr, *draw_control, client);
1869 if (!camera || !camera->successfullyCreated(*error_message))
1871 client->setCamera(camera);
1875 if (m_cache_enable_clouds) {
1876 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1878 *error_message = "Memory allocation error (clouds)";
1879 errorstream << *error_message << std::endl;
1886 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
1888 skybox = NULL; // This is used/set later on in the main run loop
1890 local_inventory = new Inventory(itemdef_manager);
1892 if (!(sky && local_inventory)) {
1893 *error_message = "Memory allocation error (sky or local inventory)";
1894 errorstream << *error_message << std::endl;
1898 /* Pre-calculated values
1900 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1902 v2u32 size = t->getOriginalSize();
1903 crack_animation_length = size.Y / size.X;
1905 crack_animation_length = 5;
1911 /* Set window caption
1913 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1915 str += utf8_to_wide(g_version_hash);
1917 str += driver->getName();
1919 device->setWindowCaption(str.c_str());
1921 LocalPlayer *player = client->getEnv().getLocalPlayer();
1922 player->hurt_tilt_timer = 0;
1923 player->hurt_tilt_strength = 0;
1925 hud = new Hud(driver, smgr, guienv, client, player, local_inventory);
1928 *error_message = "Memory error: could not create HUD";
1929 errorstream << *error_message << std::endl;
1933 mapper = client->getMinimap();
1934 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1939 bool Game::initGui()
1941 // First line of debug text
1942 guitext = addStaticText(guienv,
1943 utf8_to_wide(PROJECT_NAME_C).c_str(),
1944 core::rect<s32>(0, 0, 0, 0),
1945 false, false, guiroot);
1947 // Second line of debug text
1948 guitext2 = addStaticText(guienv,
1950 core::rect<s32>(0, 0, 0, 0),
1951 false, false, guiroot);
1953 // At the middle of the screen
1954 // Object infos are shown in this
1955 guitext_info = addStaticText(guienv,
1957 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
1958 false, true, guiroot);
1960 // Status text (displays info when showing and hiding GUI stuff, etc.)
1961 guitext_status = addStaticText(guienv,
1963 core::rect<s32>(0, 0, 0, 0),
1964 false, false, guiroot);
1965 guitext_status->setVisible(false);
1968 guitext_chat = addStaticText(
1971 core::rect<s32>(0, 0, 0, 0),
1972 //false, false); // Disable word wrap as of now
1973 false, true, guiroot);
1975 // Remove stale "recent" chat messages from previous connections
1976 chat_backend->clearRecentChat();
1978 // Chat backend and console
1979 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
1980 -1, chat_backend, client, &g_menumgr);
1981 if (!gui_chat_console) {
1982 *error_message = "Could not allocate memory for chat console";
1983 errorstream << *error_message << std::endl;
1987 // Profiler text (size is updated when text is updated)
1988 guitext_profiler = addStaticText(guienv,
1990 core::rect<s32>(0, 0, 0, 0),
1991 false, false, guiroot);
1992 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
1993 guitext_profiler->setVisible(false);
1994 guitext_profiler->setWordWrap(true);
1996 #ifdef HAVE_TOUCHSCREENGUI
1998 if (g_touchscreengui)
1999 g_touchscreengui->init(texture_src);
2006 bool Game::connectToServer(const std::string &playername,
2007 const std::string &password, std::string *address, u16 port,
2008 bool *connect_ok, bool *aborted)
2010 *connect_ok = false; // Let's not be overly optimistic
2012 bool local_server_mode = false;
2014 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2016 Address connect_address(0, 0, 0, 0, port);
2019 connect_address.Resolve(address->c_str());
2021 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2022 //connect_address.Resolve("localhost");
2023 if (connect_address.isIPv6()) {
2024 IPv6AddressBytes addr_bytes;
2025 addr_bytes.bytes[15] = 1;
2026 connect_address.setAddress(&addr_bytes);
2028 connect_address.setAddress(127, 0, 0, 1);
2030 local_server_mode = true;
2032 } catch (ResolveError &e) {
2033 *error_message = std::string("Couldn't resolve address: ") + e.what();
2034 errorstream << *error_message << std::endl;
2038 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2039 *error_message = "Unable to connect to " +
2040 connect_address.serializeString() +
2041 " because IPv6 is disabled";
2042 errorstream << *error_message << std::endl;
2046 client = new Client(device,
2047 playername.c_str(), password, *address,
2048 *draw_control, texture_src, shader_src,
2049 itemdef_manager, nodedef_manager, sound, eventmgr,
2050 connect_address.isIPv6(), &flags);
2055 infostream << "Connecting to server at ";
2056 connect_address.print(&infostream);
2057 infostream << std::endl;
2059 client->connect(connect_address,
2060 simple_singleplayer_mode || local_server_mode);
2063 Wait for server to accept connection
2069 FpsControl fps_control = { 0 };
2071 f32 wait_time = 0; // in seconds
2073 fps_control.last_time = device->getTimer()->getTime();
2077 while (device->run()) {
2079 limitFps(&fps_control, &dtime);
2081 // Update client and server
2082 client->step(dtime);
2085 server->step(dtime);
2088 if (client->getState() == LC_Init) {
2094 if (client->accessDenied()) {
2095 *error_message = "Access denied. Reason: "
2096 + client->accessDeniedReason();
2097 *reconnect_requested = client->reconnectRequested();
2098 errorstream << *error_message << std::endl;
2102 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2104 infostream << "Connect aborted [Escape]" << std::endl;
2109 // Only time out if we aren't waiting for the server we started
2110 if ((*address != "") && (wait_time > 10)) {
2111 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2112 // If no pre v25 init was sent, and no answer was received,
2113 // but the low level connection could be established
2114 // (meaning that we have a peer id), then we probably wanted
2115 // to connect to a legacy server. In this case, tell the user
2116 // to enable the option to be able to connect.
2117 if (!sent_old_init &&
2118 (client->getProtoVersion() == 0) &&
2119 client->connectedToServer()) {
2120 *error_message = "Connection failure: init packet not "
2121 "recognized by server.\n"
2122 "Most likely the server uses an old protocol version (<v25).\n"
2123 "Please ask the server owner to update to 0.4.13 or later.\n"
2124 "To still connect to the server in the meantime,\n"
2125 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2126 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2127 "entry in the advanced settings menu.";
2129 *error_message = "Connection timed out.";
2131 errorstream << *error_message << std::endl;
2136 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2138 } catch (con::PeerNotFoundException &e) {
2139 // TODO: Should something be done here? At least an info/error
2147 bool Game::getServerContent(bool *aborted)
2151 FpsControl fps_control = { 0 };
2152 f32 dtime; // in seconds
2154 fps_control.last_time = device->getTimer()->getTime();
2156 while (device->run()) {
2158 limitFps(&fps_control, &dtime);
2160 // Update client and server
2161 client->step(dtime);
2164 server->step(dtime);
2167 if (client->mediaReceived() && client->itemdefReceived() &&
2168 client->nodedefReceived()) {
2173 if (!checkConnection())
2176 if (client->getState() < LC_Init) {
2177 *error_message = "Client disconnected";
2178 errorstream << *error_message << std::endl;
2182 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2184 infostream << "Connect aborted [Escape]" << std::endl;
2191 if (!client->itemdefReceived()) {
2192 const wchar_t *text = wgettext("Item definitions...");
2194 draw_load_screen(text, device, guienv, texture_src,
2197 } else if (!client->nodedefReceived()) {
2198 const wchar_t *text = wgettext("Node definitions...");
2200 draw_load_screen(text, device, guienv, texture_src,
2204 std::stringstream message;
2205 std::fixed(message);
2206 message.precision(0);
2207 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2208 message.precision(2);
2210 if ((USE_CURL == 0) ||
2211 (!g_settings->getBool("enable_remote_media_server"))) {
2212 float cur = client->getCurRate();
2213 std::string cur_unit = gettext("KiB/s");
2217 cur_unit = gettext("MiB/s");
2220 message << " (" << cur << ' ' << cur_unit << ")";
2223 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2224 draw_load_screen(utf8_to_wide(message.str()), device,
2225 guienv, texture_src, dtime, progress);
2233 /****************************************************************************/
2234 /****************************************************************************
2236 ****************************************************************************/
2237 /****************************************************************************/
2239 inline void Game::updateInteractTimers(f32 dtime)
2241 if (runData.nodig_delay_timer >= 0)
2242 runData.nodig_delay_timer -= dtime;
2244 if (runData.object_hit_delay_timer >= 0)
2245 runData.object_hit_delay_timer -= dtime;
2247 runData.time_from_last_punch += dtime;
2251 /* returns false if game should exit, otherwise true
2253 inline bool Game::checkConnection()
2255 if (client->accessDenied()) {
2256 *error_message = "Access denied. Reason: "
2257 + client->accessDeniedReason();
2258 *reconnect_requested = client->reconnectRequested();
2259 errorstream << *error_message << std::endl;
2267 /* returns false if game should exit, otherwise true
2269 inline bool Game::handleCallbacks()
2271 if (g_gamecallback->disconnect_requested) {
2272 g_gamecallback->disconnect_requested = false;
2276 if (g_gamecallback->changepassword_requested) {
2277 (new GUIPasswordChange(guienv, guiroot, -1,
2278 &g_menumgr, client))->drop();
2279 g_gamecallback->changepassword_requested = false;
2282 if (g_gamecallback->changevolume_requested) {
2283 (new GUIVolumeChange(guienv, guiroot, -1,
2284 &g_menumgr))->drop();
2285 g_gamecallback->changevolume_requested = false;
2288 if (g_gamecallback->keyconfig_requested) {
2289 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2290 &g_menumgr))->drop();
2291 g_gamecallback->keyconfig_requested = false;
2294 if (g_gamecallback->keyconfig_changed) {
2295 keycache.populate(); // update the cache with new settings
2296 g_gamecallback->keyconfig_changed = false;
2303 void Game::processQueues()
2305 texture_src->processQueue();
2306 itemdef_manager->processQueue(client);
2307 shader_src->processQueue();
2311 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2313 float profiler_print_interval =
2314 g_settings->getFloat("profiler_print_interval");
2315 bool print_to_log = true;
2317 if (profiler_print_interval == 0) {
2318 print_to_log = false;
2319 profiler_print_interval = 5;
2322 if (profiler_interval.step(dtime, profiler_print_interval)) {
2324 infostream << "Profiler:" << std::endl;
2325 g_profiler->print(infostream);
2328 update_profiler_gui(guitext_profiler, g_fontengine,
2329 runData.profiler_current_page, runData.profiler_max_page,
2330 driver->getScreenSize().Height);
2332 g_profiler->clear();
2335 addProfilerGraphs(stats, draw_times, dtime);
2339 void Game::addProfilerGraphs(const RunStats &stats,
2340 const FpsControl &draw_times, f32 dtime)
2342 g_profiler->graphAdd("mainloop_other",
2343 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2345 if (draw_times.sleep_time != 0)
2346 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2347 g_profiler->graphAdd("mainloop_dtime", dtime);
2349 g_profiler->add("Elapsed time", dtime);
2350 g_profiler->avg("FPS", 1. / dtime);
2354 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2361 /* Time average and jitter calculation
2363 jp = &stats->dtime_jitter;
2364 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2366 jitter = dtime - jp->avg;
2368 if (jitter > jp->max)
2371 jp->counter += dtime;
2373 if (jp->counter > 0.0) {
2375 jp->max_sample = jp->max;
2376 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2380 /* Busytime average and jitter calculation
2382 jp = &stats->busy_time_jitter;
2383 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2385 jitter = draw_times.busy_time - jp->avg;
2387 if (jitter > jp->max)
2389 if (jitter < jp->min)
2392 jp->counter += dtime;
2394 if (jp->counter > 0.0) {
2396 jp->max_sample = jp->max;
2397 jp->min_sample = jp->min;
2405 /****************************************************************************
2407 ****************************************************************************/
2409 void Game::processUserInput(f32 dtime)
2411 // Reset input if window not active or some menu is active
2412 if (!device->isWindowActive() || !noMenuActive() || guienv->hasFocus(gui_chat_console)) {
2414 #ifdef HAVE_TOUCHSCREENGUI
2415 g_touchscreengui->hide();
2418 #ifdef HAVE_TOUCHSCREENGUI
2419 else if (g_touchscreengui) {
2420 /* on touchscreengui step may generate own input events which ain't
2421 * what we want in case we just did clear them */
2422 g_touchscreengui->step(dtime);
2426 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2427 gui_chat_console->closeConsoleAtOnce();
2430 // Input handler step() (used by the random input generator)
2434 if (current_formspec != NULL)
2435 current_formspec->getAndroidUIInput();
2437 handleAndroidChatInput();
2440 // Increase timer for double tap of "keymap_jump"
2441 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2442 runData.jump_timer += dtime;
2445 processItemSelection(&runData.new_playeritem);
2449 void Game::processKeyInput()
2451 if (wasKeyDown(KeyType::DROP)) {
2453 } else if (wasKeyDown(KeyType::AUTORUN)) {
2455 } else if (wasKeyDown(KeyType::INVENTORY)) {
2457 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2458 if (!gui_chat_console->isOpenInhibited()) {
2461 } else if (wasKeyDown(KeyType::CHAT)) {
2462 openConsole(0.2, L"");
2463 } else if (wasKeyDown(KeyType::CMD)) {
2464 openConsole(0.2, L"/");
2465 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2466 openConsole(0.2, L".");
2467 } else if (wasKeyDown(KeyType::CONSOLE)) {
2468 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2469 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2471 } else if (wasKeyDown(KeyType::JUMP)) {
2472 toggleFreeMoveAlt();
2473 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2475 } else if (wasKeyDown(KeyType::NOCLIP)) {
2477 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2479 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2480 client->makeScreenshot(device);
2481 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2483 } else if (wasKeyDown(KeyType::MINIMAP)) {
2484 toggleMinimap(isKeyDown(KeyType::SNEAK));
2485 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2487 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2489 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2490 toggleUpdateCamera();
2491 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2493 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2495 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2496 increaseViewRange();
2497 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2498 decreaseViewRange();
2499 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2500 toggleFullViewRange();
2501 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2503 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2505 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2507 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2509 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2510 // Print debug stacks
2511 dstream << "-----------------------------------------"
2513 dstream << "Printing debug stacks:" << std::endl;
2514 dstream << "-----------------------------------------"
2516 debug_stacks_print();
2519 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2520 runData.reset_jump_timer = false;
2521 runData.jump_timer = 0.0f;
2524 if (quicktune->hasMessage()) {
2525 m_statustext = utf8_to_wide(quicktune->getMessage());
2526 runData.statustext_time = 0.0f;
2530 void Game::processItemSelection(u16 *new_playeritem)
2532 LocalPlayer *player = client->getEnv().getLocalPlayer();
2534 /* Item selection using mouse wheel
2536 *new_playeritem = client->getPlayerItem();
2538 s32 wheel = input->getMouseWheel();
2539 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2540 player->hud_hotbar_itemcount - 1);
2544 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN)) {
2548 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP)) {
2553 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2555 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2558 /* Item selection using keyboard
2560 for (u16 i = 0; i < 10; i++) {
2561 static const KeyPress *item_keys[10] = {
2562 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2563 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2564 NumberKey + 9, NumberKey + 0,
2567 if (input->wasKeyDown(*item_keys[i])) {
2568 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2569 *new_playeritem = i;
2570 infostream << "Selected item: " << new_playeritem << std::endl;
2578 void Game::dropSelectedItem()
2580 IDropAction *a = new IDropAction();
2582 a->from_inv.setCurrentPlayer();
2583 a->from_list = "main";
2584 a->from_i = client->getPlayerItem();
2585 client->inventoryAction(a);
2589 void Game::openInventory()
2592 * Don't permit to open inventory is CAO or player doesn't exists.
2593 * This prevent showing an empty inventory at player load
2596 LocalPlayer *player = client->getEnv().getLocalPlayer();
2597 if (player == NULL || player->getCAO() == NULL)
2600 infostream << "the_game: " << "Launching inventory" << std::endl;
2602 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2603 TextDest *txt_dst = new TextDestPlayerInventory(client);
2605 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
2608 InventoryLocation inventoryloc;
2609 inventoryloc.setCurrentPlayer();
2610 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2614 void Game::openConsole(float scale, const wchar_t *line)
2616 assert(scale > 0.0f && scale <= 1.0f);
2619 porting::showInputDialog(gettext("ok"), "", "", 2);
2620 m_android_chat_open = true;
2622 if (gui_chat_console->isOpenInhibited())
2624 gui_chat_console->openConsole(scale);
2626 gui_chat_console->setCloseOnEnter(true);
2627 gui_chat_console->replaceAndAddToHistory(line);
2633 void Game::handleAndroidChatInput()
2635 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2636 std::string text = porting::getInputDialogValue();
2637 client->typeChatMessage(utf8_to_wide(text));
2643 void Game::toggleFreeMove()
2645 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2647 bool free_move = !g_settings->getBool("free_move");
2648 g_settings->set("free_move", bool_to_cstr(free_move));
2650 runData.statustext_time = 0;
2651 m_statustext = msg[free_move];
2652 if (free_move && !client->checkPrivilege("fly"))
2653 m_statustext += L" (note: no 'fly' privilege)";
2657 void Game::toggleFreeMoveAlt()
2659 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2662 runData.reset_jump_timer = true;
2666 void Game::toggleFast()
2668 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2669 bool fast_move = !g_settings->getBool("fast_move");
2670 g_settings->set("fast_move", bool_to_cstr(fast_move));
2672 runData.statustext_time = 0;
2673 m_statustext = msg[fast_move];
2675 bool has_fast_privs = client->checkPrivilege("fast");
2677 if (fast_move && !has_fast_privs)
2678 m_statustext += L" (note: no 'fast' privilege)";
2681 m_cache_hold_aux1 = fast_move && has_fast_privs;
2686 void Game::toggleNoClip()
2688 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2689 bool noclip = !g_settings->getBool("noclip");
2690 g_settings->set("noclip", bool_to_cstr(noclip));
2692 runData.statustext_time = 0;
2693 m_statustext = msg[noclip];
2695 if (noclip && !client->checkPrivilege("noclip"))
2696 m_statustext += L" (note: no 'noclip' privilege)";
2699 void Game::toggleCinematic()
2701 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2702 bool cinematic = !g_settings->getBool("cinematic");
2703 g_settings->set("cinematic", bool_to_cstr(cinematic));
2705 runData.statustext_time = 0;
2706 m_statustext = msg[cinematic];
2709 // Add WoW-style autorun by toggling continuous forward.
2710 void Game::toggleAutorun()
2712 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2713 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2714 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2716 runData.statustext_time = 0;
2717 m_statustext = msg[autorun_enabled ? 1 : 0];
2720 void Game::toggleChat()
2722 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2724 flags.show_chat = !flags.show_chat;
2725 runData.statustext_time = 0;
2726 m_statustext = msg[flags.show_chat];
2730 void Game::toggleHud()
2732 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2734 flags.show_hud = !flags.show_hud;
2735 runData.statustext_time = 0;
2736 m_statustext = msg[flags.show_hud];
2739 void Game::toggleMinimap(bool shift_pressed)
2741 if (!flags.show_hud || !g_settings->getBool("enable_minimap"))
2744 if (shift_pressed) {
2745 mapper->toggleMinimapShape();
2749 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2751 MinimapMode mode = MINIMAP_MODE_OFF;
2752 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2753 mode = mapper->getMinimapMode();
2754 mode = (MinimapMode)((int)mode + 1);
2757 flags.show_minimap = true;
2759 case MINIMAP_MODE_SURFACEx1:
2760 m_statustext = L"Minimap in surface mode, Zoom x1";
2762 case MINIMAP_MODE_SURFACEx2:
2763 m_statustext = L"Minimap in surface mode, Zoom x2";
2765 case MINIMAP_MODE_SURFACEx4:
2766 m_statustext = L"Minimap in surface mode, Zoom x4";
2768 case MINIMAP_MODE_RADARx1:
2769 m_statustext = L"Minimap in radar mode, Zoom x1";
2771 case MINIMAP_MODE_RADARx2:
2772 m_statustext = L"Minimap in radar mode, Zoom x2";
2774 case MINIMAP_MODE_RADARx4:
2775 m_statustext = L"Minimap in radar mode, Zoom x4";
2778 mode = MINIMAP_MODE_OFF;
2779 flags.show_minimap = false;
2780 m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2781 L"Minimap hidden" : L"Minimap disabled by server";
2784 runData.statustext_time = 0;
2785 mapper->setMinimapMode(mode);
2788 void Game::toggleFog()
2790 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2792 flags.force_fog_off = !flags.force_fog_off;
2793 runData.statustext_time = 0;
2794 m_statustext = msg[flags.force_fog_off];
2798 void Game::toggleDebug()
2800 // Initial / 4x toggle: Chat only
2801 // 1x toggle: Debug text with chat
2802 // 2x toggle: Debug text with profiler graph
2803 // 3x toggle: Debug text and wireframe
2804 if (!flags.show_debug) {
2805 flags.show_debug = true;
2806 flags.show_profiler_graph = false;
2807 draw_control->show_wireframe = false;
2808 m_statustext = L"Debug info shown";
2809 } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2810 flags.show_profiler_graph = true;
2811 m_statustext = L"Profiler graph shown";
2812 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2813 flags.show_profiler_graph = false;
2814 draw_control->show_wireframe = true;
2815 m_statustext = L"Wireframe shown";
2817 flags.show_debug = false;
2818 flags.show_profiler_graph = false;
2819 draw_control->show_wireframe = false;
2820 if (client->checkPrivilege("debug")) {
2821 m_statustext = L"Debug info, profiler graph, and wireframe hidden";
2823 m_statustext = L"Debug info and profiler graph hidden";
2826 runData.statustext_time = 0;
2830 void Game::toggleUpdateCamera()
2832 static const wchar_t *msg[] = {
2833 L"Camera update enabled",
2834 L"Camera update disabled"
2837 flags.disable_camera_update = !flags.disable_camera_update;
2838 runData.statustext_time = 0;
2839 m_statustext = msg[flags.disable_camera_update];
2843 void Game::toggleProfiler()
2845 runData.profiler_current_page =
2846 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2848 // FIXME: This updates the profiler with incomplete values
2849 update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2850 runData.profiler_max_page, driver->getScreenSize().Height);
2852 if (runData.profiler_current_page != 0) {
2853 std::wstringstream sstr;
2854 sstr << "Profiler shown (page " << runData.profiler_current_page
2855 << " of " << runData.profiler_max_page << ")";
2856 m_statustext = sstr.str();
2858 m_statustext = L"Profiler hidden";
2860 runData.statustext_time = 0;
2864 void Game::increaseViewRange()
2866 s16 range = g_settings->getS16("viewing_range");
2867 s16 range_new = range + 10;
2869 if (range_new > 4000) {
2871 m_statustext = utf8_to_wide("Viewing range is at maximum: "
2874 m_statustext = utf8_to_wide("Viewing range changed to "
2877 g_settings->set("viewing_range", itos(range_new));
2878 runData.statustext_time = 0;
2882 void Game::decreaseViewRange()
2884 s16 range = g_settings->getS16("viewing_range");
2885 s16 range_new = range - 10;
2887 if (range_new < 20) {
2889 m_statustext = utf8_to_wide("Viewing range is at minimum: "
2892 m_statustext = utf8_to_wide("Viewing range changed to "
2895 g_settings->set("viewing_range", itos(range_new));
2896 runData.statustext_time = 0;
2900 void Game::toggleFullViewRange()
2902 static const wchar_t *msg[] = {
2903 L"Disabled full viewing range",
2904 L"Enabled full viewing range"
2907 draw_control->range_all = !draw_control->range_all;
2908 infostream << msg[draw_control->range_all] << std::endl;
2909 m_statustext = msg[draw_control->range_all];
2910 runData.statustext_time = 0;
2914 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2916 if ((device->isWindowActive() && noMenuActive()) || random_input) {
2919 if (!random_input) {
2920 // Mac OSX gets upset if this is set every frame
2921 if (device->getCursorControl()->isVisible())
2922 device->getCursorControl()->setVisible(false);
2926 if (m_first_loop_after_window_activation)
2927 m_first_loop_after_window_activation = false;
2929 updateCameraOrientation(cam, dtime);
2931 input->setMousePos((driver->getScreenSize().Width / 2),
2932 (driver->getScreenSize().Height / 2));
2936 // Mac OSX gets upset if this is set every frame
2937 if (!device->getCursorControl()->isVisible())
2938 device->getCursorControl()->setVisible(true);
2941 if (!m_first_loop_after_window_activation)
2942 m_first_loop_after_window_activation = true;
2947 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2949 #ifdef HAVE_TOUCHSCREENGUI
2950 if (g_touchscreengui) {
2951 cam->camera_yaw += g_touchscreengui->getYawChange();
2952 cam->camera_pitch = g_touchscreengui->getPitch();
2956 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
2957 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
2959 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2963 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
2964 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
2966 #ifdef HAVE_TOUCHSCREENGUI
2970 if (m_cache_enable_joysticks) {
2971 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
2972 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
2973 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
2976 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2980 void Game::updatePlayerControl(const CameraOrientation &cam)
2982 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2984 // DO NOT use the isKeyDown method for the forward, backward, left, right
2985 // buttons, as the code that uses the controls needs to be able to
2986 // distinguish between the two in order to know when to use joysticks.
2988 PlayerControl control(
2989 input->isKeyDown(keycache.key[KeyType::FORWARD]),
2990 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
2991 input->isKeyDown(keycache.key[KeyType::LEFT]),
2992 input->isKeyDown(keycache.key[KeyType::RIGHT]),
2993 isKeyDown(KeyType::JUMP),
2994 isKeyDown(KeyType::SPECIAL1),
2995 isKeyDown(KeyType::SNEAK),
2996 isKeyDown(KeyType::ZOOM),
3001 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3002 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3006 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3007 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3008 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3009 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3010 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3011 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3012 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3013 ( (u32)(isLeftPressed() & 0x1) << 7) |
3014 ( (u32)(isRightPressed() & 0x1) << 8
3018 /* For Android, simulate holding down AUX1 (fast move) if the user has
3019 * the fast_move setting toggled on. If there is an aux1 key defined for
3020 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3023 if (m_cache_hold_aux1) {
3024 control.aux1 = control.aux1 ^ true;
3025 keypress_bits ^= ((u32)(1U << 5));
3029 client->setPlayerControl(control);
3030 LocalPlayer *player = client->getEnv().getLocalPlayer();
3031 player->keyPressed = keypress_bits;
3037 inline void Game::step(f32 *dtime)
3039 bool can_be_and_is_paused =
3040 (simple_singleplayer_mode && g_menumgr.pausesGame());
3042 if (can_be_and_is_paused) { // This is for a singleplayer server
3043 *dtime = 0; // No time passes
3045 if (server != NULL) {
3046 //TimeTaker timer("server->step(dtime)");
3047 server->step(*dtime);
3050 //TimeTaker timer("client.step(dtime)");
3051 client->step(*dtime);
3056 void Game::processClientEvents(CameraOrientation *cam)
3058 LocalPlayer *player = client->getEnv().getLocalPlayer();
3060 while (client->hasClientEvents()) {
3061 ClientEvent event = client->getClientEvent();
3063 switch (event.type) {
3064 case CE_PLAYER_DAMAGE:
3065 if (client->getHP() == 0)
3067 if (client->moddingEnabled()) {
3068 client->getScript()->on_damage_taken(event.player_damage.amount);
3071 runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3072 runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3074 player->hurt_tilt_timer = 1.5;
3075 player->hurt_tilt_strength =
3076 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3078 client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3081 case CE_PLAYER_FORCE_MOVE:
3082 cam->camera_yaw = event.player_force_move.yaw;
3083 cam->camera_pitch = event.player_force_move.pitch;
3086 case CE_DEATHSCREEN:
3087 // This should be enabled for death formspec in builtin
3088 client->getScript()->on_death();
3090 /* Handle visualization */
3091 runData.damage_flash = 0;
3092 player->hurt_tilt_timer = 0;
3093 player->hurt_tilt_strength = 0;
3096 case CE_SHOW_FORMSPEC:
3097 if (*(event.show_formspec.formspec) == "") {
3098 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3099 current_formspec->quitMenu();
3102 FormspecFormSource *fs_src =
3103 new FormspecFormSource(*(event.show_formspec.formspec));
3104 TextDestPlayerInventory *txt_dst =
3105 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3107 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3109 cur_formname = *(event.show_formspec.formname);
3112 delete event.show_formspec.formspec;
3113 delete event.show_formspec.formname;
3116 case CE_SHOW_LOCAL_FORMSPEC:
3118 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3119 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3120 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3123 delete event.show_formspec.formspec;
3124 delete event.show_formspec.formname;
3127 case CE_SPAWN_PARTICLE:
3128 case CE_ADD_PARTICLESPAWNER:
3129 case CE_DELETE_PARTICLESPAWNER:
3130 client->getParticleManager()->handleParticleEvent(&event, client,
3136 u32 id = event.hudadd.id;
3138 HudElement *e = player->getHud(id);
3141 delete event.hudadd.pos;
3142 delete event.hudadd.name;
3143 delete event.hudadd.scale;
3144 delete event.hudadd.text;
3145 delete event.hudadd.align;
3146 delete event.hudadd.offset;
3147 delete event.hudadd.world_pos;
3148 delete event.hudadd.size;
3153 e->type = (HudElementType)event.hudadd.type;
3154 e->pos = *event.hudadd.pos;
3155 e->name = *event.hudadd.name;
3156 e->scale = *event.hudadd.scale;
3157 e->text = *event.hudadd.text;
3158 e->number = event.hudadd.number;
3159 e->item = event.hudadd.item;
3160 e->dir = event.hudadd.dir;
3161 e->align = *event.hudadd.align;
3162 e->offset = *event.hudadd.offset;
3163 e->world_pos = *event.hudadd.world_pos;
3164 e->size = *event.hudadd.size;
3166 u32 new_id = player->addHud(e);
3167 //if this isn't true our huds aren't consistent
3168 sanity_check(new_id == id);
3171 delete event.hudadd.pos;
3172 delete event.hudadd.name;
3173 delete event.hudadd.scale;
3174 delete event.hudadd.text;
3175 delete event.hudadd.align;
3176 delete event.hudadd.offset;
3177 delete event.hudadd.world_pos;
3178 delete event.hudadd.size;
3183 HudElement *e = player->removeHud(event.hudrm.id);
3192 u32 id = event.hudchange.id;
3193 HudElement *e = player->getHud(id);
3196 delete event.hudchange.v3fdata;
3197 delete event.hudchange.v2fdata;
3198 delete event.hudchange.sdata;
3199 delete event.hudchange.v2s32data;
3203 switch (event.hudchange.stat) {
3205 e->pos = *event.hudchange.v2fdata;
3209 e->name = *event.hudchange.sdata;
3212 case HUD_STAT_SCALE:
3213 e->scale = *event.hudchange.v2fdata;
3217 e->text = *event.hudchange.sdata;
3220 case HUD_STAT_NUMBER:
3221 e->number = event.hudchange.data;
3225 e->item = event.hudchange.data;
3229 e->dir = event.hudchange.data;
3232 case HUD_STAT_ALIGN:
3233 e->align = *event.hudchange.v2fdata;
3236 case HUD_STAT_OFFSET:
3237 e->offset = *event.hudchange.v2fdata;
3240 case HUD_STAT_WORLD_POS:
3241 e->world_pos = *event.hudchange.v3fdata;
3245 e->size = *event.hudchange.v2s32data;
3250 delete event.hudchange.v3fdata;
3251 delete event.hudchange.v2fdata;
3252 delete event.hudchange.sdata;
3253 delete event.hudchange.v2s32data;
3257 sky->setVisible(false);
3258 // Whether clouds are visible in front of a custom skybox
3259 sky->setCloudsEnabled(event.set_sky.clouds);
3266 // Handle according to type
3267 if (*event.set_sky.type == "regular") {
3268 sky->setVisible(true);
3269 sky->setCloudsEnabled(true);
3270 } else if (*event.set_sky.type == "skybox" &&
3271 event.set_sky.params->size() == 6) {
3272 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3273 skybox = smgr->addSkyBoxSceneNode(
3274 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3275 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3276 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3277 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3278 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3279 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3281 // Handle everything else as plain color
3283 if (*event.set_sky.type != "plain")
3284 infostream << "Unknown sky type: "
3285 << (*event.set_sky.type) << std::endl;
3287 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3290 delete event.set_sky.bgcolor;
3291 delete event.set_sky.type;
3292 delete event.set_sky.params;
3295 case CE_OVERRIDE_DAY_NIGHT_RATIO:
3296 client->getEnv().setDayNightRatioOverride(
3297 event.override_day_night_ratio.do_override,
3298 event.override_day_night_ratio.ratio_f * 1000);
3301 case CE_CLOUD_PARAMS:
3303 clouds->setDensity(event.cloud_params.density);
3304 clouds->setColorBright(video::SColor(event.cloud_params.color_bright));
3305 clouds->setColorAmbient(video::SColor(event.cloud_params.color_ambient));
3306 clouds->setHeight(event.cloud_params.height);
3307 clouds->setThickness(event.cloud_params.thickness);
3308 clouds->setSpeed(v2f(
3309 event.cloud_params.speed_x,
3310 event.cloud_params.speed_y));
3315 // unknown or unhandled type
3323 void Game::updateCamera(u32 busy_time, f32 dtime)
3325 LocalPlayer *player = client->getEnv().getLocalPlayer();
3328 For interaction purposes, get info about the held item
3330 - Is it a usable item?
3331 - Can it point to liquids?
3333 ItemStack playeritem;
3335 InventoryList *mlist = local_inventory->getList("main");
3337 if (mlist && client->getPlayerItem() < mlist->getSize())
3338 playeritem = mlist->getItem(client->getPlayerItem());
3341 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3342 InventoryList *hlist = local_inventory->getList("hand");
3344 playeritem = hlist->getItem(0);
3348 ToolCapabilities playeritem_toolcap =
3349 playeritem.getToolCapabilities(itemdef_manager);
3351 v3s16 old_camera_offset = camera->getOffset();
3353 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3354 GenericCAO *playercao = player->getCAO();
3356 // If playercao not loaded, don't change camera
3357 if (playercao == NULL)
3360 camera->toggleCameraMode();
3362 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3363 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3366 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3367 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3369 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3370 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3372 camera->step(dtime);
3374 v3f camera_position = camera->getPosition();
3375 v3f camera_direction = camera->getDirection();
3376 f32 camera_fov = camera->getFovMax();
3377 v3s16 camera_offset = camera->getOffset();
3379 m_camera_offset_changed = (camera_offset != old_camera_offset);
3381 if (!flags.disable_camera_update) {
3382 client->getEnv().getClientMap().updateCamera(camera_position,
3383 camera_direction, camera_fov, camera_offset);
3385 if (m_camera_offset_changed) {
3386 client->updateCameraOffset(camera_offset);
3387 client->getEnv().updateCameraOffset(camera_offset);
3390 clouds->updateCameraOffset(camera_offset);
3396 void Game::updateSound(f32 dtime)
3398 // Update sound listener
3399 v3s16 camera_offset = camera->getOffset();
3400 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3401 v3f(0, 0, 0), // velocity
3402 camera->getDirection(),
3403 camera->getCameraNode()->getUpVector());
3404 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3407 // Update sound maker
3408 soundmaker->step(dtime);
3410 LocalPlayer *player = client->getEnv().getLocalPlayer();
3412 ClientMap &map = client->getEnv().getClientMap();
3413 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3414 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3418 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3420 LocalPlayer *player = client->getEnv().getLocalPlayer();
3422 ItemStack playeritem;
3424 InventoryList *mlist = local_inventory->getList("main");
3426 if (mlist && client->getPlayerItem() < mlist->getSize())
3427 playeritem = mlist->getItem(client->getPlayerItem());
3430 const ItemDefinition &playeritem_def =
3431 playeritem.getDefinition(itemdef_manager);
3432 InventoryList *hlist = local_inventory->getList("hand");
3433 const ItemDefinition &hand_def =
3434 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3436 v3f player_position = player->getPosition();
3437 v3f camera_position = camera->getPosition();
3438 v3f camera_direction = camera->getDirection();
3439 v3s16 camera_offset = camera->getOffset();
3443 Calculate what block is the crosshair pointing to
3446 f32 d = playeritem_def.range; // max. distance
3447 f32 d_hand = hand_def.range;
3449 if (d < 0 && d_hand >= 0)
3454 core::line3d<f32> shootline;
3456 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3457 shootline = core::line3d<f32>(camera_position,
3458 camera_position + camera_direction * BS * d);
3460 // prevent player pointing anything in front-view
3461 shootline = core::line3d<f32>(camera_position,camera_position);
3464 #ifdef HAVE_TOUCHSCREENGUI
3466 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3467 shootline = g_touchscreengui->getShootline();
3468 shootline.start += intToFloat(camera_offset, BS);
3469 shootline.end += intToFloat(camera_offset, BS);
3474 PointedThing pointed = updatePointedThing(shootline,
3475 playeritem_def.liquids_pointable,
3476 !runData.ldown_for_dig,
3479 if (pointed != runData.pointed_old) {
3480 infostream << "Pointing at " << pointed.dump() << std::endl;
3481 hud->updateSelectionMesh(camera_offset);
3486 - releasing left mouse button
3487 - pointing away from node
3489 if (runData.digging) {
3490 if (getLeftReleased()) {
3491 infostream << "Left button released"
3492 << " (stopped digging)" << std::endl;
3493 runData.digging = false;
3494 } else if (pointed != runData.pointed_old) {
3495 if (pointed.type == POINTEDTHING_NODE
3496 && runData.pointed_old.type == POINTEDTHING_NODE
3497 && pointed.node_undersurface
3498 == runData.pointed_old.node_undersurface) {
3499 // Still pointing to the same node, but a different face.
3502 infostream << "Pointing away from node"
3503 << " (stopped digging)" << std::endl;
3504 runData.digging = false;
3505 hud->updateSelectionMesh(camera_offset);
3509 if (!runData.digging) {
3510 client->interact(1, runData.pointed_old);
3511 client->setCrack(-1, v3s16(0, 0, 0));
3512 runData.dig_time = 0.0;
3514 } else if (runData.dig_instantly && getLeftReleased()) {
3515 // Remove e.g. torches faster when clicking instead of holding LMB
3516 runData.nodig_delay_timer = 0;
3517 runData.dig_instantly = false;
3520 if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3521 runData.ldown_for_dig = false;
3524 runData.left_punch = false;
3526 soundmaker->m_player_leftpunch_sound.name = "";
3528 if (isRightPressed())
3529 runData.repeat_rightclick_timer += dtime;
3531 runData.repeat_rightclick_timer = 0;
3533 if (playeritem_def.usable && isLeftPressed()) {
3534 if (getLeftClicked())
3535 client->interact(4, pointed);
3536 } else if (pointed.type == POINTEDTHING_NODE) {
3537 ToolCapabilities playeritem_toolcap =
3538 playeritem.getToolCapabilities(itemdef_manager);
3539 if (playeritem.name.empty()) {
3540 playeritem_toolcap = *hand_def.tool_capabilities;
3542 handlePointingAtNode(pointed, playeritem_def, playeritem_toolcap, dtime);
3543 } else if (pointed.type == POINTEDTHING_OBJECT) {
3544 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3545 } else if (isLeftPressed()) {
3546 // When button is held down in air, show continuous animation
3547 runData.left_punch = true;
3548 } else if (getRightClicked()) {
3549 handlePointingAtNothing(playeritem);
3552 runData.pointed_old = pointed;
3554 if (runData.left_punch || getLeftClicked())
3555 camera->setDigging(0); // left click animation
3557 input->resetLeftClicked();
3558 input->resetRightClicked();
3560 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3561 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3563 input->resetLeftReleased();
3564 input->resetRightReleased();
3566 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3567 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3571 PointedThing Game::updatePointedThing(
3572 const core::line3d<f32> &shootline,
3573 bool liquids_pointable,
3574 bool look_for_object,
3575 const v3s16 &camera_offset)
3577 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3578 selectionboxes->clear();
3579 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3580 static const bool show_entity_selectionbox = g_settings->getBool(
3581 "show_entity_selectionbox");
3583 ClientMap &map = client->getEnv().getClientMap();
3584 INodeDefManager *nodedef=client->getNodeDefManager();
3586 runData.selected_object = NULL;
3588 PointedThing result=client->getEnv().getPointedThing(
3589 shootline, liquids_pointable, look_for_object);
3590 if (result.type == POINTEDTHING_OBJECT) {
3591 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3592 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox()) {
3593 aabb3f *selection_box = runData.selected_object->getSelectionBox();
3595 // Box should exist because object was
3596 // returned in the first place
3598 assert(selection_box);
3600 v3f pos = runData.selected_object->getPosition();
3601 selectionboxes->push_back(aabb3f(
3602 selection_box->MinEdge, selection_box->MaxEdge));
3603 selectionboxes->push_back(
3604 aabb3f(selection_box->MinEdge, selection_box->MaxEdge));
3605 hud->setSelectionPos(pos, camera_offset);
3607 } else if (result.type == POINTEDTHING_NODE) {
3608 // Update selection boxes
3609 MapNode n = map.getNodeNoEx(result.node_undersurface);
3610 std::vector<aabb3f> boxes;
3611 n.getSelectionBoxes(nodedef, &boxes,
3612 n.getNeighbors(result.node_undersurface, &map));
3615 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3616 i != boxes.end(); ++i) {
3618 box.MinEdge -= v3f(d, d, d);
3619 box.MaxEdge += v3f(d, d, d);
3620 selectionboxes->push_back(box);
3622 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3624 hud->setSelectedFaceNormal(v3f(
3625 result.intersection_normal.X,
3626 result.intersection_normal.Y,
3627 result.intersection_normal.Z));
3630 // Update selection mesh light level and vertex colors
3631 if (selectionboxes->size() > 0) {
3632 v3f pf = hud->getSelectionPos();
3633 v3s16 p = floatToInt(pf, BS);
3635 // Get selection mesh light level
3636 MapNode n = map.getNodeNoEx(p);
3637 u16 node_light = getInteriorLight(n, -1, nodedef);
3638 u16 light_level = node_light;
3640 for (u8 i = 0; i < 6; i++) {
3641 n = map.getNodeNoEx(p + g_6dirs[i]);
3642 node_light = getInteriorLight(n, -1, nodedef);
3643 if (node_light > light_level)
3644 light_level = node_light;
3647 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3649 final_color_blend(&c, light_level, daynight_ratio);
3651 // Modify final color a bit with time
3652 u32 timer = porting::getTimeMs() % 5000;
3653 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3654 float sin_r = 0.08 * sin(timerf);
3655 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3656 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3658 core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3660 core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3662 core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3664 // Set mesh final color
3665 hud->setSelectionMeshColor(c);
3671 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3673 infostream << "Right Clicked in Air" << std::endl;
3674 PointedThing fauxPointed;
3675 fauxPointed.type = POINTEDTHING_NOTHING;
3676 client->interact(5, fauxPointed);
3680 void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
3681 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3683 v3s16 nodepos = pointed.node_undersurface;
3684 v3s16 neighbourpos = pointed.node_abovesurface;
3687 Check information text of node
3690 ClientMap &map = client->getEnv().getClientMap();
3691 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3694 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3696 MapNode n = map.getNodeNoEx(nodepos);
3698 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3699 infotext = L"Unknown node: ";
3700 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3704 if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3705 && client->checkPrivilege("interact")) {
3706 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3709 if ((getRightClicked() ||
3710 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3711 client->checkPrivilege("interact")) {
3712 runData.repeat_rightclick_timer = 0;
3713 infostream << "Ground right-clicked" << std::endl;
3715 if (meta && meta->getString("formspec") != "" && !random_input
3716 && !isKeyDown(KeyType::SNEAK)) {
3717 infostream << "Launching custom inventory view" << std::endl;
3719 InventoryLocation inventoryloc;
3720 inventoryloc.setNodeMeta(nodepos);
3722 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3723 &client->getEnv().getClientMap(), nodepos);
3724 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3726 create_formspec_menu(¤t_formspec, client,
3727 device, &input->joystick, fs_src, txt_dst);
3730 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3732 // Report right click to server
3734 camera->setDigging(1); // right click animation (always shown for feedback)
3736 // If the wielded item has node placement prediction,
3738 bool placed = nodePlacementPrediction(*client,
3740 nodepos, neighbourpos);
3744 client->interact(3, pointed);
3746 soundmaker->m_player_rightpunch_sound =
3747 playeritem_def.sound_place;
3749 if (client->moddingEnabled())
3750 client->getScript()->on_placenode(pointed, playeritem_def);
3752 soundmaker->m_player_rightpunch_sound =
3755 if (playeritem_def.node_placement_prediction == "" ||
3756 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3757 client->interact(3, pointed); // Report to server
3759 soundmaker->m_player_rightpunch_sound =
3760 playeritem_def.sound_place_failed;
3768 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3769 const v3f &player_position, bool show_debug)
3771 infotext = unescape_enriched(
3772 utf8_to_wide(runData.selected_object->infoText()));
3775 if (infotext != L"") {
3778 infotext += unescape_enriched(utf8_to_wide(
3779 runData.selected_object->debugInfoText()));
3782 if (isLeftPressed()) {
3783 bool do_punch = false;
3784 bool do_punch_damage = false;
3786 if (runData.object_hit_delay_timer <= 0.0) {
3788 do_punch_damage = true;
3789 runData.object_hit_delay_timer = object_hit_delay;
3792 if (getLeftClicked())
3796 infostream << "Left-clicked object" << std::endl;
3797 runData.left_punch = true;
3800 if (do_punch_damage) {
3801 // Report direct punch
3802 v3f objpos = runData.selected_object->getPosition();
3803 v3f dir = (objpos - player_position).normalize();
3804 ItemStack item = playeritem;
3805 if (playeritem.name.empty()) {
3806 InventoryList *hlist = local_inventory->getList("hand");
3808 item = hlist->getItem(0);
3812 bool disable_send = runData.selected_object->directReportPunch(
3813 dir, &item, runData.time_from_last_punch);
3814 runData.time_from_last_punch = 0;
3817 client->interact(0, pointed);
3819 } else if (getRightClicked()) {
3820 infostream << "Right-clicked object" << std::endl;
3821 client->interact(3, pointed); // place
3826 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3827 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3829 LocalPlayer *player = client->getEnv().getLocalPlayer();
3830 ClientMap &map = client->getEnv().getClientMap();
3831 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3833 // NOTE: Similar piece of code exists on the server side for
3835 // Get digging parameters
3836 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3837 &playeritem_toolcap);
3839 // If can't dig, try hand
3840 if (!params.diggable) {
3841 InventoryList *hlist = local_inventory->getList("hand");
3842 const ItemDefinition &hand =
3843 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3844 const ToolCapabilities *tp = hand.tool_capabilities;
3847 params = getDigParams(nodedef_manager->get(n).groups, tp);
3850 if (!runData.digging) {
3851 infostream << "Started digging" << std::endl;
3852 runData.dig_instantly = params.time == 0;
3853 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3855 client->interact(0, pointed);
3856 runData.digging = true;
3857 runData.ldown_for_dig = true;
3860 if (!params.diggable) {
3861 // I guess nobody will wait for this long
3862 runData.dig_time_complete = 10000000.0;
3864 runData.dig_time_complete = params.time;
3866 if (m_cache_enable_particles) {
3867 const ContentFeatures &features =
3868 client->getNodeDefManager()->get(n);
3869 client->getParticleManager()->addPunchingParticles(client, smgr,
3870 player, nodepos, n, features);
3874 if (!runData.dig_instantly) {
3875 runData.dig_index = (float)crack_animation_length
3877 / runData.dig_time_complete;
3879 // This is for e.g. torches
3880 runData.dig_index = crack_animation_length;
3883 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3885 if (sound_dig.exists() && params.diggable) {
3886 if (sound_dig.name == "__group") {
3887 if (params.main_group != "") {
3888 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3889 soundmaker->m_player_leftpunch_sound.name =
3890 std::string("default_dig_") +
3894 soundmaker->m_player_leftpunch_sound = sound_dig;
3898 // Don't show cracks if not diggable
3899 if (runData.dig_time_complete >= 100000.0) {
3900 } else if (runData.dig_index < crack_animation_length) {
3901 //TimeTaker timer("client.setTempMod");
3902 //infostream<<"dig_index="<<dig_index<<std::endl;
3903 client->setCrack(runData.dig_index, nodepos);
3905 infostream << "Digging completed" << std::endl;
3906 client->setCrack(-1, v3s16(0, 0, 0));
3908 runData.dig_time = 0;
3909 runData.digging = false;
3911 runData.nodig_delay_timer =
3912 runData.dig_time_complete / (float)crack_animation_length;
3914 // We don't want a corresponding delay to very time consuming nodes
3915 // and nodes without digging time (e.g. torches) get a fixed delay.
3916 if (runData.nodig_delay_timer > 0.3)
3917 runData.nodig_delay_timer = 0.3;
3918 else if (runData.dig_instantly)
3919 runData.nodig_delay_timer = 0.15;
3921 bool is_valid_position;
3922 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3923 if (is_valid_position) {
3924 if (client->moddingEnabled()) {
3925 if (client->getScript()->on_dignode(nodepos, wasnode)) {
3929 client->removeNode(nodepos);
3932 client->interact(2, pointed);
3934 if (m_cache_enable_particles) {
3935 const ContentFeatures &features =
3936 client->getNodeDefManager()->get(wasnode);
3937 client->getParticleManager()->addDiggingParticles(client, smgr,
3938 player, nodepos, wasnode, features);
3942 // Send event to trigger sound
3943 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3944 client->event()->put(e);
3947 if (runData.dig_time_complete < 100000.0) {
3948 runData.dig_time += dtime;
3950 runData.dig_time = 0;
3951 client->setCrack(-1, nodepos);
3954 camera->setDigging(0); // left click animation
3958 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
3959 const CameraOrientation &cam)
3961 LocalPlayer *player = client->getEnv().getLocalPlayer();
3967 if (draw_control->range_all) {
3968 runData.fog_range = 100000 * BS;
3970 runData.fog_range = draw_control->wanted_range * BS;
3974 Calculate general brightness
3976 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3977 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3978 float direct_brightness;
3981 if (m_cache_enable_noclip && m_cache_enable_free_move) {
3982 direct_brightness = time_brightness;
3983 sunlight_seen = true;
3985 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3986 float old_brightness = sky->getBrightness();
3987 direct_brightness = client->getEnv().getClientMap()
3988 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
3989 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3993 float time_of_day_smooth = runData.time_of_day_smooth;
3994 float time_of_day = client->getEnv().getTimeOfDayF();
3996 static const float maxsm = 0.05;
3997 static const float todsm = 0.05;
3999 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4000 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4001 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4002 time_of_day_smooth = time_of_day;
4004 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4005 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4006 + (time_of_day + 1.0) * todsm;
4008 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4009 + time_of_day * todsm;
4011 runData.time_of_day = time_of_day;
4012 runData.time_of_day_smooth = time_of_day_smooth;
4014 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4015 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4016 player->getPitch());
4022 v3f player_position = player->getPosition();
4023 if (sky->getCloudsVisible()) {
4024 clouds->setVisible(true);
4025 clouds->step(dtime);
4026 clouds->update(v2f(player_position.X, player_position.Z),
4027 sky->getCloudColor());
4029 clouds->setVisible(false);
4036 client->getParticleManager()->step(dtime);
4042 if (m_cache_enable_fog && !flags.force_fog_off) {
4045 video::EFT_FOG_LINEAR,
4046 runData.fog_range * m_cache_fog_start,
4047 runData.fog_range * 1.0,
4055 video::EFT_FOG_LINEAR,
4065 Get chat messages from client
4068 v2u32 screensize = driver->getScreenSize();
4070 updateChat(*client, dtime, flags.show_debug, screensize,
4071 flags.show_chat, runData.profiler_current_page,
4072 *chat_backend, guitext_chat);
4078 if (client->getPlayerItem() != runData.new_playeritem)
4079 client->selectPlayerItem(runData.new_playeritem);
4081 // Update local inventory if it has changed
4082 if (client->getLocalInventoryUpdated()) {
4083 //infostream<<"Updating local inventory"<<std::endl;
4084 client->getLocalInventory(*local_inventory);
4085 runData.update_wielded_item_trigger = true;
4088 if (runData.update_wielded_item_trigger) {
4089 // Update wielded tool
4090 InventoryList *mlist = local_inventory->getList("main");
4092 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4093 ItemStack item = mlist->getItem(client->getPlayerItem());
4094 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4095 InventoryList *hlist = local_inventory->getList("hand");
4097 item = hlist->getItem(0);
4099 camera->wield(item);
4102 runData.update_wielded_item_trigger = false;
4106 Update block draw list every 200ms or when camera direction has
4109 runData.update_draw_list_timer += dtime;
4111 v3f camera_direction = camera->getDirection();
4112 if (runData.update_draw_list_timer >= 0.2
4113 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4114 || m_camera_offset_changed) {
4115 runData.update_draw_list_timer = 0;
4116 client->getEnv().getClientMap().updateDrawList(driver);
4117 runData.update_draw_list_last_cam_dir = camera_direction;
4120 updateGui(*stats, dtime, cam);
4123 make sure menu is on top
4124 1. Delete formspec menu reference if menu was removed
4125 2. Else, make sure formspec menu is on top
4127 if (current_formspec) {
4128 if (current_formspec->getReferenceCount() == 1) {
4129 current_formspec->drop();
4130 current_formspec = NULL;
4131 } else if (!noMenuActive()) {
4132 guiroot->bringToFront(current_formspec);
4140 const video::SColor &skycolor = sky->getSkyColor();
4142 TimeTaker tt_draw("mainloop: draw");
4143 driver->beginScene(true, true, skycolor);
4145 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4146 guienv, screensize, skycolor, flags.show_hud,
4147 flags.show_minimap);
4152 if (flags.show_profiler_graph)
4153 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4158 if (runData.damage_flash > 0.0) {
4159 video::SColor color(runData.damage_flash, 180, 0, 0);
4160 driver->draw2DRectangle(color,
4161 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4164 runData.damage_flash -= 100.0 * dtime;
4170 if (player->hurt_tilt_timer > 0.0) {
4171 player->hurt_tilt_timer -= dtime * 5;
4173 if (player->hurt_tilt_timer < 0)
4174 player->hurt_tilt_strength = 0;
4178 Update minimap pos and rotation
4180 if (flags.show_minimap && flags.show_hud) {
4181 mapper->setPos(floatToInt(player->getPosition(), BS));
4182 mapper->setAngle(player->getYaw());
4190 stats->drawtime = tt_draw.stop(true);
4191 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4195 inline static const char *yawToDirectionString(int yaw)
4197 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4199 yaw = wrapDegrees_0_360(yaw);
4200 yaw = (yaw + 45) % 360 / 90;
4202 return direction[yaw];
4206 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4208 v2u32 screensize = driver->getScreenSize();
4209 LocalPlayer *player = client->getEnv().getLocalPlayer();
4210 v3f player_position = player->getPosition();
4212 if (flags.show_debug) {
4213 static float drawtime_avg = 0;
4214 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4216 u16 fps = 1.0 / stats.dtime_jitter.avg;
4218 std::ostringstream os(std::ios_base::binary);
4220 << PROJECT_NAME_C " " << g_version_hash
4222 << " (R: range_all=" << draw_control->range_all << ")"
4223 << std::setprecision(0)
4224 << " drawtime = " << drawtime_avg
4225 << std::setprecision(1)
4226 << ", dtime_jitter = "
4227 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4228 << std::setprecision(1)
4229 << ", v_range = " << draw_control->wanted_range
4230 << std::setprecision(3)
4231 << ", RTT = " << client->getRTT();
4232 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4233 guitext->setVisible(true);
4235 guitext->setVisible(false);
4238 if (guitext->isVisible()) {
4239 core::rect<s32> rect(
4241 screensize.X, 5 + g_fontengine->getTextHeight()
4243 guitext->setRelativePosition(rect);
4246 if (flags.show_debug) {
4247 std::ostringstream os(std::ios_base::binary);
4248 os << std::setprecision(1) << std::fixed
4249 << "(" << (player_position.X / BS)
4250 << ", " << (player_position.Y / BS)
4251 << ", " << (player_position.Z / BS)
4252 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4253 << " " << yawToDirectionString(cam.camera_yaw)
4254 << ") (seed = " << ((u64)client->getMapSeed())
4257 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4258 ClientMap &map = client->getEnv().getClientMap();
4259 const INodeDefManager *nodedef = client->getNodeDefManager();
4260 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4261 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4262 const ContentFeatures &features = nodedef->get(n);
4263 os << " (pointing_at = " << nodedef->get(n).name
4264 << " - " << features.tiledef[0].name.c_str()
4269 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4270 guitext2->setVisible(true);
4272 core::rect<s32> rect(
4273 5, 5 + g_fontengine->getTextHeight(),
4274 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4276 guitext2->setRelativePosition(rect);
4278 guitext2->setVisible(false);
4281 setStaticText(guitext_info, infotext.c_str());
4282 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4284 float statustext_time_max = 1.5;
4286 if (!m_statustext.empty()) {
4287 runData.statustext_time += dtime;
4289 if (runData.statustext_time >= statustext_time_max) {
4291 runData.statustext_time = 0;
4295 setStaticText(guitext_status, m_statustext.c_str());
4296 guitext_status->setVisible(!m_statustext.empty());
4298 if (!m_statustext.empty()) {
4299 s32 status_width = guitext_status->getTextWidth();
4300 s32 status_height = guitext_status->getTextHeight();
4301 s32 status_y = screensize.Y - 150;
4302 s32 status_x = (screensize.X - status_width) / 2;
4303 core::rect<s32> rect(
4304 status_x , status_y - status_height,
4305 status_x + status_width, status_y
4307 guitext_status->setRelativePosition(rect);
4310 video::SColor initial_color(255, 0, 0, 0);
4312 if (guienv->getSkin())
4313 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4315 video::SColor final_color = initial_color;
4316 final_color.setAlpha(0);
4317 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4318 initial_color, final_color,
4319 pow(runData.statustext_time / statustext_time_max, 2.0f));
4320 guitext_status->setOverrideColor(fade_color);
4321 guitext_status->enableOverrideColor(true);
4326 /* Log times and stuff for visualization */
4327 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4329 Profiler::GraphValues values;
4330 g_profiler->graphGet(values);
4336 /****************************************************************************
4338 ****************************************************************************/
4340 /* On some computers framerate doesn't seem to be automatically limited
4342 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4344 // not using getRealTime is necessary for wine
4345 device->getTimer()->tick(); // Maker sure device time is up-to-date
4346 u32 time = device->getTimer()->getTime();
4347 u32 last_time = fps_timings->last_time;
4349 if (time > last_time) // Make sure time hasn't overflowed
4350 fps_timings->busy_time = time - last_time;
4352 fps_timings->busy_time = 0;
4354 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4355 ? g_settings->getFloat("pause_fps_max")
4356 : g_settings->getFloat("fps_max"));
4358 if (fps_timings->busy_time < frametime_min) {
4359 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4360 device->sleep(fps_timings->sleep_time);
4362 fps_timings->sleep_time = 0;
4365 /* Get the new value of the device timer. Note that device->sleep() may
4366 * not sleep for the entire requested time as sleep may be interrupted and
4367 * therefore it is arguably more accurate to get the new time from the
4368 * device rather than calculating it by adding sleep_time to time.
4371 device->getTimer()->tick(); // Update device timer
4372 time = device->getTimer()->getTime();
4374 if (time > last_time) // Make sure last_time hasn't overflowed
4375 *dtime = (time - last_time) / 1000.0;
4379 fps_timings->last_time = time;
4382 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4383 // pass a copy of it to this function
4384 // Note: \p msg must be allocated using new (not malloc())
4385 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4386 int percent, bool draw_clouds)
4388 draw_load_screen(msg, device, guienv, texture_src, dtime, percent,
4393 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4395 ((Game *)data)->readSettings();
4398 void Game::readSettings()
4400 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4401 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4402 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4403 m_cache_enable_particles = g_settings->getBool("enable_particles");
4404 m_cache_enable_fog = g_settings->getBool("enable_fog");
4405 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4406 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4407 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4409 m_cache_enable_noclip = g_settings->getBool("noclip");
4410 m_cache_enable_free_move = g_settings->getBool("free_move");
4412 m_cache_fog_start = g_settings->getFloat("fog_start");
4414 m_cache_cam_smoothing = 0;
4415 if (g_settings->getBool("cinematic"))
4416 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4418 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4420 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4421 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4422 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4426 /****************************************************************************/
4427 /****************************************************************************
4429 ****************************************************************************/
4430 /****************************************************************************/
4432 void Game::extendedResourceCleanup()
4434 // Extended resource accounting
4435 infostream << "Irrlicht resources after cleanup:" << std::endl;
4436 infostream << "\tRemaining meshes : "
4437 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4438 infostream << "\tRemaining textures : "
4439 << driver->getTextureCount() << std::endl;
4441 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4442 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4443 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4447 clearTextureNameCache();
4448 infostream << "\tRemaining materials: "
4449 << driver-> getMaterialRendererCount()
4450 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4453 void Game::showPauseMenu()
4456 static const std::string control_text = strgettext("Default Controls:\n"
4457 "No menu visible:\n"
4458 "- single tap: button activate\n"
4459 "- double tap: place/use\n"
4460 "- slide finger: look around\n"
4461 "Menu/Inventory visible:\n"
4462 "- double tap (outside):\n"
4464 "- touch stack, touch slot:\n"
4466 "- touch&drag, tap 2nd finger\n"
4467 " --> place single item to slot\n"
4470 static const std::string control_text = strgettext("Default Controls:\n"
4472 "- Space: jump/climb\n"
4473 "- Shift: sneak/go down\n"
4476 "- Mouse: turn/look\n"
4477 "- Mouse left: dig/punch\n"
4478 "- Mouse right: place/use\n"
4479 "- Mouse wheel: select item\n"
4484 float ypos = simple_singleplayer_mode ? 0.5 : 0.1;
4485 std::ostringstream os;
4487 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4488 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4489 << strgettext("Continue") << "]";
4491 if (!simple_singleplayer_mode) {
4492 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4493 << strgettext("Change Password") << "]";
4497 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4498 << strgettext("Sound Volume") << "]";
4499 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4500 << strgettext("Change Keys") << "]";
4502 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4503 << strgettext("Exit to Menu") << "]";
4504 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4505 << strgettext("Exit to OS") << "]"
4506 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4507 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
4508 << g_build_info << "\n"
4509 << "path_user = " << wrap_rows(porting::path_user, 20)
4513 /* Note: FormspecFormSource and LocalFormspecHandler *
4514 * are deleted by guiFormSpecMenu */
4515 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4516 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4518 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
4519 current_formspec->setFocus("btn_continue");
4520 current_formspec->doPause = true;
4523 /****************************************************************************/
4524 /****************************************************************************
4525 extern function for launching the game
4526 ****************************************************************************/
4527 /****************************************************************************/
4529 void the_game(bool *kill,
4531 InputHandler *input,
4532 IrrlichtDevice *device,
4534 const std::string &map_dir,
4535 const std::string &playername,
4536 const std::string &password,
4537 const std::string &address, // If empty local server is created
4540 std::string &error_message,
4541 ChatBackend &chat_backend,
4542 bool *reconnect_requested,
4543 const SubgameSpec &gamespec, // Used for local game
4544 bool simple_singleplayer_mode)
4548 /* Make a copy of the server address because if a local singleplayer server
4549 * is created then this is updated and we don't want to change the value
4550 * passed to us by the calling function
4552 std::string server_address = address;
4556 if (game.startup(kill, random_input, input, device, map_dir,
4557 playername, password, &server_address, port, error_message,
4558 reconnect_requested, &chat_backend, gamespec,
4559 simple_singleplayer_mode)) {
4564 } catch (SerializationError &e) {
4565 error_message = std::string("A serialization error occurred:\n")
4566 + e.what() + "\n\nThe server is probably "
4567 " running a different version of " PROJECT_NAME_C ".";
4568 errorstream << error_message << std::endl;
4569 } catch (ServerError &e) {
4570 error_message = e.what();
4571 errorstream << "ServerError: " << error_message << std::endl;
4572 } catch (ModError &e) {
4573 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4574 errorstream << "ModError: " << error_message << std::endl;