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.
24 #include "client/renderingengine.h"
27 #include "client/inputhandler.h"
28 #include "client/tile.h" // For TextureSource
29 #include "client/keys.h"
30 #include "client/joystick_controller.h"
31 #include "clientmap.h"
34 #include "content_cao.h"
35 #include "event_manager.h"
36 #include "fontengine.h"
41 #include "guiChatConsole.h"
42 #include "guiFormSpecMenu.h"
43 #include "guiKeyChangeMenu.h"
44 #include "guiPasswordChange.h"
45 #include "guiVolumeChange.h"
46 #include "mainmenumanager.h"
49 #include "nodedef.h" // Needed for determining pointing to nodes
50 #include "nodemetadata.h"
51 #include "particles.h"
53 #include "quicktune_shortcutter.h"
61 #include "util/basic_macros.h"
62 #include "util/directiontables.h"
63 #include "util/pointedthing.h"
64 #include "irrlicht_changes/static_text.h"
66 #include "script/scripting_client.h"
69 #include "sound_openal.h"
77 struct TextDestNodeMetadata : public TextDest
79 TextDestNodeMetadata(v3s16 p, Client *client)
84 // This is deprecated I guess? -celeron55
85 void gotText(const std::wstring &text)
87 std::string ntext = wide_to_utf8(text);
88 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
89 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
91 fields["text"] = ntext;
92 m_client->sendNodemetaFields(m_p, "", fields);
94 void gotText(const StringMap &fields)
96 m_client->sendNodemetaFields(m_p, "", fields);
103 struct TextDestPlayerInventory : public TextDest
105 TextDestPlayerInventory(Client *client)
110 TextDestPlayerInventory(Client *client, const std::string &formname)
113 m_formname = formname;
115 void gotText(const StringMap &fields)
117 m_client->sendInventoryFields(m_formname, fields);
123 struct LocalFormspecHandler : public TextDest
125 LocalFormspecHandler(const std::string &formname)
127 m_formname = formname;
130 LocalFormspecHandler(const std::string &formname, Client *client):
133 m_formname = formname;
136 void gotText(const StringMap &fields)
138 if (m_formname == "MT_PAUSE_MENU") {
139 if (fields.find("btn_sound") != fields.end()) {
140 g_gamecallback->changeVolume();
144 if (fields.find("btn_key_config") != fields.end()) {
145 g_gamecallback->keyConfig();
149 if (fields.find("btn_exit_menu") != fields.end()) {
150 g_gamecallback->disconnect();
154 if (fields.find("btn_exit_os") != fields.end()) {
155 g_gamecallback->exitToOS();
157 RenderingEngine::get_raw_device()->closeDevice();
162 if (fields.find("btn_change_password") != fields.end()) {
163 g_gamecallback->changePassword();
167 if (fields.find("quit") != fields.end()) {
171 if (fields.find("btn_continue") != fields.end()) {
176 // Don't disable this part when modding is disabled, it's used in builtin
177 if (m_client && m_client->getScript())
178 m_client->getScript()->on_formspec_input(m_formname, fields);
181 Client *m_client = nullptr;
184 /* Form update callback */
186 class NodeMetadataFormSource: public IFormSource
189 NodeMetadataFormSource(ClientMap *map, v3s16 p):
194 std::string getForm()
196 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
201 return meta->getString("formspec");
204 virtual std::string resolveText(const std::string &str)
206 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
211 return meta->resolveString(str);
218 class PlayerInventoryFormSource: public IFormSource
221 PlayerInventoryFormSource(Client *client):
225 std::string getForm()
227 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
228 return player->inventory_formspec;
234 /* Profiler display */
236 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
237 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
239 if (show_profiler == 0) {
240 guitext_profiler->setVisible(false);
243 std::ostringstream os(std::ios_base::binary);
244 g_profiler->printPage(os, show_profiler, show_profiler_max);
245 std::wstring text = utf8_to_wide(os.str());
246 setStaticText(guitext_profiler, text.c_str());
247 guitext_profiler->setVisible(true);
249 s32 w = fe->getTextWidth(text);
254 unsigned text_height = fe->getTextHeight();
256 core::position2di upper_left, lower_right;
259 upper_left.Y = (text_height + 5) * 2;
260 lower_right.X = 12 + w;
261 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
263 if (lower_right.Y > screen_height * 2 / 3)
264 lower_right.Y = screen_height * 2 / 3;
266 core::rect<s32> rect(upper_left, lower_right);
268 guitext_profiler->setRelativePosition(rect);
269 guitext_profiler->setVisible(true);
277 Profiler::GraphValues values;
283 Meta(float initial = 0,
284 video::SColor color = video::SColor(255, 255, 255, 255)):
290 std::deque<Piece> m_log;
292 u32 m_log_max_size = 200;
294 ProfilerGraph() = default;
296 void put(const Profiler::GraphValues &values)
299 piece.values = values;
300 m_log.push_back(piece);
302 while (m_log.size() > m_log_max_size)
303 m_log.erase(m_log.begin());
306 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
307 gui::IGUIFont *font) const
309 // Do *not* use UNORDERED_MAP here as the order needs
310 // to be the same for each call to prevent flickering
311 std::map<std::string, Meta> m_meta;
313 for (const Piece &piece : m_log) {
314 for (const auto &i : piece.values) {
315 const std::string &id = i.first;
316 const float &value = i.second;
317 std::map<std::string, Meta>::iterator j = m_meta.find(id);
319 if (j == m_meta.end()) {
320 m_meta[id] = Meta(value);
324 if (value < j->second.min)
325 j->second.min = value;
327 if (value > j->second.max)
328 j->second.max = value;
333 static const video::SColor usable_colors[] = {
334 video::SColor(255, 255, 100, 100),
335 video::SColor(255, 90, 225, 90),
336 video::SColor(255, 100, 100, 255),
337 video::SColor(255, 255, 150, 50),
338 video::SColor(255, 220, 220, 100)
340 static const u32 usable_colors_count =
341 sizeof(usable_colors) / sizeof(*usable_colors);
342 u32 next_color_i = 0;
344 for (auto &i : m_meta) {
345 Meta &meta = i.second;
346 video::SColor color(255, 200, 200, 200);
348 if (next_color_i < usable_colors_count)
349 color = usable_colors[next_color_i++];
355 s32 textx = x_left + m_log_max_size + 15;
356 s32 textx2 = textx + 200 - 15;
359 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
360 i != m_meta.end(); ++i) {
361 const std::string &id = i->first;
362 const Meta &meta = i->second;
364 s32 y = y_bottom - meta_i * 50;
365 float show_min = meta.min;
366 float show_max = meta.max;
368 if (show_min >= -0.0001 && show_max >= -0.0001) {
369 if (show_min <= show_max * 0.5)
375 snprintf(buf, 10, "%.3g", show_max);
376 font->draw(utf8_to_wide(buf).c_str(),
377 core::rect<s32>(textx, y - graphh,
378 textx2, y - graphh + texth),
380 snprintf(buf, 10, "%.3g", show_min);
381 font->draw(utf8_to_wide(buf).c_str(),
382 core::rect<s32>(textx, y - texth,
385 font->draw(utf8_to_wide(id).c_str(),
386 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
387 textx2, y - graphh / 2 + texth / 2),
390 s32 graph1h = graphh;
391 bool relativegraph = (show_min != 0 && show_min != show_max);
392 float lastscaledvalue = 0.0;
393 bool lastscaledvalue_exists = false;
395 for (const Piece &piece : m_log) {
397 bool value_exists = false;
398 Profiler::GraphValues::const_iterator k =
399 piece.values.find(id);
401 if (k != piece.values.end()) {
408 lastscaledvalue_exists = false;
412 float scaledvalue = 1.0;
414 if (show_max != show_min)
415 scaledvalue = (value - show_min) / (show_max - show_min);
417 if (scaledvalue == 1.0 && value == 0) {
419 lastscaledvalue_exists = false;
424 if (lastscaledvalue_exists) {
425 s32 ivalue1 = lastscaledvalue * graph1h;
426 s32 ivalue2 = scaledvalue * graph1h;
427 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
428 v2s32(x, graph1y - ivalue2), meta.color);
431 lastscaledvalue = scaledvalue;
432 lastscaledvalue_exists = true;
434 s32 ivalue = scaledvalue * graph1h;
435 driver->draw2DLine(v2s32(x, graph1y),
436 v2s32(x, graph1y - ivalue), meta.color);
447 class NodeDugEvent: public MtEvent
453 NodeDugEvent(v3s16 p, MapNode n):
457 const char *getType() const
465 ISoundManager *m_sound;
466 INodeDefManager *m_ndef;
468 bool makes_footstep_sound;
469 float m_player_step_timer;
471 SimpleSoundSpec m_player_step_sound;
472 SimpleSoundSpec m_player_leftpunch_sound;
473 SimpleSoundSpec m_player_rightpunch_sound;
475 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
478 makes_footstep_sound(true),
479 m_player_step_timer(0)
483 void playPlayerStep()
485 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
486 m_player_step_timer = 0.03;
487 if (makes_footstep_sound)
488 m_sound->playSound(m_player_step_sound, false);
492 static void viewBobbingStep(MtEvent *e, void *data)
494 SoundMaker *sm = (SoundMaker *)data;
495 sm->playPlayerStep();
498 static void playerRegainGround(MtEvent *e, void *data)
500 SoundMaker *sm = (SoundMaker *)data;
501 sm->playPlayerStep();
504 static void playerJump(MtEvent *e, void *data)
506 //SoundMaker *sm = (SoundMaker*)data;
509 static void cameraPunchLeft(MtEvent *e, void *data)
511 SoundMaker *sm = (SoundMaker *)data;
512 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
515 static void cameraPunchRight(MtEvent *e, void *data)
517 SoundMaker *sm = (SoundMaker *)data;
518 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
521 static void nodeDug(MtEvent *e, void *data)
523 SoundMaker *sm = (SoundMaker *)data;
524 NodeDugEvent *nde = (NodeDugEvent *)e;
525 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
528 static void playerDamage(MtEvent *e, void *data)
530 SoundMaker *sm = (SoundMaker *)data;
531 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
534 static void playerFallingDamage(MtEvent *e, void *data)
536 SoundMaker *sm = (SoundMaker *)data;
537 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
540 void registerReceiver(MtEventManager *mgr)
542 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
543 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
544 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
545 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
546 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
547 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
548 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
549 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
552 void step(float dtime)
554 m_player_step_timer -= dtime;
558 // Locally stored sounds don't need to be preloaded because of this
559 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
561 std::set<std::string> m_fetched;
563 void paths_insert(std::set<std::string> &dst_paths,
564 const std::string &base,
565 const std::string &name)
567 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
568 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
569 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
570 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
571 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
572 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
573 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
574 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
575 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
576 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
577 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
580 void fetchSounds(const std::string &name,
581 std::set<std::string> &dst_paths,
582 std::set<std::string> &dst_datas)
584 if (m_fetched.count(name))
587 m_fetched.insert(name);
589 paths_insert(dst_paths, porting::path_share, name);
590 paths_insert(dst_paths, porting::path_user, name);
595 // before 1.8 there isn't a "integer interface", only float
596 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
597 typedef f32 SamplerLayer_t;
599 typedef s32 SamplerLayer_t;
603 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
606 bool *m_force_fog_off;
609 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
610 CachedPixelShaderSetting<float> m_fog_distance;
611 CachedVertexShaderSetting<float> m_animation_timer_vertex;
612 CachedPixelShaderSetting<float> m_animation_timer_pixel;
613 CachedPixelShaderSetting<float, 3> m_day_light;
614 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
615 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
616 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
617 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
618 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
619 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
623 void onSettingsChange(const std::string &name)
625 if (name == "enable_fog")
626 m_fog_enabled = g_settings->getBool("enable_fog");
629 static void settingsCallback(const std::string &name, void *userdata)
631 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
634 void setSky(Sky *sky) { m_sky = sky; }
636 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
637 f32 *fog_range, Client *client) :
639 m_force_fog_off(force_fog_off),
640 m_fog_range(fog_range),
641 m_sky_bg_color("skyBgColor"),
642 m_fog_distance("fogDistance"),
643 m_animation_timer_vertex("animationTimer"),
644 m_animation_timer_pixel("animationTimer"),
645 m_day_light("dayLight"),
646 m_eye_position_pixel("eyePosition"),
647 m_eye_position_vertex("eyePosition"),
648 m_minimap_yaw("yawVec"),
649 m_base_texture("baseTexture"),
650 m_normal_texture("normalTexture"),
651 m_texture_flags("textureFlags"),
654 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
655 m_fog_enabled = g_settings->getBool("enable_fog");
658 ~GameGlobalShaderConstantSetter()
660 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
663 virtual void onSetConstants(video::IMaterialRendererServices *services,
670 video::SColor bgcolor = m_sky->getBgColor();
671 video::SColorf bgcolorf(bgcolor);
672 float bgcolorfa[4] = {
678 m_sky_bg_color.set(bgcolorfa, services);
681 float fog_distance = 10000 * BS;
683 if (m_fog_enabled && !*m_force_fog_off)
684 fog_distance = *m_fog_range;
686 m_fog_distance.set(&fog_distance, services);
688 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
689 video::SColorf sunlight;
690 get_sunlight_color(&sunlight, daynight_ratio);
695 m_day_light.set(dnc, services);
697 u32 animation_timer = porting::getTimeMs() % 100000;
698 float animation_timer_f = (float)animation_timer / 100000.f;
699 m_animation_timer_vertex.set(&animation_timer_f, services);
700 m_animation_timer_pixel.set(&animation_timer_f, services);
702 float eye_position_array[3];
703 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
704 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
705 eye_position_array[0] = epos.X;
706 eye_position_array[1] = epos.Y;
707 eye_position_array[2] = epos.Z;
709 epos.getAs3Values(eye_position_array);
711 m_eye_position_pixel.set(eye_position_array, services);
712 m_eye_position_vertex.set(eye_position_array, services);
714 if (m_client->getMinimap()) {
715 float minimap_yaw_array[3];
716 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
717 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
718 minimap_yaw_array[0] = minimap_yaw.X;
719 minimap_yaw_array[1] = minimap_yaw.Y;
720 minimap_yaw_array[2] = minimap_yaw.Z;
722 minimap_yaw.getAs3Values(minimap_yaw_array);
724 m_minimap_yaw.set(minimap_yaw_array, services);
727 SamplerLayer_t base_tex = 0,
730 m_base_texture.set(&base_tex, services);
731 m_normal_texture.set(&normal_tex, services);
732 m_texture_flags.set(&flags_tex, services);
737 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
740 bool *m_force_fog_off;
743 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
745 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
746 f32 *fog_range, Client *client) :
748 m_force_fog_off(force_fog_off),
749 m_fog_range(fog_range),
753 void setSky(Sky *sky) {
755 for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
756 ggscs->setSky(m_sky);
758 created_nosky.clear();
761 virtual IShaderConstantSetter* create()
763 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
764 m_sky, m_force_fog_off, m_fog_range, m_client);
766 created_nosky.push_back(scs);
772 bool nodePlacementPrediction(Client &client, const ItemDefinition &playeritem_def,
773 const ItemStack &playeritem, v3s16 nodepos, v3s16 neighbourpos)
775 std::string prediction = playeritem_def.node_placement_prediction;
776 INodeDefManager *nodedef = client.ndef();
777 ClientMap &map = client.getEnv().getClientMap();
779 bool is_valid_position;
781 node = map.getNodeNoEx(nodepos, &is_valid_position);
782 if (!is_valid_position)
785 if (!prediction.empty() && !nodedef->get(node).rightclickable) {
786 verbosestream << "Node placement prediction for "
787 << playeritem_def.name << " is "
788 << prediction << std::endl;
789 v3s16 p = neighbourpos;
791 // Place inside node itself if buildable_to
792 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
793 if (is_valid_position)
795 if (nodedef->get(n_under).buildable_to)
798 node = map.getNodeNoEx(p, &is_valid_position);
799 if (is_valid_position &&!nodedef->get(node).buildable_to)
804 // Find id of predicted node
806 bool found = nodedef->getId(prediction, id);
809 errorstream << "Node placement prediction failed for "
810 << playeritem_def.name << " (places "
812 << ") - Name not known" << std::endl;
816 const ContentFeatures &predicted_f = nodedef->get(id);
818 // Predict param2 for facedir and wallmounted nodes
821 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
822 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
823 v3s16 dir = nodepos - neighbourpos;
825 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
826 param2 = dir.Y < 0 ? 1 : 0;
827 } else if (abs(dir.X) > abs(dir.Z)) {
828 param2 = dir.X < 0 ? 3 : 2;
830 param2 = dir.Z < 0 ? 5 : 4;
834 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
835 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
836 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
838 if (abs(dir.X) > abs(dir.Z)) {
839 param2 = dir.X < 0 ? 3 : 1;
841 param2 = dir.Z < 0 ? 2 : 0;
847 //Check attachment if node is in group attached_node
848 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
849 static v3s16 wallmounted_dirs[8] = {
859 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
860 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
861 pp = p + wallmounted_dirs[param2];
863 pp = p + v3s16(0, -1, 0);
865 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
870 if ((predicted_f.param_type_2 == CPT2_COLOR
871 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
872 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
873 const std::string &indexstr = playeritem.metadata.getString(
875 if (!indexstr.empty()) {
876 s32 index = mystoi(indexstr);
877 if (predicted_f.param_type_2 == CPT2_COLOR) {
879 } else if (predicted_f.param_type_2
880 == CPT2_COLORED_WALLMOUNTED) {
881 // param2 = pure palette index + other
882 param2 = (index & 0xf8) | (param2 & 0x07);
883 } else if (predicted_f.param_type_2
884 == CPT2_COLORED_FACEDIR) {
885 // param2 = pure palette index + other
886 param2 = (index & 0xe0) | (param2 & 0x1f);
891 // Add node to client map
892 MapNode n(id, 0, param2);
895 LocalPlayer *player = client.getEnv().getLocalPlayer();
897 // Dont place node when player would be inside new node
898 // NOTE: This is to be eventually implemented by a mod as client-side Lua
899 if (!nodedef->get(n).walkable ||
900 g_settings->getBool("enable_build_where_you_stand") ||
901 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
902 (nodedef->get(n).walkable &&
903 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
904 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
906 // This triggers the required mesh update too
907 client.addNode(p, n);
910 } catch (InvalidPositionException &e) {
911 errorstream << "Node placement prediction failed for "
912 << playeritem_def.name << " (places "
914 << ") - Position not loaded" << std::endl;
921 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
922 Client *client, JoystickController *joystick,
923 IFormSource *fs_src, TextDest *txt_dest)
926 if (*cur_formspec == 0) {
927 *cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
928 client, client->getTextureSource(), fs_src, txt_dest);
929 (*cur_formspec)->doPause = false;
932 Caution: do not call (*cur_formspec)->drop() here --
933 the reference might outlive the menu, so we will
934 periodically check if *cur_formspec is the only
935 remaining reference (i.e. the menu was removed)
936 and delete it in that case.
940 (*cur_formspec)->setFormSource(fs_src);
941 (*cur_formspec)->setTextDest(txt_dest);
947 #define SIZE_TAG "size[11,5.5]"
949 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
952 /******************************************************************************/
953 static void updateChat(Client &client, f32 dtime, bool show_debug,
954 const v2u32 &screensize, bool show_chat, u32 show_profiler,
955 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
957 // Add chat log output for errors to be shown in chat
958 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
960 // Get new messages from error log buffer
961 while (!chat_log_error_buf.empty()) {
962 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
963 if (!g_settings->getBool("disable_escape_sequences")) {
964 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
966 chat_backend.addMessage(L"", error_message);
969 // Get new messages from client
970 std::wstring message;
971 while (client.getChatMessage(message)) {
972 chat_backend.addUnparsedMessage(message);
975 // Remove old messages
976 chat_backend.step(dtime);
978 // Display all messages in a static text element
979 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
980 EnrichedString recent_chat = chat_backend.getRecentChat();
981 unsigned int line_height = g_fontengine->getLineHeight();
983 setStaticText(guitext_chat, recent_chat);
985 // Update gui element size and position
989 chat_y += 3 * line_height;
991 // first pass to calculate height of text to be set
992 const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
993 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
995 core::rect<s32> rect(10, chat_y, width, chat_y + window_size.Y);
996 guitext_chat->setRelativePosition(rect);
998 //now use real height of text and adjust rect according to this size
999 rect = core::rect<s32>(10, chat_y, width,
1000 chat_y + guitext_chat->getTextHeight());
1003 guitext_chat->setRelativePosition(rect);
1004 // Don't show chat if disabled or empty or profiler is enabled
1005 guitext_chat->setVisible(
1006 show_chat && recent_chat_count != 0 && !show_profiler);
1010 /****************************************************************************
1011 Fast key cache for main game loop
1012 ****************************************************************************/
1014 /* This is faster than using getKeySetting with the tradeoff that functions
1015 * using it must make sure that it's initialised before using it and there is
1016 * no error handling (for example bounds checking). This is really intended for
1017 * use only in the main running loop of the client (the_game()) where the faster
1018 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1019 * (e.g. formspecs) should continue using getKeySetting().
1027 populate_nonchanging();
1032 // Keys that are not settings dependent
1033 void populate_nonchanging();
1035 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1036 InputHandler *handler;
1039 void KeyCache::populate_nonchanging()
1041 key[KeyType::ESC] = EscapeKey;
1044 void KeyCache::populate()
1046 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1047 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1048 key[KeyType::LEFT] = getKeySetting("keymap_left");
1049 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1050 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1051 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1052 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1054 key[KeyType::AUTOFORWARD] = getKeySetting("keymap_autoforward");
1056 key[KeyType::DROP] = getKeySetting("keymap_drop");
1057 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1058 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1059 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1060 key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
1061 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1062 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1063 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1064 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1065 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1066 key[KeyType::HOTBAR_PREV] = getKeySetting("keymap_hotbar_previous");
1067 key[KeyType::HOTBAR_NEXT] = getKeySetting("keymap_hotbar_next");
1068 key[KeyType::MUTE] = getKeySetting("keymap_mute");
1069 key[KeyType::INC_VOLUME] = getKeySetting("keymap_increase_volume");
1070 key[KeyType::DEC_VOLUME] = getKeySetting("keymap_decrease_volume");
1071 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1072 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1073 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1074 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1075 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1076 = getKeySetting("keymap_toggle_force_fog_off");
1077 key[KeyType::TOGGLE_UPDATE_CAMERA]
1078 = getKeySetting("keymap_toggle_update_camera");
1079 key[KeyType::TOGGLE_DEBUG]
1080 = getKeySetting("keymap_toggle_debug");
1081 key[KeyType::TOGGLE_PROFILER]
1082 = getKeySetting("keymap_toggle_profiler");
1083 key[KeyType::CAMERA_MODE]
1084 = getKeySetting("keymap_camera_mode");
1085 key[KeyType::INCREASE_VIEWING_RANGE]
1086 = getKeySetting("keymap_increase_viewing_range_min");
1087 key[KeyType::DECREASE_VIEWING_RANGE]
1088 = getKeySetting("keymap_decrease_viewing_range_min");
1089 key[KeyType::RANGESELECT]
1090 = getKeySetting("keymap_rangeselect");
1091 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1093 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1094 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1095 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1096 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1098 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1100 for (int i = 0; i < 23; i++) {
1101 std::string slot_key_name = "keymap_slot" + std::to_string(i + 1);
1102 key[KeyType::SLOT_1 + i] = getKeySetting(slot_key_name.c_str());
1106 // First clear all keys, then re-add the ones we listen for
1107 handler->dontListenForKeys();
1108 for (const KeyPress &k : key) {
1109 handler->listenForKey(k);
1111 handler->listenForKey(EscapeKey);
1112 handler->listenForKey(CancelKey);
1117 /****************************************************************************
1119 ****************************************************************************/
1121 const float object_hit_delay = 0.2;
1124 u32 last_time, busy_time, sleep_time;
1128 /* The reason the following structs are not anonymous structs within the
1129 * class is that they are not used by the majority of member functions and
1130 * many functions that do require objects of thse types do not modify them
1131 * (so they can be passed as a const qualified parameter)
1133 struct CameraOrientation {
1134 f32 camera_yaw; // "right/left"
1135 f32 camera_pitch; // "up/down"
1138 struct GameRunData {
1141 PointedThing pointed_old;
1145 bool digging_blocked;
1147 bool update_wielded_item_trigger;
1148 bool reset_jump_timer;
1149 float nodig_delay_timer;
1151 float dig_time_complete;
1152 float repeat_rightclick_timer;
1153 float object_hit_delay_timer;
1154 float time_from_last_punch;
1155 ClientActiveObject *selected_object;
1159 float update_draw_list_timer;
1160 float statustext_time;
1164 v3f update_draw_list_last_cam_dir;
1166 u32 profiler_current_page;
1167 u32 profiler_max_page; // Number of pages
1170 float time_of_day_smooth;
1174 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1180 Jitter dtime_jitter, busy_time_jitter;
1183 /****************************************************************************
1185 ****************************************************************************/
1187 /* This is not intended to be a public class. If a public class becomes
1188 * desirable then it may be better to create another 'wrapper' class that
1189 * hides most of the stuff in this class (nothing in this class is required
1190 * by any other file) but exposes the public methods/data only.
1197 bool startup(bool *kill,
1199 InputHandler *input,
1200 const std::string &map_dir,
1201 const std::string &playername,
1202 const std::string &password,
1203 // If address is "", local server is used and address is updated
1204 std::string *address,
1206 std::string &error_message,
1208 ChatBackend *chat_backend,
1209 const SubgameSpec &gamespec, // Used for local game
1210 bool simple_singleplayer_mode);
1217 void extendedResourceCleanup();
1219 // Basic initialisation
1220 bool init(const std::string &map_dir, std::string *address,
1222 const SubgameSpec &gamespec);
1224 bool createSingleplayerServer(const std::string &map_dir,
1225 const SubgameSpec &gamespec, u16 port, std::string *address);
1228 bool createClient(const std::string &playername,
1229 const std::string &password, std::string *address, u16 port);
1232 // Client connection
1233 bool connectToServer(const std::string &playername,
1234 const std::string &password, std::string *address, u16 port,
1235 bool *connect_ok, bool *aborted);
1236 bool getServerContent(bool *aborted);
1240 void updateInteractTimers(f32 dtime);
1241 bool checkConnection();
1242 bool handleCallbacks();
1243 void processQueues();
1244 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1245 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1246 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1249 void processUserInput(f32 dtime);
1250 void processKeyInput();
1251 void processItemSelection(u16 *new_playeritem);
1253 void dropSelectedItem();
1254 void openInventory();
1255 void openConsole(float scale, const wchar_t *line=NULL);
1256 void toggleFreeMove();
1257 void toggleFreeMoveAlt();
1259 void toggleNoClip();
1260 void toggleCinematic();
1261 void toggleAutoforward();
1265 void toggleMinimap(bool shift_pressed);
1268 void toggleUpdateCamera();
1269 void toggleProfiler();
1271 void increaseViewRange();
1272 void decreaseViewRange();
1273 void toggleFullViewRange();
1275 void updateCameraDirection(CameraOrientation *cam, float dtime);
1276 void updateCameraOrientation(CameraOrientation *cam, float dtime);
1277 void updatePlayerControl(const CameraOrientation &cam);
1278 void step(f32 *dtime);
1279 void processClientEvents(CameraOrientation *cam);
1280 void updateCamera(u32 busy_time, f32 dtime);
1281 void updateSound(f32 dtime);
1282 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
1284 * Returns the object or node the player is pointing at.
1285 * Also updates the selected thing in the Hud.
1287 * @param[in] shootline the shootline, starting from
1288 * the camera position. This also gives the maximal distance
1290 * @param[in] liquids_pointable if false, liquids are ignored
1291 * @param[in] look_for_object if false, objects are ignored
1292 * @param[in] camera_offset offset of the camera
1293 * @param[out] selected_object the selected object or
1296 PointedThing updatePointedThing(
1297 const core::line3d<f32> &shootline, bool liquids_pointable,
1298 bool look_for_object, const v3s16 &camera_offset);
1299 void handlePointingAtNothing(const ItemStack &playerItem);
1300 void handlePointingAtNode(const PointedThing &pointed,
1301 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
1302 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1303 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
1304 const v3f &player_position, bool show_debug);
1305 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
1306 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1307 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
1308 const CameraOrientation &cam);
1309 void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
1310 void updateProfilerGraphs(ProfilerGraph *graph);
1313 void limitFps(FpsControl *fps_timings, f32 *dtime);
1315 void showOverlayMessage(const char *msg, float dtime, int percent,
1316 bool draw_clouds = true);
1318 static void settingChangedCallback(const std::string &setting_name, void *data);
1319 void readSettings();
1321 inline bool getLeftClicked()
1323 return input->getLeftClicked() ||
1324 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1326 inline bool getRightClicked()
1328 return input->getRightClicked() ||
1329 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1331 inline bool isLeftPressed()
1333 return input->getLeftState() ||
1334 input->joystick.isKeyDown(KeyType::MOUSE_L);
1336 inline bool isRightPressed()
1338 return input->getRightState() ||
1339 input->joystick.isKeyDown(KeyType::MOUSE_R);
1341 inline bool getLeftReleased()
1343 return input->getLeftReleased() ||
1344 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1347 inline bool isKeyDown(GameKeyType k)
1349 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1351 inline bool wasKeyDown(GameKeyType k)
1353 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1357 void handleAndroidChatInput();
1361 void showPauseMenu();
1363 InputHandler *input;
1368 IWritableTextureSource *texture_src;
1369 IWritableShaderSource *shader_src;
1371 // When created, these will be filled with data received from the server
1372 IWritableItemDefManager *itemdef_manager;
1373 IWritableNodeDefManager *nodedef_manager;
1375 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1376 ISoundManager *sound;
1377 bool sound_is_dummy = false;
1378 SoundMaker *soundmaker;
1380 ChatBackend *chat_backend;
1382 GUIFormSpecMenu *current_formspec;
1383 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1384 std::string cur_formname;
1386 EventManager *eventmgr;
1387 QuicktuneShortcutter *quicktune;
1389 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1390 MapDrawControl *draw_control;
1392 Clouds *clouds; // Free using ->Drop()
1393 Sky *sky; // Free using ->Drop()
1394 Inventory *local_inventory;
1398 GameRunData runData;
1402 This class does take ownership/responsibily for cleaning up etc of any of
1403 these items (e.g. device)
1405 IrrlichtDevice *device;
1406 video::IVideoDriver *driver;
1407 scene::ISceneManager *smgr;
1409 std::string *error_message;
1410 bool *reconnect_requested;
1411 scene::ISceneNode *skybox;
1414 bool simple_singleplayer_mode;
1417 /* Pre-calculated values
1419 int crack_animation_length;
1423 gui::IGUIStaticText *guitext; // First line of debug text
1424 gui::IGUIStaticText *guitext2; // Second line of debug text
1425 gui::IGUIStaticText *guitext3; // Third line of debug text
1426 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1427 gui::IGUIStaticText *guitext_status;
1428 gui::IGUIStaticText *guitext_chat; // Chat text
1429 gui::IGUIStaticText *guitext_profiler; // Profiler text
1431 std::wstring infotext;
1432 std::wstring m_statustext;
1436 IntervalLimiter profiler_interval;
1439 * TODO: Local caching of settings is not optimal and should at some stage
1440 * be updated to use a global settings object for getting thse values
1441 * (as opposed to the this local caching). This can be addressed in
1444 bool m_cache_doubletap_jump;
1445 bool m_cache_enable_clouds;
1446 bool m_cache_enable_joysticks;
1447 bool m_cache_enable_particles;
1448 bool m_cache_enable_fog;
1449 bool m_cache_enable_noclip;
1450 bool m_cache_enable_free_move;
1451 f32 m_cache_mouse_sensitivity;
1452 f32 m_cache_joystick_frustum_sensitivity;
1453 f32 m_repeat_right_click_time;
1454 f32 m_cache_cam_smoothing;
1455 f32 m_cache_fog_start;
1457 bool m_invert_mouse = false;
1458 bool m_first_loop_after_window_activation = false;
1459 bool m_camera_offset_changed = false;
1462 bool m_cache_hold_aux1;
1463 bool m_android_chat_open;
1472 itemdef_manager(NULL),
1473 nodedef_manager(NULL),
1477 current_formspec(NULL),
1481 gui_chat_console(NULL),
1486 local_inventory(NULL),
1490 g_settings->registerChangedCallback("doubletap_jump",
1491 &settingChangedCallback, this);
1492 g_settings->registerChangedCallback("enable_clouds",
1493 &settingChangedCallback, this);
1494 g_settings->registerChangedCallback("doubletap_joysticks",
1495 &settingChangedCallback, this);
1496 g_settings->registerChangedCallback("enable_particles",
1497 &settingChangedCallback, this);
1498 g_settings->registerChangedCallback("enable_fog",
1499 &settingChangedCallback, this);
1500 g_settings->registerChangedCallback("mouse_sensitivity",
1501 &settingChangedCallback, this);
1502 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1503 &settingChangedCallback, this);
1504 g_settings->registerChangedCallback("repeat_rightclick_time",
1505 &settingChangedCallback, this);
1506 g_settings->registerChangedCallback("noclip",
1507 &settingChangedCallback, this);
1508 g_settings->registerChangedCallback("free_move",
1509 &settingChangedCallback, this);
1510 g_settings->registerChangedCallback("cinematic",
1511 &settingChangedCallback, this);
1512 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1513 &settingChangedCallback, this);
1514 g_settings->registerChangedCallback("camera_smoothing",
1515 &settingChangedCallback, this);
1520 m_cache_hold_aux1 = false; // This is initialised properly later
1527 /****************************************************************************
1529 ****************************************************************************/
1535 if (!sound_is_dummy)
1538 delete server; // deleted first to stop all server threads
1541 delete local_inventory;
1547 delete nodedef_manager;
1548 delete itemdef_manager;
1549 delete draw_control;
1551 extendedResourceCleanup();
1553 g_settings->deregisterChangedCallback("doubletap_jump",
1554 &settingChangedCallback, this);
1555 g_settings->deregisterChangedCallback("enable_clouds",
1556 &settingChangedCallback, this);
1557 g_settings->deregisterChangedCallback("enable_particles",
1558 &settingChangedCallback, this);
1559 g_settings->deregisterChangedCallback("enable_fog",
1560 &settingChangedCallback, this);
1561 g_settings->deregisterChangedCallback("mouse_sensitivity",
1562 &settingChangedCallback, this);
1563 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1564 &settingChangedCallback, this);
1565 g_settings->deregisterChangedCallback("noclip",
1566 &settingChangedCallback, this);
1567 g_settings->deregisterChangedCallback("free_move",
1568 &settingChangedCallback, this);
1569 g_settings->deregisterChangedCallback("cinematic",
1570 &settingChangedCallback, this);
1571 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1572 &settingChangedCallback, this);
1573 g_settings->deregisterChangedCallback("camera_smoothing",
1574 &settingChangedCallback, this);
1577 bool Game::startup(bool *kill,
1579 InputHandler *input,
1580 const std::string &map_dir,
1581 const std::string &playername,
1582 const std::string &password,
1583 std::string *address, // can change if simple_singleplayer_mode
1585 std::string &error_message,
1587 ChatBackend *chat_backend,
1588 const SubgameSpec &gamespec,
1589 bool simple_singleplayer_mode)
1592 this->device = RenderingEngine::get_raw_device();
1594 this->error_message = &error_message;
1595 this->reconnect_requested = reconnect;
1596 this->random_input = random_input;
1597 this->input = input;
1598 this->chat_backend = chat_backend;
1599 this->simple_singleplayer_mode = simple_singleplayer_mode;
1601 keycache.handler = input;
1602 keycache.populate();
1604 driver = device->getVideoDriver();
1605 smgr = RenderingEngine::get_scene_manager();
1607 RenderingEngine::get_scene_manager()->getParameters()->
1608 setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1610 memset(&runData, 0, sizeof(runData));
1611 runData.time_from_last_punch = 10.0;
1612 runData.profiler_max_page = 3;
1613 runData.update_wielded_item_trigger = true;
1615 memset(&flags, 0, sizeof(flags));
1616 flags.show_chat = true;
1617 flags.show_hud = true;
1618 flags.show_debug = g_settings->getBool("show_debug");
1619 m_invert_mouse = g_settings->getBool("invert_mouse");
1620 m_first_loop_after_window_activation = true;
1622 if (!init(map_dir, address, port, gamespec))
1625 if (!createClient(playername, password, address, port))
1634 ProfilerGraph graph;
1635 RunStats stats = { 0 };
1636 CameraOrientation cam_view_target = { 0 };
1637 CameraOrientation cam_view = { 0 };
1638 FpsControl draw_times = { 0 };
1639 f32 dtime; // in seconds
1641 /* Clear the profiler */
1642 Profiler::GraphValues dummyvalues;
1643 g_profiler->graphGet(dummyvalues);
1645 draw_times.last_time = RenderingEngine::get_timer_time();
1647 set_light_table(g_settings->getFloat("display_gamma"));
1650 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1651 && client->checkPrivilege("fast");
1654 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1655 g_settings->getU16("screen_h"));
1657 while (RenderingEngine::run()
1658 && !(*kill || g_gamecallback->shutdown_requested
1659 || (server && server->getShutdownRequested()))) {
1661 const irr::core::dimension2d<u32> ¤t_screen_size =
1662 RenderingEngine::get_video_driver()->getScreenSize();
1663 // Verify if window size has changed and save it if it's the case
1664 // Ensure evaluating settings->getBool after verifying screensize
1665 // First condition is cheaper
1666 if (previous_screen_size != current_screen_size &&
1667 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1668 g_settings->getBool("autosave_screensize")) {
1669 g_settings->setU16("screen_w", current_screen_size.Width);
1670 g_settings->setU16("screen_h", current_screen_size.Height);
1671 previous_screen_size = current_screen_size;
1674 /* Must be called immediately after a device->run() call because it
1675 * uses device->getTimer()->getTime()
1677 limitFps(&draw_times, &dtime);
1679 updateStats(&stats, draw_times, dtime);
1680 updateInteractTimers(dtime);
1682 if (!checkConnection())
1684 if (!handleCallbacks())
1690 hud->resizeHotbar();
1692 updateProfilers(stats, draw_times, dtime);
1693 processUserInput(dtime);
1694 // Update camera before player movement to avoid camera lag of one frame
1695 updateCameraDirection(&cam_view_target, dtime);
1696 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1697 cam_view.camera_yaw) * m_cache_cam_smoothing;
1698 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1699 cam_view.camera_pitch) * m_cache_cam_smoothing;
1700 updatePlayerControl(cam_view);
1702 processClientEvents(&cam_view_target);
1703 updateCamera(draw_times.busy_time, dtime);
1705 processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
1706 updateFrame(&graph, &stats, dtime, cam_view);
1707 updateProfilerGraphs(&graph);
1709 // Update if minimap has been disabled by the server
1710 flags.show_minimap &= client->shouldShowMinimap();
1715 void Game::shutdown()
1717 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1718 if (g_settings->get("3d_mode") == "pageflip") {
1719 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1722 if (current_formspec)
1723 current_formspec->quitMenu();
1725 showOverlayMessage("Shutting down...", 0, 0, false);
1730 if (gui_chat_console)
1731 gui_chat_console->drop();
1737 while (g_menumgr.menuCount() > 0) {
1738 g_menumgr.m_stack.front()->setVisible(false);
1739 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1742 if (current_formspec) {
1743 current_formspec->drop();
1744 current_formspec = NULL;
1747 chat_backend->addMessage(L"", L"# Disconnected.");
1748 chat_backend->addMessage(L"", L"");
1752 while (!client->isShutdown()) {
1753 assert(texture_src != NULL);
1754 assert(shader_src != NULL);
1755 texture_src->processQueue();
1756 shader_src->processQueue();
1763 /****************************************************************************/
1764 /****************************************************************************
1766 ****************************************************************************/
1767 /****************************************************************************/
1770 const std::string &map_dir,
1771 std::string *address,
1773 const SubgameSpec &gamespec)
1775 texture_src = createTextureSource();
1777 showOverlayMessage("Loading...", 0, 0);
1779 shader_src = createShaderSource();
1781 itemdef_manager = createItemDefManager();
1782 nodedef_manager = createNodeDefManager();
1784 eventmgr = new EventManager();
1785 quicktune = new QuicktuneShortcutter();
1787 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1788 && eventmgr && quicktune))
1794 // Create a server if not connecting to an existing one
1795 if (address->empty()) {
1796 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1803 bool Game::initSound()
1806 if (g_settings->getBool("enable_sound")) {
1807 infostream << "Attempting to use OpenAL audio" << std::endl;
1808 sound = createOpenALSoundManager(&soundfetcher);
1810 infostream << "Failed to initialize OpenAL audio" << std::endl;
1812 infostream << "Sound disabled." << std::endl;
1816 infostream << "Using dummy audio." << std::endl;
1817 sound = &dummySoundManager;
1818 sound_is_dummy = true;
1821 soundmaker = new SoundMaker(sound, nodedef_manager);
1825 soundmaker->registerReceiver(eventmgr);
1830 bool Game::createSingleplayerServer(const std::string &map_dir,
1831 const SubgameSpec &gamespec, u16 port, std::string *address)
1833 showOverlayMessage("Creating server...", 0, 5);
1835 std::string bind_str = g_settings->get("bind_address");
1836 Address bind_addr(0, 0, 0, 0, port);
1838 if (g_settings->getBool("ipv6_server")) {
1839 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1843 bind_addr.Resolve(bind_str.c_str());
1844 } catch (ResolveError &e) {
1845 infostream << "Resolving bind address \"" << bind_str
1846 << "\" failed: " << e.what()
1847 << " -- Listening on all addresses." << std::endl;
1850 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1851 *error_message = "Unable to listen on " +
1852 bind_addr.serializeString() +
1853 " because IPv6 is disabled";
1854 errorstream << *error_message << std::endl;
1858 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1859 bind_addr.isIPv6(), false);
1861 server->start(bind_addr);
1866 bool Game::createClient(const std::string &playername,
1867 const std::string &password, std::string *address, u16 port)
1869 showOverlayMessage("Creating client...", 0, 10);
1871 draw_control = new MapDrawControl;
1875 bool could_connect, connect_aborted;
1877 if (!connectToServer(playername, password, address, port,
1878 &could_connect, &connect_aborted))
1881 if (!could_connect) {
1882 if (error_message->empty() && !connect_aborted) {
1883 // Should not happen if error messages are set properly
1884 *error_message = "Connection failed for unknown reason";
1885 errorstream << *error_message << std::endl;
1890 if (!getServerContent(&connect_aborted)) {
1891 if (error_message->empty() && !connect_aborted) {
1892 // Should not happen if error messages are set properly
1893 *error_message = "Connection failed for unknown reason";
1894 errorstream << *error_message << std::endl;
1899 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1900 &flags.force_fog_off, &runData.fog_range, client);
1901 shader_src->addShaderConstantSetterFactory(scsf);
1903 // Update cached textures, meshes and materials
1904 client->afterContentReceived();
1908 camera = new Camera(*draw_control, client);
1909 if (!camera || !camera->successfullyCreated(*error_message))
1911 client->setCamera(camera);
1915 if (m_cache_enable_clouds) {
1916 clouds = new Clouds(smgr, -1, time(0));
1918 *error_message = "Memory allocation error (clouds)";
1919 errorstream << *error_message << std::endl;
1926 sky = new Sky(-1, texture_src);
1928 skybox = NULL; // This is used/set later on in the main run loop
1930 local_inventory = new Inventory(itemdef_manager);
1932 if (!(sky && local_inventory)) {
1933 *error_message = "Memory allocation error (sky or local inventory)";
1934 errorstream << *error_message << std::endl;
1938 /* Pre-calculated values
1940 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1942 v2u32 size = t->getOriginalSize();
1943 crack_animation_length = size.Y / size.X;
1945 crack_animation_length = 5;
1951 /* Set window caption
1953 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1955 str += utf8_to_wide(g_version_hash);
1957 str += driver->getName();
1959 device->setWindowCaption(str.c_str());
1961 LocalPlayer *player = client->getEnv().getLocalPlayer();
1962 player->hurt_tilt_timer = 0;
1963 player->hurt_tilt_strength = 0;
1965 hud = new Hud(guienv, client, player, local_inventory);
1968 *error_message = "Memory error: could not create HUD";
1969 errorstream << *error_message << std::endl;
1973 mapper = client->getMinimap();
1975 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1980 bool Game::initGui()
1982 // First line of debug text
1983 guitext = addStaticText(guienv,
1984 utf8_to_wide(PROJECT_NAME_C).c_str(),
1985 core::rect<s32>(0, 0, 0, 0),
1986 false, false, guiroot);
1988 // Second line of debug text
1989 guitext2 = addStaticText(guienv,
1991 core::rect<s32>(0, 0, 0, 0),
1992 false, false, guiroot);
1994 // Third line of debug text
1995 guitext3 = addStaticText(guienv,
1997 core::rect<s32>(0, 0, 0, 0),
1998 false, false, guiroot);
2000 // At the middle of the screen
2001 // Object infos are shown in this
2002 guitext_info = addStaticText(guienv,
2004 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2005 false, true, guiroot);
2007 // Status text (displays info when showing and hiding GUI stuff, etc.)
2008 guitext_status = addStaticText(guienv,
2010 core::rect<s32>(0, 0, 0, 0),
2011 false, false, guiroot);
2012 guitext_status->setVisible(false);
2015 guitext_chat = addStaticText(
2018 core::rect<s32>(0, 0, 0, 0),
2019 //false, false); // Disable word wrap as of now
2020 false, true, guiroot);
2022 // Remove stale "recent" chat messages from previous connections
2023 chat_backend->clearRecentChat();
2025 // Chat backend and console
2026 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2027 -1, chat_backend, client, &g_menumgr);
2028 if (!gui_chat_console) {
2029 *error_message = "Could not allocate memory for chat console";
2030 errorstream << *error_message << std::endl;
2034 // Profiler text (size is updated when text is updated)
2035 guitext_profiler = addStaticText(guienv,
2037 core::rect<s32>(0, 0, 0, 0),
2038 false, false, guiroot);
2039 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2040 guitext_profiler->setVisible(false);
2041 guitext_profiler->setWordWrap(true);
2043 #ifdef HAVE_TOUCHSCREENGUI
2045 if (g_touchscreengui)
2046 g_touchscreengui->init(texture_src);
2053 bool Game::connectToServer(const std::string &playername,
2054 const std::string &password, std::string *address, u16 port,
2055 bool *connect_ok, bool *aborted)
2057 *connect_ok = false; // Let's not be overly optimistic
2059 bool local_server_mode = false;
2061 showOverlayMessage("Resolving address...", 0, 15);
2063 Address connect_address(0, 0, 0, 0, port);
2066 connect_address.Resolve(address->c_str());
2068 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2069 //connect_address.Resolve("localhost");
2070 if (connect_address.isIPv6()) {
2071 IPv6AddressBytes addr_bytes;
2072 addr_bytes.bytes[15] = 1;
2073 connect_address.setAddress(&addr_bytes);
2075 connect_address.setAddress(127, 0, 0, 1);
2077 local_server_mode = true;
2079 } catch (ResolveError &e) {
2080 *error_message = std::string("Couldn't resolve address: ") + e.what();
2081 errorstream << *error_message << std::endl;
2085 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2086 *error_message = "Unable to connect to " +
2087 connect_address.serializeString() +
2088 " because IPv6 is disabled";
2089 errorstream << *error_message << std::endl;
2093 client = new Client(playername.c_str(), password, *address,
2094 *draw_control, texture_src, shader_src,
2095 itemdef_manager, nodedef_manager, sound, eventmgr,
2096 connect_address.isIPv6(), &flags);
2101 infostream << "Connecting to server at ";
2102 connect_address.print(&infostream);
2103 infostream << std::endl;
2105 client->connect(connect_address,
2106 simple_singleplayer_mode || local_server_mode);
2109 Wait for server to accept connection
2115 FpsControl fps_control = { 0 };
2117 f32 wait_time = 0; // in seconds
2119 fps_control.last_time = RenderingEngine::get_timer_time();
2124 while (RenderingEngine::run()) {
2126 limitFps(&fps_control, &dtime);
2128 // Update client and server
2129 client->step(dtime);
2132 server->step(dtime);
2135 if (client->getState() == LC_Init) {
2141 if (client->accessDenied()) {
2142 *error_message = "Access denied. Reason: "
2143 + client->accessDeniedReason();
2144 *reconnect_requested = client->reconnectRequested();
2145 errorstream << *error_message << std::endl;
2149 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2151 infostream << "Connect aborted [Escape]" << std::endl;
2156 // Only time out if we aren't waiting for the server we started
2157 if ((!address->empty()) && (wait_time > 10)) {
2158 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2159 // If no pre v25 init was sent, and no answer was received,
2160 // but the low level connection could be established
2161 // (meaning that we have a peer id), then we probably wanted
2162 // to connect to a legacy server. In this case, tell the user
2163 // to enable the option to be able to connect.
2164 if (!sent_old_init &&
2165 (client->getProtoVersion() == 0) &&
2166 client->connectedToServer()) {
2167 *error_message = "Connection failure: init packet not "
2168 "recognized by server.\n"
2169 "Most likely the server uses an old protocol version (<v25).\n"
2170 "Please ask the server owner to update to 0.4.13 or later.\n"
2171 "To still connect to the server in the meantime,\n"
2172 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2173 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2174 "entry in the advanced settings menu.";
2176 *error_message = "Connection timed out.";
2178 errorstream << *error_message << std::endl;
2183 showOverlayMessage("Connecting to server...", dtime, 20);
2185 } catch (con::PeerNotFoundException &e) {
2186 // TODO: Should something be done here? At least an info/error
2194 bool Game::getServerContent(bool *aborted)
2198 FpsControl fps_control = { 0 };
2199 f32 dtime; // in seconds
2201 fps_control.last_time = RenderingEngine::get_timer_time();
2203 while (RenderingEngine::run()) {
2205 limitFps(&fps_control, &dtime);
2207 // Update client and server
2208 client->step(dtime);
2211 server->step(dtime);
2214 if (client->mediaReceived() && client->itemdefReceived() &&
2215 client->nodedefReceived()) {
2220 if (!checkConnection())
2223 if (client->getState() < LC_Init) {
2224 *error_message = "Client disconnected";
2225 errorstream << *error_message << std::endl;
2229 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2231 infostream << "Connect aborted [Escape]" << std::endl;
2238 if (!client->itemdefReceived()) {
2239 const wchar_t *text = wgettext("Item definitions...");
2241 RenderingEngine::draw_load_screen(text, guienv, texture_src,
2244 } else if (!client->nodedefReceived()) {
2245 const wchar_t *text = wgettext("Node definitions...");
2247 RenderingEngine::draw_load_screen(text, guienv, texture_src,
2251 std::stringstream message;
2252 std::fixed(message);
2253 message.precision(0);
2254 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2255 message.precision(2);
2257 if ((USE_CURL == 0) ||
2258 (!g_settings->getBool("enable_remote_media_server"))) {
2259 float cur = client->getCurRate();
2260 std::string cur_unit = gettext("KiB/s");
2264 cur_unit = gettext("MiB/s");
2267 message << " (" << cur << ' ' << cur_unit << ")";
2270 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2271 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
2272 texture_src, dtime, progress);
2280 /****************************************************************************/
2281 /****************************************************************************
2283 ****************************************************************************/
2284 /****************************************************************************/
2286 inline void Game::updateInteractTimers(f32 dtime)
2288 if (runData.nodig_delay_timer >= 0)
2289 runData.nodig_delay_timer -= dtime;
2291 if (runData.object_hit_delay_timer >= 0)
2292 runData.object_hit_delay_timer -= dtime;
2294 runData.time_from_last_punch += dtime;
2298 /* returns false if game should exit, otherwise true
2300 inline bool Game::checkConnection()
2302 if (client->accessDenied()) {
2303 *error_message = "Access denied. Reason: "
2304 + client->accessDeniedReason();
2305 *reconnect_requested = client->reconnectRequested();
2306 errorstream << *error_message << std::endl;
2314 /* returns false if game should exit, otherwise true
2316 inline bool Game::handleCallbacks()
2318 if (g_gamecallback->disconnect_requested) {
2319 g_gamecallback->disconnect_requested = false;
2323 if (g_gamecallback->changepassword_requested) {
2324 (new GUIPasswordChange(guienv, guiroot, -1,
2325 &g_menumgr, client))->drop();
2326 g_gamecallback->changepassword_requested = false;
2329 if (g_gamecallback->changevolume_requested) {
2330 (new GUIVolumeChange(guienv, guiroot, -1,
2331 &g_menumgr))->drop();
2332 g_gamecallback->changevolume_requested = false;
2335 if (g_gamecallback->keyconfig_requested) {
2336 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2337 &g_menumgr))->drop();
2338 g_gamecallback->keyconfig_requested = false;
2341 if (g_gamecallback->keyconfig_changed) {
2342 keycache.populate(); // update the cache with new settings
2343 g_gamecallback->keyconfig_changed = false;
2350 void Game::processQueues()
2352 texture_src->processQueue();
2353 itemdef_manager->processQueue(client);
2354 shader_src->processQueue();
2358 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2360 float profiler_print_interval =
2361 g_settings->getFloat("profiler_print_interval");
2362 bool print_to_log = true;
2364 if (profiler_print_interval == 0) {
2365 print_to_log = false;
2366 profiler_print_interval = 5;
2369 if (profiler_interval.step(dtime, profiler_print_interval)) {
2371 infostream << "Profiler:" << std::endl;
2372 g_profiler->print(infostream);
2375 update_profiler_gui(guitext_profiler, g_fontengine,
2376 runData.profiler_current_page, runData.profiler_max_page,
2377 driver->getScreenSize().Height);
2379 g_profiler->clear();
2382 addProfilerGraphs(stats, draw_times, dtime);
2386 void Game::addProfilerGraphs(const RunStats &stats,
2387 const FpsControl &draw_times, f32 dtime)
2389 g_profiler->graphAdd("mainloop_other",
2390 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2392 if (draw_times.sleep_time != 0)
2393 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2394 g_profiler->graphAdd("mainloop_dtime", dtime);
2396 g_profiler->add("Elapsed time", dtime);
2397 g_profiler->avg("FPS", 1. / dtime);
2401 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2408 /* Time average and jitter calculation
2410 jp = &stats->dtime_jitter;
2411 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2413 jitter = dtime - jp->avg;
2415 if (jitter > jp->max)
2418 jp->counter += dtime;
2420 if (jp->counter > 0.0) {
2422 jp->max_sample = jp->max;
2423 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2427 /* Busytime average and jitter calculation
2429 jp = &stats->busy_time_jitter;
2430 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2432 jitter = draw_times.busy_time - jp->avg;
2434 if (jitter > jp->max)
2436 if (jitter < jp->min)
2439 jp->counter += dtime;
2441 if (jp->counter > 0.0) {
2443 jp->max_sample = jp->max;
2444 jp->min_sample = jp->min;
2452 /****************************************************************************
2454 ****************************************************************************/
2456 void Game::processUserInput(f32 dtime)
2458 // Reset input if window not active or some menu is active
2459 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
2461 #ifdef HAVE_TOUCHSCREENGUI
2462 g_touchscreengui->hide();
2465 #ifdef HAVE_TOUCHSCREENGUI
2466 else if (g_touchscreengui) {
2467 /* on touchscreengui step may generate own input events which ain't
2468 * what we want in case we just did clear them */
2469 g_touchscreengui->step(dtime);
2473 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2474 gui_chat_console->closeConsoleAtOnce();
2477 // Input handler step() (used by the random input generator)
2481 if (current_formspec != NULL)
2482 current_formspec->getAndroidUIInput();
2484 handleAndroidChatInput();
2487 // Increase timer for double tap of "keymap_jump"
2488 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2489 runData.jump_timer += dtime;
2492 processItemSelection(&runData.new_playeritem);
2496 void Game::processKeyInput()
2498 if (wasKeyDown(KeyType::DROP)) {
2500 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
2501 toggleAutoforward();
2502 } else if (wasKeyDown(KeyType::INVENTORY)) {
2504 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2505 if (!gui_chat_console->isOpenInhibited()) {
2508 } else if (wasKeyDown(KeyType::CHAT)) {
2509 openConsole(0.2, L"");
2510 } else if (wasKeyDown(KeyType::CMD)) {
2511 openConsole(0.2, L"/");
2512 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2513 openConsole(0.2, L".");
2514 } else if (wasKeyDown(KeyType::CONSOLE)) {
2515 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2516 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2518 } else if (wasKeyDown(KeyType::JUMP)) {
2519 toggleFreeMoveAlt();
2520 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2522 } else if (wasKeyDown(KeyType::NOCLIP)) {
2524 } else if (wasKeyDown(KeyType::MUTE)) {
2525 float volume = g_settings->getFloat("sound_volume");
2526 if (volume < 0.001f) {
2527 g_settings->setFloat("sound_volume", 1.0f);
2528 m_statustext = narrow_to_wide(gettext("Volume changed to 100%"));
2530 g_settings->setFloat("sound_volume", 0.0f);
2531 m_statustext = narrow_to_wide(gettext("Volume changed to 0%"));
2533 runData.statustext_time = 0;
2534 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
2535 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
2537 g_settings->setFloat("sound_volume", new_volume);
2538 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2539 m_statustext = narrow_to_wide(buf);
2540 runData.statustext_time = 0;
2541 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
2542 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
2544 g_settings->setFloat("sound_volume", new_volume);
2545 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2546 m_statustext = narrow_to_wide(buf);
2547 runData.statustext_time = 0;
2548 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2550 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2551 client->makeScreenshot();
2552 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2554 } else if (wasKeyDown(KeyType::MINIMAP)) {
2555 toggleMinimap(isKeyDown(KeyType::SNEAK));
2556 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2558 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2560 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2561 toggleUpdateCamera();
2562 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2564 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2566 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2567 increaseViewRange();
2568 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2569 decreaseViewRange();
2570 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2571 toggleFullViewRange();
2572 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2574 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2576 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2578 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2580 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2581 // Print debug stacks
2582 dstream << "-----------------------------------------"
2584 dstream << "Printing debug stacks:" << std::endl;
2585 dstream << "-----------------------------------------"
2587 debug_stacks_print();
2590 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2591 runData.reset_jump_timer = false;
2592 runData.jump_timer = 0.0f;
2595 if (quicktune->hasMessage()) {
2596 m_statustext = utf8_to_wide(quicktune->getMessage());
2597 runData.statustext_time = 0.0f;
2601 void Game::processItemSelection(u16 *new_playeritem)
2603 LocalPlayer *player = client->getEnv().getLocalPlayer();
2605 /* Item selection using mouse wheel
2607 *new_playeritem = client->getPlayerItem();
2609 s32 wheel = input->getMouseWheel();
2610 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2611 player->hud_hotbar_itemcount - 1);
2615 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2616 wasKeyDown(KeyType::HOTBAR_NEXT)) {
2620 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2621 wasKeyDown(KeyType::HOTBAR_PREV)) {
2626 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2628 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2631 /* Item selection using hotbar slot keys
2633 for (u16 i = 0; i < 23; i++) {
2634 if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
2635 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2636 *new_playeritem = i;
2637 infostream << "Selected item: " << new_playeritem << std::endl;
2645 void Game::dropSelectedItem()
2647 IDropAction *a = new IDropAction();
2649 a->from_inv.setCurrentPlayer();
2650 a->from_list = "main";
2651 a->from_i = client->getPlayerItem();
2652 client->inventoryAction(a);
2656 void Game::openInventory()
2659 * Don't permit to open inventory is CAO or player doesn't exists.
2660 * This prevent showing an empty inventory at player load
2663 LocalPlayer *player = client->getEnv().getLocalPlayer();
2664 if (!player || !player->getCAO())
2667 infostream << "the_game: " << "Launching inventory" << std::endl;
2669 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2670 TextDest *txt_dst = new TextDestPlayerInventory(client);
2672 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
2675 InventoryLocation inventoryloc;
2676 inventoryloc.setCurrentPlayer();
2677 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2681 void Game::openConsole(float scale, const wchar_t *line)
2683 assert(scale > 0.0f && scale <= 1.0f);
2686 porting::showInputDialog(gettext("ok"), "", "", 2);
2687 m_android_chat_open = true;
2689 if (gui_chat_console->isOpenInhibited())
2691 gui_chat_console->openConsole(scale);
2693 gui_chat_console->setCloseOnEnter(true);
2694 gui_chat_console->replaceAndAddToHistory(line);
2700 void Game::handleAndroidChatInput()
2702 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2703 std::string text = porting::getInputDialogValue();
2704 client->typeChatMessage(utf8_to_wide(text));
2710 void Game::toggleFreeMove()
2712 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2714 bool free_move = !g_settings->getBool("free_move");
2715 g_settings->set("free_move", bool_to_cstr(free_move));
2717 runData.statustext_time = 0;
2718 m_statustext = msg[free_move];
2719 if (free_move && !client->checkPrivilege("fly"))
2720 m_statustext += L" (note: no 'fly' privilege)";
2724 void Game::toggleFreeMoveAlt()
2726 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2729 runData.reset_jump_timer = true;
2733 void Game::toggleFast()
2735 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2736 bool fast_move = !g_settings->getBool("fast_move");
2737 g_settings->set("fast_move", bool_to_cstr(fast_move));
2739 runData.statustext_time = 0;
2740 m_statustext = msg[fast_move];
2742 bool has_fast_privs = client->checkPrivilege("fast");
2744 if (fast_move && !has_fast_privs)
2745 m_statustext += L" (note: no 'fast' privilege)";
2748 m_cache_hold_aux1 = fast_move && has_fast_privs;
2753 void Game::toggleNoClip()
2755 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2756 bool noclip = !g_settings->getBool("noclip");
2757 g_settings->set("noclip", bool_to_cstr(noclip));
2759 runData.statustext_time = 0;
2760 m_statustext = msg[noclip];
2762 if (noclip && !client->checkPrivilege("noclip"))
2763 m_statustext += L" (note: no 'noclip' privilege)";
2766 void Game::toggleCinematic()
2768 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2769 bool cinematic = !g_settings->getBool("cinematic");
2770 g_settings->set("cinematic", bool_to_cstr(cinematic));
2772 runData.statustext_time = 0;
2773 m_statustext = msg[cinematic];
2776 // Autoforward by toggling continuous forward.
2777 void Game::toggleAutoforward()
2779 static const wchar_t *msg[] = { L"autoforward disabled", L"autoforward enabled" };
2780 bool autoforward_enabled = !g_settings->getBool("continuous_forward");
2781 g_settings->set("continuous_forward", bool_to_cstr(autoforward_enabled));
2783 runData.statustext_time = 0;
2784 m_statustext = msg[autoforward_enabled ? 1 : 0];
2787 void Game::toggleChat()
2789 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2791 flags.show_chat = !flags.show_chat;
2792 runData.statustext_time = 0;
2793 m_statustext = msg[flags.show_chat];
2797 void Game::toggleHud()
2799 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2801 flags.show_hud = !flags.show_hud;
2802 runData.statustext_time = 0;
2803 m_statustext = msg[flags.show_hud];
2806 void Game::toggleMinimap(bool shift_pressed)
2808 if (!mapper || !flags.show_hud || !g_settings->getBool("enable_minimap"))
2811 if (shift_pressed) {
2812 mapper->toggleMinimapShape();
2816 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2818 MinimapMode mode = MINIMAP_MODE_OFF;
2819 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2820 mode = mapper->getMinimapMode();
2821 mode = (MinimapMode)((int)mode + 1);
2822 // If radar is disabled and in, or switching to, radar mode
2823 if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE) && mode > 3)
2824 mode = MINIMAP_MODE_OFF;
2827 flags.show_minimap = true;
2829 case MINIMAP_MODE_SURFACEx1:
2830 m_statustext = L"Minimap in surface mode, Zoom x1";
2832 case MINIMAP_MODE_SURFACEx2:
2833 m_statustext = L"Minimap in surface mode, Zoom x2";
2835 case MINIMAP_MODE_SURFACEx4:
2836 m_statustext = L"Minimap in surface mode, Zoom x4";
2838 case MINIMAP_MODE_RADARx1:
2839 m_statustext = L"Minimap in radar mode, Zoom x1";
2841 case MINIMAP_MODE_RADARx2:
2842 m_statustext = L"Minimap in radar mode, Zoom x2";
2844 case MINIMAP_MODE_RADARx4:
2845 m_statustext = L"Minimap in radar mode, Zoom x4";
2848 mode = MINIMAP_MODE_OFF;
2849 flags.show_minimap = false;
2850 m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2851 L"Minimap hidden" : L"Minimap disabled by server";
2854 runData.statustext_time = 0;
2855 mapper->setMinimapMode(mode);
2858 void Game::toggleFog()
2860 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2862 flags.force_fog_off = !flags.force_fog_off;
2863 runData.statustext_time = 0;
2864 m_statustext = msg[flags.force_fog_off];
2868 void Game::toggleDebug()
2870 // Initial / 4x toggle: Chat only
2871 // 1x toggle: Debug text with chat
2872 // 2x toggle: Debug text with profiler graph
2873 // 3x toggle: Debug text and wireframe
2874 if (!flags.show_debug) {
2875 flags.show_debug = true;
2876 flags.show_profiler_graph = false;
2877 draw_control->show_wireframe = false;
2878 m_statustext = L"Debug info shown";
2879 } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2880 flags.show_profiler_graph = true;
2881 m_statustext = L"Profiler graph shown";
2882 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2883 flags.show_profiler_graph = false;
2884 draw_control->show_wireframe = true;
2885 m_statustext = L"Wireframe shown";
2887 flags.show_debug = false;
2888 flags.show_profiler_graph = false;
2889 draw_control->show_wireframe = false;
2890 if (client->checkPrivilege("debug")) {
2891 m_statustext = L"Debug info, profiler graph, and wireframe hidden";
2893 m_statustext = L"Debug info and profiler graph hidden";
2896 runData.statustext_time = 0;
2900 void Game::toggleUpdateCamera()
2902 static const wchar_t *msg[] = {
2903 L"Camera update enabled",
2904 L"Camera update disabled"
2907 flags.disable_camera_update = !flags.disable_camera_update;
2908 runData.statustext_time = 0;
2909 m_statustext = msg[flags.disable_camera_update];
2913 void Game::toggleProfiler()
2915 runData.profiler_current_page =
2916 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2918 // FIXME: This updates the profiler with incomplete values
2919 update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2920 runData.profiler_max_page, driver->getScreenSize().Height);
2922 if (runData.profiler_current_page != 0) {
2923 std::wstringstream sstr;
2924 sstr << "Profiler shown (page " << runData.profiler_current_page
2925 << " of " << runData.profiler_max_page << ")";
2926 m_statustext = sstr.str();
2928 m_statustext = L"Profiler hidden";
2930 runData.statustext_time = 0;
2934 void Game::increaseViewRange()
2936 s16 range = g_settings->getS16("viewing_range");
2937 s16 range_new = range + 10;
2939 if (range_new > 4000) {
2941 m_statustext = utf8_to_wide("Viewing range is at maximum: "
2944 m_statustext = utf8_to_wide("Viewing range changed to "
2947 g_settings->set("viewing_range", itos(range_new));
2948 runData.statustext_time = 0;
2952 void Game::decreaseViewRange()
2954 s16 range = g_settings->getS16("viewing_range");
2955 s16 range_new = range - 10;
2957 if (range_new < 20) {
2959 m_statustext = utf8_to_wide("Viewing range is at minimum: "
2962 m_statustext = utf8_to_wide("Viewing range changed to "
2965 g_settings->set("viewing_range", itos(range_new));
2966 runData.statustext_time = 0;
2970 void Game::toggleFullViewRange()
2972 static const wchar_t *msg[] = {
2973 L"Normal view range",
2974 L"Infinite view range"
2977 draw_control->range_all = !draw_control->range_all;
2978 infostream << msg[draw_control->range_all] << std::endl;
2979 m_statustext = msg[draw_control->range_all];
2980 runData.statustext_time = 0;
2984 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2986 if ((device->isWindowActive() && device->isWindowFocused()
2987 && !isMenuActive()) || random_input) {
2990 if (!random_input) {
2991 // Mac OSX gets upset if this is set every frame
2992 if (device->getCursorControl()->isVisible())
2993 device->getCursorControl()->setVisible(false);
2997 if (m_first_loop_after_window_activation)
2998 m_first_loop_after_window_activation = false;
3000 updateCameraOrientation(cam, dtime);
3002 input->setMousePos((driver->getScreenSize().Width / 2),
3003 (driver->getScreenSize().Height / 2));
3007 // Mac OSX gets upset if this is set every frame
3008 if (!device->getCursorControl()->isVisible())
3009 device->getCursorControl()->setVisible(true);
3012 m_first_loop_after_window_activation = true;
3017 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
3019 #ifdef HAVE_TOUCHSCREENGUI
3020 if (g_touchscreengui) {
3021 cam->camera_yaw += g_touchscreengui->getYawChange();
3022 cam->camera_pitch = g_touchscreengui->getPitch();
3026 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3027 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3029 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3033 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3034 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3036 #ifdef HAVE_TOUCHSCREENGUI
3040 if (m_cache_enable_joysticks) {
3041 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3042 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
3043 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
3046 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3050 void Game::updatePlayerControl(const CameraOrientation &cam)
3052 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3054 // DO NOT use the isKeyDown method for the forward, backward, left, right
3055 // buttons, as the code that uses the controls needs to be able to
3056 // distinguish between the two in order to know when to use joysticks.
3058 PlayerControl control(
3059 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3060 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3061 input->isKeyDown(keycache.key[KeyType::LEFT]),
3062 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3063 isKeyDown(KeyType::JUMP),
3064 isKeyDown(KeyType::SPECIAL1),
3065 isKeyDown(KeyType::SNEAK),
3066 isKeyDown(KeyType::ZOOM),
3071 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3072 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3076 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3077 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3078 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3079 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3080 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3081 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3082 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3083 ( (u32)(isLeftPressed() & 0x1) << 7) |
3084 ( (u32)(isRightPressed() & 0x1) << 8
3088 /* For Android, simulate holding down AUX1 (fast move) if the user has
3089 * the fast_move setting toggled on. If there is an aux1 key defined for
3090 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3093 if (m_cache_hold_aux1) {
3094 control.aux1 = control.aux1 ^ true;
3095 keypress_bits ^= ((u32)(1U << 5));
3099 client->setPlayerControl(control);
3100 LocalPlayer *player = client->getEnv().getLocalPlayer();
3101 player->keyPressed = keypress_bits;
3107 inline void Game::step(f32 *dtime)
3109 bool can_be_and_is_paused =
3110 (simple_singleplayer_mode && g_menumgr.pausesGame());
3112 if (can_be_and_is_paused) { // This is for a singleplayer server
3113 *dtime = 0; // No time passes
3115 if (server != NULL) {
3116 //TimeTaker timer("server->step(dtime)");
3117 server->step(*dtime);
3120 //TimeTaker timer("client.step(dtime)");
3121 client->step(*dtime);
3126 void Game::processClientEvents(CameraOrientation *cam)
3128 LocalPlayer *player = client->getEnv().getLocalPlayer();
3130 while (client->hasClientEvents()) {
3131 ClientEvent event = client->getClientEvent();
3133 switch (event.type) {
3134 case CE_PLAYER_DAMAGE:
3135 if (client->getHP() == 0)
3137 if (client->moddingEnabled()) {
3138 client->getScript()->on_damage_taken(event.player_damage.amount);
3141 runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3142 runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3144 player->hurt_tilt_timer = 1.5;
3145 player->hurt_tilt_strength =
3146 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3148 client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3151 case CE_PLAYER_FORCE_MOVE:
3152 cam->camera_yaw = event.player_force_move.yaw;
3153 cam->camera_pitch = event.player_force_move.pitch;
3156 case CE_DEATHSCREEN:
3157 // This should be enabled for death formspec in builtin
3158 client->getScript()->on_death();
3160 /* Handle visualization */
3161 runData.damage_flash = 0;
3162 player->hurt_tilt_timer = 0;
3163 player->hurt_tilt_strength = 0;
3166 case CE_SHOW_FORMSPEC:
3167 if (event.show_formspec.formspec->empty()) {
3168 if (current_formspec && (event.show_formspec.formname->empty()
3169 || *(event.show_formspec.formname) == cur_formname)) {
3170 current_formspec->quitMenu();
3173 FormspecFormSource *fs_src =
3174 new FormspecFormSource(*(event.show_formspec.formspec));
3175 TextDestPlayerInventory *txt_dst =
3176 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3178 create_formspec_menu(¤t_formspec, client, &input->joystick,
3180 cur_formname = *(event.show_formspec.formname);
3183 delete event.show_formspec.formspec;
3184 delete event.show_formspec.formname;
3187 case CE_SHOW_LOCAL_FORMSPEC:
3189 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3190 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3191 create_formspec_menu(¤t_formspec, client, &input->joystick,
3194 delete event.show_formspec.formspec;
3195 delete event.show_formspec.formname;
3198 case CE_SPAWN_PARTICLE:
3199 case CE_ADD_PARTICLESPAWNER:
3200 case CE_DELETE_PARTICLESPAWNER:
3201 client->getParticleManager()->handleParticleEvent(&event, client, player);
3206 u32 id = event.hudadd.id;
3208 HudElement *e = player->getHud(id);
3211 delete event.hudadd.pos;
3212 delete event.hudadd.name;
3213 delete event.hudadd.scale;
3214 delete event.hudadd.text;
3215 delete event.hudadd.align;
3216 delete event.hudadd.offset;
3217 delete event.hudadd.world_pos;
3218 delete event.hudadd.size;
3223 e->type = (HudElementType)event.hudadd.type;
3224 e->pos = *event.hudadd.pos;
3225 e->name = *event.hudadd.name;
3226 e->scale = *event.hudadd.scale;
3227 e->text = *event.hudadd.text;
3228 e->number = event.hudadd.number;
3229 e->item = event.hudadd.item;
3230 e->dir = event.hudadd.dir;
3231 e->align = *event.hudadd.align;
3232 e->offset = *event.hudadd.offset;
3233 e->world_pos = *event.hudadd.world_pos;
3234 e->size = *event.hudadd.size;
3236 u32 new_id = player->addHud(e);
3237 //if this isn't true our huds aren't consistent
3238 sanity_check(new_id == id);
3241 delete event.hudadd.pos;
3242 delete event.hudadd.name;
3243 delete event.hudadd.scale;
3244 delete event.hudadd.text;
3245 delete event.hudadd.align;
3246 delete event.hudadd.offset;
3247 delete event.hudadd.world_pos;
3248 delete event.hudadd.size;
3253 HudElement *e = player->removeHud(event.hudrm.id);
3261 u32 id = event.hudchange.id;
3262 HudElement *e = player->getHud(id);
3265 delete event.hudchange.v3fdata;
3266 delete event.hudchange.v2fdata;
3267 delete event.hudchange.sdata;
3268 delete event.hudchange.v2s32data;
3272 switch (event.hudchange.stat) {
3274 e->pos = *event.hudchange.v2fdata;
3278 e->name = *event.hudchange.sdata;
3281 case HUD_STAT_SCALE:
3282 e->scale = *event.hudchange.v2fdata;
3286 e->text = *event.hudchange.sdata;
3289 case HUD_STAT_NUMBER:
3290 e->number = event.hudchange.data;
3294 e->item = event.hudchange.data;
3298 e->dir = event.hudchange.data;
3301 case HUD_STAT_ALIGN:
3302 e->align = *event.hudchange.v2fdata;
3305 case HUD_STAT_OFFSET:
3306 e->offset = *event.hudchange.v2fdata;
3309 case HUD_STAT_WORLD_POS:
3310 e->world_pos = *event.hudchange.v3fdata;
3314 e->size = *event.hudchange.v2s32data;
3319 delete event.hudchange.v3fdata;
3320 delete event.hudchange.v2fdata;
3321 delete event.hudchange.sdata;
3322 delete event.hudchange.v2s32data;
3326 sky->setVisible(false);
3327 // Whether clouds are visible in front of a custom skybox
3328 sky->setCloudsEnabled(event.set_sky.clouds);
3335 // Handle according to type
3336 if (*event.set_sky.type == "regular") {
3337 sky->setVisible(true);
3338 sky->setCloudsEnabled(true);
3339 } else if (*event.set_sky.type == "skybox" &&
3340 event.set_sky.params->size() == 6) {
3341 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3342 skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
3343 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3344 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3345 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3346 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3347 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3348 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3350 // Handle everything else as plain color
3352 if (*event.set_sky.type != "plain")
3353 infostream << "Unknown sky type: "
3354 << (*event.set_sky.type) << std::endl;
3356 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3359 delete event.set_sky.bgcolor;
3360 delete event.set_sky.type;
3361 delete event.set_sky.params;
3364 case CE_OVERRIDE_DAY_NIGHT_RATIO:
3365 client->getEnv().setDayNightRatioOverride(
3366 event.override_day_night_ratio.do_override,
3367 event.override_day_night_ratio.ratio_f * 1000);
3370 case CE_CLOUD_PARAMS:
3372 clouds->setDensity(event.cloud_params.density);
3373 clouds->setColorBright(video::SColor(event.cloud_params.color_bright));
3374 clouds->setColorAmbient(video::SColor(event.cloud_params.color_ambient));
3375 clouds->setHeight(event.cloud_params.height);
3376 clouds->setThickness(event.cloud_params.thickness);
3377 clouds->setSpeed(v2f(
3378 event.cloud_params.speed_x,
3379 event.cloud_params.speed_y));
3384 // unknown or unhandled type
3392 void Game::updateCamera(u32 busy_time, f32 dtime)
3394 LocalPlayer *player = client->getEnv().getLocalPlayer();
3397 For interaction purposes, get info about the held item
3399 - Is it a usable item?
3400 - Can it point to liquids?
3402 ItemStack playeritem;
3404 InventoryList *mlist = local_inventory->getList("main");
3406 if (mlist && client->getPlayerItem() < mlist->getSize())
3407 playeritem = mlist->getItem(client->getPlayerItem());
3410 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3411 InventoryList *hlist = local_inventory->getList("hand");
3413 playeritem = hlist->getItem(0);
3417 ToolCapabilities playeritem_toolcap =
3418 playeritem.getToolCapabilities(itemdef_manager);
3420 v3s16 old_camera_offset = camera->getOffset();
3422 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3423 GenericCAO *playercao = player->getCAO();
3425 // If playercao not loaded, don't change camera
3429 camera->toggleCameraMode();
3431 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3432 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3435 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3436 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3438 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3439 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio);
3440 camera->step(dtime);
3442 v3f camera_position = camera->getPosition();
3443 v3f camera_direction = camera->getDirection();
3444 f32 camera_fov = camera->getFovMax();
3445 v3s16 camera_offset = camera->getOffset();
3447 m_camera_offset_changed = (camera_offset != old_camera_offset);
3449 if (!flags.disable_camera_update) {
3450 client->getEnv().getClientMap().updateCamera(camera_position,
3451 camera_direction, camera_fov, camera_offset);
3453 if (m_camera_offset_changed) {
3454 client->updateCameraOffset(camera_offset);
3455 client->getEnv().updateCameraOffset(camera_offset);
3458 clouds->updateCameraOffset(camera_offset);
3464 void Game::updateSound(f32 dtime)
3466 // Update sound listener
3467 v3s16 camera_offset = camera->getOffset();
3468 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3469 v3f(0, 0, 0), // velocity
3470 camera->getDirection(),
3471 camera->getCameraNode()->getUpVector());
3473 // Check if volume is in the proper range, else fix it.
3474 float old_volume = g_settings->getFloat("sound_volume");
3475 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
3476 sound->setListenerGain(new_volume);
3478 if (old_volume != new_volume) {
3479 g_settings->setFloat("sound_volume", new_volume);
3482 LocalPlayer *player = client->getEnv().getLocalPlayer();
3484 // Tell the sound maker whether to make footstep sounds
3485 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3487 // Update sound maker
3488 if (player->makes_footstep_sound)
3489 soundmaker->step(dtime);
3491 ClientMap &map = client->getEnv().getClientMap();
3492 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3493 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3497 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3499 LocalPlayer *player = client->getEnv().getLocalPlayer();
3501 ItemStack playeritem;
3503 InventoryList *mlist = local_inventory->getList("main");
3505 if (mlist && client->getPlayerItem() < mlist->getSize())
3506 playeritem = mlist->getItem(client->getPlayerItem());
3509 const ItemDefinition &playeritem_def =
3510 playeritem.getDefinition(itemdef_manager);
3511 InventoryList *hlist = local_inventory->getList("hand");
3512 const ItemDefinition &hand_def =
3513 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3515 v3f player_position = player->getPosition();
3516 v3f camera_position = camera->getPosition();
3517 v3f camera_direction = camera->getDirection();
3518 v3s16 camera_offset = camera->getOffset();
3522 Calculate what block is the crosshair pointing to
3525 f32 d = playeritem_def.range; // max. distance
3526 f32 d_hand = hand_def.range;
3528 if (d < 0 && d_hand >= 0)
3533 core::line3d<f32> shootline;
3535 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3536 shootline = core::line3d<f32>(camera_position,
3537 camera_position + camera_direction * BS * d);
3539 // prevent player pointing anything in front-view
3540 shootline = core::line3d<f32>(camera_position,camera_position);
3543 #ifdef HAVE_TOUCHSCREENGUI
3545 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3546 shootline = g_touchscreengui->getShootline();
3547 // Scale shootline to the acual distance the player can reach
3548 shootline.end = shootline.start
3549 + shootline.getVector().normalize() * BS * d;
3550 shootline.start += intToFloat(camera_offset, BS);
3551 shootline.end += intToFloat(camera_offset, BS);
3556 PointedThing pointed = updatePointedThing(shootline,
3557 playeritem_def.liquids_pointable,
3558 !runData.ldown_for_dig,
3561 if (pointed != runData.pointed_old) {
3562 infostream << "Pointing at " << pointed.dump() << std::endl;
3563 hud->updateSelectionMesh(camera_offset);
3566 if (runData.digging_blocked && !isLeftPressed()) {
3567 // allow digging again if button is not pressed
3568 runData.digging_blocked = false;
3573 - releasing left mouse button
3574 - pointing away from node
3576 if (runData.digging) {
3577 if (getLeftReleased()) {
3578 infostream << "Left button released"
3579 << " (stopped digging)" << std::endl;
3580 runData.digging = false;
3581 } else if (pointed != runData.pointed_old) {
3582 if (pointed.type == POINTEDTHING_NODE
3583 && runData.pointed_old.type == POINTEDTHING_NODE
3584 && pointed.node_undersurface
3585 == runData.pointed_old.node_undersurface) {
3586 // Still pointing to the same node, but a different face.
3589 infostream << "Pointing away from node"
3590 << " (stopped digging)" << std::endl;
3591 runData.digging = false;
3592 hud->updateSelectionMesh(camera_offset);
3596 if (!runData.digging) {
3597 client->interact(1, runData.pointed_old);
3598 client->setCrack(-1, v3s16(0, 0, 0));
3599 runData.dig_time = 0.0;
3601 } else if (runData.dig_instantly && getLeftReleased()) {
3602 // Remove e.g. torches faster when clicking instead of holding LMB
3603 runData.nodig_delay_timer = 0;
3604 runData.dig_instantly = false;
3607 if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3608 runData.ldown_for_dig = false;
3611 runData.left_punch = false;
3613 soundmaker->m_player_leftpunch_sound.name = "";
3615 // Prepare for repeating, unless we're not supposed to
3616 if (isRightPressed() && !g_settings->getBool("safe_dig_and_place"))
3617 runData.repeat_rightclick_timer += dtime;
3619 runData.repeat_rightclick_timer = 0;
3621 if (playeritem_def.usable && isLeftPressed()) {
3622 if (getLeftClicked() && (!client->moddingEnabled()
3623 || !client->getScript()->on_item_use(playeritem, pointed)))
3624 client->interact(4, pointed);
3625 } else if (pointed.type == POINTEDTHING_NODE) {
3626 ToolCapabilities playeritem_toolcap =
3627 playeritem.getToolCapabilities(itemdef_manager);
3628 if (playeritem.name.empty() && hand_def.tool_capabilities != NULL) {
3629 playeritem_toolcap = *hand_def.tool_capabilities;
3631 handlePointingAtNode(pointed, playeritem_def, playeritem,
3632 playeritem_toolcap, dtime);
3633 } else if (pointed.type == POINTEDTHING_OBJECT) {
3634 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3635 } else if (isLeftPressed()) {
3636 // When button is held down in air, show continuous animation
3637 runData.left_punch = true;
3638 } else if (getRightClicked()) {
3639 handlePointingAtNothing(playeritem);
3642 runData.pointed_old = pointed;
3644 if (runData.left_punch || getLeftClicked())
3645 camera->setDigging(0); // left click animation
3647 input->resetLeftClicked();
3648 input->resetRightClicked();
3650 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3651 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3653 input->resetLeftReleased();
3654 input->resetRightReleased();
3656 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3657 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3661 PointedThing Game::updatePointedThing(
3662 const core::line3d<f32> &shootline,
3663 bool liquids_pointable,
3664 bool look_for_object,
3665 const v3s16 &camera_offset)
3667 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3668 selectionboxes->clear();
3669 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3670 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3671 "show_entity_selectionbox");
3673 ClientEnvironment &env = client->getEnv();
3674 ClientMap &map = env.getClientMap();
3675 INodeDefManager *nodedef = map.getNodeDefManager();
3677 runData.selected_object = NULL;
3679 RaycastState s(shootline, look_for_object, liquids_pointable);
3680 PointedThing result;
3681 env.continueRaycast(&s, &result);
3682 if (result.type == POINTEDTHING_OBJECT) {
3683 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3684 aabb3f selection_box;
3685 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3686 runData.selected_object->getSelectionBox(&selection_box)) {
3687 v3f pos = runData.selected_object->getPosition();
3688 selectionboxes->push_back(aabb3f(selection_box));
3689 hud->setSelectionPos(pos, camera_offset);
3691 } else if (result.type == POINTEDTHING_NODE) {
3692 // Update selection boxes
3693 MapNode n = map.getNodeNoEx(result.node_undersurface);
3694 std::vector<aabb3f> boxes;
3695 n.getSelectionBoxes(nodedef, &boxes,
3696 n.getNeighbors(result.node_undersurface, &map));
3699 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3700 i != boxes.end(); ++i) {
3702 box.MinEdge -= v3f(d, d, d);
3703 box.MaxEdge += v3f(d, d, d);
3704 selectionboxes->push_back(box);
3706 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3708 hud->setSelectedFaceNormal(v3f(
3709 result.intersection_normal.X,
3710 result.intersection_normal.Y,
3711 result.intersection_normal.Z));
3714 // Update selection mesh light level and vertex colors
3715 if (!selectionboxes->empty()) {
3716 v3f pf = hud->getSelectionPos();
3717 v3s16 p = floatToInt(pf, BS);
3719 // Get selection mesh light level
3720 MapNode n = map.getNodeNoEx(p);
3721 u16 node_light = getInteriorLight(n, -1, nodedef);
3722 u16 light_level = node_light;
3724 for (const v3s16 &dir : g_6dirs) {
3725 n = map.getNodeNoEx(p + dir);
3726 node_light = getInteriorLight(n, -1, nodedef);
3727 if (node_light > light_level)
3728 light_level = node_light;
3731 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3733 final_color_blend(&c, light_level, daynight_ratio);
3735 // Modify final color a bit with time
3736 u32 timer = porting::getTimeMs() % 5000;
3737 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3738 float sin_r = 0.08 * sin(timerf);
3739 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3740 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3741 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3742 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3743 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3745 // Set mesh final color
3746 hud->setSelectionMeshColor(c);
3752 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3754 infostream << "Right Clicked in Air" << std::endl;
3755 PointedThing fauxPointed;
3756 fauxPointed.type = POINTEDTHING_NOTHING;
3757 client->interact(5, fauxPointed);
3761 void Game::handlePointingAtNode(const PointedThing &pointed,
3762 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
3763 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3765 v3s16 nodepos = pointed.node_undersurface;
3766 v3s16 neighbourpos = pointed.node_abovesurface;
3769 Check information text of node
3772 ClientMap &map = client->getEnv().getClientMap();
3774 if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3775 && !runData.digging_blocked
3776 && client->checkPrivilege("interact")) {
3777 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3780 // This should be done after digging handling
3781 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3784 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3786 MapNode n = map.getNodeNoEx(nodepos);
3788 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3789 infotext = L"Unknown node: ";
3790 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3794 if ((getRightClicked() ||
3795 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3796 client->checkPrivilege("interact")) {
3797 runData.repeat_rightclick_timer = 0;
3798 infostream << "Ground right-clicked" << std::endl;
3800 if (meta && !meta->getString("formspec").empty() && !random_input
3801 && !isKeyDown(KeyType::SNEAK)) {
3802 // Report right click to server
3803 if (nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3804 client->interact(3, pointed);
3807 infostream << "Launching custom inventory view" << std::endl;
3809 InventoryLocation inventoryloc;
3810 inventoryloc.setNodeMeta(nodepos);
3812 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3813 &client->getEnv().getClientMap(), nodepos);
3814 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3816 create_formspec_menu(¤t_formspec, client,
3817 &input->joystick, fs_src, txt_dst);
3820 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3822 // Report right click to server
3824 camera->setDigging(1); // right click animation (always shown for feedback)
3826 // If the wielded item has node placement prediction,
3828 bool placed = nodePlacementPrediction(*client,
3829 playeritem_def, playeritem,
3830 nodepos, neighbourpos);
3834 client->interact(3, pointed);
3836 soundmaker->m_player_rightpunch_sound =
3837 playeritem_def.sound_place;
3839 if (client->moddingEnabled())
3840 client->getScript()->on_placenode(pointed, playeritem_def);
3842 soundmaker->m_player_rightpunch_sound =
3845 if (playeritem_def.node_placement_prediction.empty() ||
3846 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3847 client->interact(3, pointed); // Report to server
3849 soundmaker->m_player_rightpunch_sound =
3850 playeritem_def.sound_place_failed;
3858 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3859 const v3f &player_position, bool show_debug)
3861 infotext = unescape_enriched(
3862 utf8_to_wide(runData.selected_object->infoText()));
3865 if (!infotext.empty()) {
3868 infotext += unescape_enriched(utf8_to_wide(
3869 runData.selected_object->debugInfoText()));
3872 if (isLeftPressed()) {
3873 bool do_punch = false;
3874 bool do_punch_damage = false;
3876 if (runData.object_hit_delay_timer <= 0.0) {
3878 do_punch_damage = true;
3879 runData.object_hit_delay_timer = object_hit_delay;
3882 if (getLeftClicked())
3886 infostream << "Left-clicked object" << std::endl;
3887 runData.left_punch = true;
3890 if (do_punch_damage) {
3891 // Report direct punch
3892 v3f objpos = runData.selected_object->getPosition();
3893 v3f dir = (objpos - player_position).normalize();
3894 ItemStack item = playeritem;
3895 if (playeritem.name.empty()) {
3896 InventoryList *hlist = local_inventory->getList("hand");
3898 item = hlist->getItem(0);
3902 bool disable_send = runData.selected_object->directReportPunch(
3903 dir, &item, runData.time_from_last_punch);
3904 runData.time_from_last_punch = 0;
3907 client->interact(0, pointed);
3909 } else if (getRightClicked()) {
3910 infostream << "Right-clicked object" << std::endl;
3911 client->interact(3, pointed); // place
3916 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3917 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3919 LocalPlayer *player = client->getEnv().getLocalPlayer();
3920 ClientMap &map = client->getEnv().getClientMap();
3921 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3923 // NOTE: Similar piece of code exists on the server side for
3925 // Get digging parameters
3926 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3927 &playeritem_toolcap);
3929 // If can't dig, try hand
3930 if (!params.diggable) {
3931 InventoryList *hlist = local_inventory->getList("hand");
3932 const ItemDefinition &hand =
3933 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3934 const ToolCapabilities *tp = hand.tool_capabilities;
3937 params = getDigParams(nodedef_manager->get(n).groups, tp);
3940 if (!params.diggable) {
3941 // I guess nobody will wait for this long
3942 runData.dig_time_complete = 10000000.0;
3944 runData.dig_time_complete = params.time;
3946 if (m_cache_enable_particles) {
3947 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3948 client->getParticleManager()->addPunchingParticles(client,
3949 player, nodepos, n, features);
3953 if (!runData.digging) {
3954 infostream << "Started digging" << std::endl;
3955 runData.dig_instantly = runData.dig_time_complete == 0;
3956 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3958 client->interact(0, pointed);
3959 runData.digging = true;
3960 runData.ldown_for_dig = true;
3963 if (!runData.dig_instantly) {
3964 runData.dig_index = (float)crack_animation_length
3966 / runData.dig_time_complete;
3968 // This is for e.g. torches
3969 runData.dig_index = crack_animation_length;
3972 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3974 if (sound_dig.exists() && params.diggable) {
3975 if (sound_dig.name == "__group") {
3976 if (!params.main_group.empty()) {
3977 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3978 soundmaker->m_player_leftpunch_sound.name =
3979 std::string("default_dig_") +
3983 soundmaker->m_player_leftpunch_sound = sound_dig;
3987 // Don't show cracks if not diggable
3988 if (runData.dig_time_complete >= 100000.0) {
3989 } else if (runData.dig_index < crack_animation_length) {
3990 //TimeTaker timer("client.setTempMod");
3991 //infostream<<"dig_index="<<dig_index<<std::endl;
3992 client->setCrack(runData.dig_index, nodepos);
3994 infostream << "Digging completed" << std::endl;
3995 client->setCrack(-1, v3s16(0, 0, 0));
3997 runData.dig_time = 0;
3998 runData.digging = false;
3999 // we successfully dug, now block it from repeating if we want to be safe
4000 if (g_settings->getBool("safe_dig_and_place"))
4001 runData.digging_blocked = true;
4003 runData.nodig_delay_timer =
4004 runData.dig_time_complete / (float)crack_animation_length;
4006 // We don't want a corresponding delay to very time consuming nodes
4007 // and nodes without digging time (e.g. torches) get a fixed delay.
4008 if (runData.nodig_delay_timer > 0.3)
4009 runData.nodig_delay_timer = 0.3;
4010 else if (runData.dig_instantly)
4011 runData.nodig_delay_timer = 0.15;
4013 bool is_valid_position;
4014 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
4015 if (is_valid_position) {
4016 if (client->moddingEnabled() &&
4017 client->getScript()->on_dignode(nodepos, wasnode)) {
4020 client->removeNode(nodepos);
4023 client->interact(2, pointed);
4025 if (m_cache_enable_particles) {
4026 const ContentFeatures &features =
4027 client->getNodeDefManager()->get(wasnode);
4028 client->getParticleManager()->addDiggingParticles(client,
4029 player, nodepos, wasnode, features);
4033 // Send event to trigger sound
4034 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4035 client->event()->put(e);
4038 if (runData.dig_time_complete < 100000.0) {
4039 runData.dig_time += dtime;
4041 runData.dig_time = 0;
4042 client->setCrack(-1, nodepos);
4045 camera->setDigging(0); // left click animation
4049 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
4050 const CameraOrientation &cam)
4052 LocalPlayer *player = client->getEnv().getLocalPlayer();
4058 if (draw_control->range_all) {
4059 runData.fog_range = 100000 * BS;
4061 runData.fog_range = draw_control->wanted_range * BS;
4065 Calculate general brightness
4067 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4068 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4069 float direct_brightness;
4072 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4073 direct_brightness = time_brightness;
4074 sunlight_seen = true;
4076 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4077 float old_brightness = sky->getBrightness();
4078 direct_brightness = client->getEnv().getClientMap()
4079 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
4080 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4084 float time_of_day_smooth = runData.time_of_day_smooth;
4085 float time_of_day = client->getEnv().getTimeOfDayF();
4087 static const float maxsm = 0.05;
4088 static const float todsm = 0.05;
4090 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4091 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4092 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4093 time_of_day_smooth = time_of_day;
4095 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4096 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4097 + (time_of_day + 1.0) * todsm;
4099 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4100 + time_of_day * todsm;
4102 runData.time_of_day = time_of_day;
4103 runData.time_of_day_smooth = time_of_day_smooth;
4105 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4106 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4107 player->getPitch());
4113 if (sky->getCloudsVisible()) {
4114 clouds->setVisible(true);
4115 clouds->step(dtime);
4116 // camera->getPosition is not enough for 3rd person views
4117 v3f camera_node_position = camera->getCameraNode()->getPosition();
4118 v3s16 camera_offset = camera->getOffset();
4119 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
4120 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
4121 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
4122 clouds->update(camera_node_position,
4123 sky->getCloudColor());
4124 if (clouds->isCameraInsideCloud() && m_cache_enable_fog &&
4125 !flags.force_fog_off) {
4126 // if inside clouds, and fog enabled, use that as sky
4128 video::SColor clouds_dark = clouds->getColor()
4129 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
4130 sky->overrideColors(clouds_dark, clouds->getColor());
4131 sky->setBodiesVisible(false);
4132 runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
4133 // do not draw clouds after all
4134 clouds->setVisible(false);
4137 clouds->setVisible(false);
4144 client->getParticleManager()->step(dtime);
4150 if (m_cache_enable_fog && !flags.force_fog_off) {
4153 video::EFT_FOG_LINEAR,
4154 runData.fog_range * m_cache_fog_start,
4155 runData.fog_range * 1.0,
4163 video::EFT_FOG_LINEAR,
4173 Get chat messages from client
4176 v2u32 screensize = driver->getScreenSize();
4178 updateChat(*client, dtime, flags.show_debug, screensize,
4179 flags.show_chat, runData.profiler_current_page,
4180 *chat_backend, guitext_chat);
4186 if (client->getPlayerItem() != runData.new_playeritem)
4187 client->selectPlayerItem(runData.new_playeritem);
4189 // Update local inventory if it has changed
4190 if (client->getLocalInventoryUpdated()) {
4191 //infostream<<"Updating local inventory"<<std::endl;
4192 client->getLocalInventory(*local_inventory);
4193 runData.update_wielded_item_trigger = true;
4196 if (runData.update_wielded_item_trigger) {
4197 // Update wielded tool
4198 InventoryList *mlist = local_inventory->getList("main");
4200 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4201 ItemStack item = mlist->getItem(client->getPlayerItem());
4202 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4203 InventoryList *hlist = local_inventory->getList("hand");
4205 item = hlist->getItem(0);
4207 camera->wield(item);
4210 runData.update_wielded_item_trigger = false;
4214 Update block draw list every 200ms or when camera direction has
4217 runData.update_draw_list_timer += dtime;
4219 v3f camera_direction = camera->getDirection();
4220 if (runData.update_draw_list_timer >= 0.2
4221 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4222 || m_camera_offset_changed) {
4223 runData.update_draw_list_timer = 0;
4224 client->getEnv().getClientMap().updateDrawList();
4225 runData.update_draw_list_last_cam_dir = camera_direction;
4228 updateGui(*stats, dtime, cam);
4231 make sure menu is on top
4232 1. Delete formspec menu reference if menu was removed
4233 2. Else, make sure formspec menu is on top
4235 if (current_formspec) {
4236 if (current_formspec->getReferenceCount() == 1) {
4237 current_formspec->drop();
4238 current_formspec = NULL;
4239 } else if (isMenuActive()) {
4240 guiroot->bringToFront(current_formspec);
4247 const video::SColor &skycolor = sky->getSkyColor();
4249 TimeTaker tt_draw("mainloop: draw");
4250 driver->beginScene(true, true, skycolor);
4252 RenderingEngine::draw_scene(camera, client, player, hud, mapper,
4253 guienv, screensize, skycolor, flags.show_hud,
4254 flags.show_minimap);
4259 if (flags.show_profiler_graph)
4260 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4265 if (runData.damage_flash > 0.0) {
4266 video::SColor color(runData.damage_flash, 180, 0, 0);
4267 driver->draw2DRectangle(color,
4268 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4271 runData.damage_flash -= 100.0 * dtime;
4277 if (player->hurt_tilt_timer > 0.0) {
4278 player->hurt_tilt_timer -= dtime * 5;
4280 if (player->hurt_tilt_timer < 0)
4281 player->hurt_tilt_strength = 0;
4285 Update minimap pos and rotation
4287 if (mapper && flags.show_minimap && flags.show_hud) {
4288 mapper->setPos(floatToInt(player->getPosition(), BS));
4289 mapper->setAngle(player->getYaw());
4297 stats->drawtime = tt_draw.stop(true);
4298 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4302 inline static const char *yawToDirectionString(int yaw)
4304 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4306 yaw = wrapDegrees_0_360(yaw);
4307 yaw = (yaw + 45) % 360 / 90;
4309 return direction[yaw];
4313 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4315 v2u32 screensize = driver->getScreenSize();
4316 LocalPlayer *player = client->getEnv().getLocalPlayer();
4317 v3f player_position = player->getPosition();
4319 if (flags.show_debug) {
4320 static float drawtime_avg = 0;
4321 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4322 u16 fps = 1.0 / stats.dtime_jitter.avg;
4324 std::ostringstream os(std::ios_base::binary);
4326 << PROJECT_NAME_C " " << g_version_hash
4327 << ", FPS = " << fps
4328 << ", range_all = " << draw_control->range_all
4329 << std::setprecision(0)
4330 << ", drawtime = " << drawtime_avg << " ms"
4331 << std::setprecision(1)
4332 << ", dtime_jitter = "
4333 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4334 << std::setprecision(1)
4335 << ", view_range = " << draw_control->wanted_range
4336 << std::setprecision(3)
4337 << ", RTT = " << client->getRTT() << " s";
4338 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4339 guitext->setVisible(true);
4341 guitext->setVisible(false);
4344 if (guitext->isVisible()) {
4345 core::rect<s32> rect(
4347 screensize.X, 5 + g_fontengine->getTextHeight()
4349 guitext->setRelativePosition(rect);
4352 if (flags.show_debug) {
4353 std::ostringstream os(std::ios_base::binary);
4354 os << std::setprecision(1) << std::fixed
4355 << "pos = (" << (player_position.X / BS)
4356 << ", " << (player_position.Y / BS)
4357 << ", " << (player_position.Z / BS)
4358 << "), yaw = " << (wrapDegrees_0_360(cam.camera_yaw)) << "°"
4359 << " " << yawToDirectionString(cam.camera_yaw)
4360 << ", seed = " << ((u64)client->getMapSeed());
4361 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4362 guitext2->setVisible(true);
4364 guitext2->setVisible(false);
4367 if (guitext2->isVisible()) {
4368 core::rect<s32> rect(
4369 5, 5 + g_fontengine->getTextHeight(),
4370 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4372 guitext2->setRelativePosition(rect);
4375 if (flags.show_debug && runData.pointed_old.type == POINTEDTHING_NODE) {
4376 ClientMap &map = client->getEnv().getClientMap();
4377 const INodeDefManager *nodedef = client->getNodeDefManager();
4378 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4380 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4381 std::ostringstream os(std::ios_base::binary);
4382 os << "pointing_at = (" << nodedef->get(n).name
4383 << ", param2 = " << (u64) n.getParam2()
4385 setStaticText(guitext3, utf8_to_wide(os.str()).c_str());
4386 guitext3->setVisible(true);
4388 guitext3->setVisible(false);
4391 guitext3->setVisible(false);
4394 if (guitext3->isVisible()) {
4395 core::rect<s32> rect(
4396 5, 5 + g_fontengine->getTextHeight() * 2,
4397 screensize.X, 5 + g_fontengine->getTextHeight() * 3
4399 guitext3->setRelativePosition(rect);
4402 setStaticText(guitext_info, infotext.c_str());
4403 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4405 float statustext_time_max = 1.5;
4407 if (!m_statustext.empty()) {
4408 runData.statustext_time += dtime;
4410 if (runData.statustext_time >= statustext_time_max) {
4412 runData.statustext_time = 0;
4416 setStaticText(guitext_status, m_statustext.c_str());
4417 guitext_status->setVisible(!m_statustext.empty());
4419 if (!m_statustext.empty()) {
4420 s32 status_width = guitext_status->getTextWidth();
4421 s32 status_height = guitext_status->getTextHeight();
4422 s32 status_y = screensize.Y - 150;
4423 s32 status_x = (screensize.X - status_width) / 2;
4424 core::rect<s32> rect(
4425 status_x , status_y - status_height,
4426 status_x + status_width, status_y
4428 guitext_status->setRelativePosition(rect);
4431 video::SColor initial_color(255, 0, 0, 0);
4433 if (guienv->getSkin())
4434 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4436 video::SColor final_color = initial_color;
4437 final_color.setAlpha(0);
4438 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4439 initial_color, final_color,
4440 pow(runData.statustext_time / statustext_time_max, 2.0f));
4441 guitext_status->setOverrideColor(fade_color);
4442 guitext_status->enableOverrideColor(true);
4447 /* Log times and stuff for visualization */
4448 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4450 Profiler::GraphValues values;
4451 g_profiler->graphGet(values);
4457 /****************************************************************************
4459 ****************************************************************************/
4461 /* On some computers framerate doesn't seem to be automatically limited
4463 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4465 // not using getRealTime is necessary for wine
4466 device->getTimer()->tick(); // Maker sure device time is up-to-date
4467 u32 time = device->getTimer()->getTime();
4468 u32 last_time = fps_timings->last_time;
4470 if (time > last_time) // Make sure time hasn't overflowed
4471 fps_timings->busy_time = time - last_time;
4473 fps_timings->busy_time = 0;
4475 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4476 ? g_settings->getFloat("pause_fps_max")
4477 : g_settings->getFloat("fps_max"));
4479 if (fps_timings->busy_time < frametime_min) {
4480 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4481 device->sleep(fps_timings->sleep_time);
4483 fps_timings->sleep_time = 0;
4486 /* Get the new value of the device timer. Note that device->sleep() may
4487 * not sleep for the entire requested time as sleep may be interrupted and
4488 * therefore it is arguably more accurate to get the new time from the
4489 * device rather than calculating it by adding sleep_time to time.
4492 device->getTimer()->tick(); // Update device timer
4493 time = device->getTimer()->getTime();
4495 if (time > last_time) // Make sure last_time hasn't overflowed
4496 *dtime = (time - last_time) / 1000.0;
4500 fps_timings->last_time = time;
4503 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
4505 const wchar_t *wmsg = wgettext(msg);
4506 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
4511 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4513 ((Game *)data)->readSettings();
4516 void Game::readSettings()
4518 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4519 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4520 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4521 m_cache_enable_particles = g_settings->getBool("enable_particles");
4522 m_cache_enable_fog = g_settings->getBool("enable_fog");
4523 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4524 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4525 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4527 m_cache_enable_noclip = g_settings->getBool("noclip");
4528 m_cache_enable_free_move = g_settings->getBool("free_move");
4530 m_cache_fog_start = g_settings->getFloat("fog_start");
4532 m_cache_cam_smoothing = 0;
4533 if (g_settings->getBool("cinematic"))
4534 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4536 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4538 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4539 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4540 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4544 /****************************************************************************/
4545 /****************************************************************************
4547 ****************************************************************************/
4548 /****************************************************************************/
4550 void Game::extendedResourceCleanup()
4552 // Extended resource accounting
4553 infostream << "Irrlicht resources after cleanup:" << std::endl;
4554 infostream << "\tRemaining meshes : "
4555 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
4556 infostream << "\tRemaining textures : "
4557 << driver->getTextureCount() << std::endl;
4559 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4560 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4561 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4565 clearTextureNameCache();
4566 infostream << "\tRemaining materials: "
4567 << driver-> getMaterialRendererCount()
4568 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4571 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4572 void Game::showPauseMenu()
4575 static const std::string control_text = strgettext("Default Controls:\n"
4576 "No menu visible:\n"
4577 "- single tap: button activate\n"
4578 "- double tap: place/use\n"
4579 "- slide finger: look around\n"
4580 "Menu/Inventory visible:\n"
4581 "- double tap (outside):\n"
4583 "- touch stack, touch slot:\n"
4585 "- touch&drag, tap 2nd finger\n"
4586 " --> place single item to slot\n"
4589 static const std::string control_text_template = strgettext("Controls:\n"
4590 "- %s: move forwards\n"
4591 "- %s: move backwards\n"
4593 "- %s: move right\n"
4594 "- %s: jump/climb\n"
4595 "- %s: sneak/go down\n"
4598 "- Mouse: turn/look\n"
4599 "- Mouse left: dig/punch\n"
4600 "- Mouse right: place/use\n"
4601 "- Mouse wheel: select item\n"
4605 char control_text_buf[600];
4607 snprintf(control_text_buf, ARRLEN(control_text_buf), control_text_template.c_str(),
4608 GET_KEY_NAME(keymap_forward),
4609 GET_KEY_NAME(keymap_backward),
4610 GET_KEY_NAME(keymap_left),
4611 GET_KEY_NAME(keymap_right),
4612 GET_KEY_NAME(keymap_jump),
4613 GET_KEY_NAME(keymap_sneak),
4614 GET_KEY_NAME(keymap_drop),
4615 GET_KEY_NAME(keymap_inventory),
4616 GET_KEY_NAME(keymap_chat)
4619 std::string control_text = std::string(control_text_buf);
4620 str_formspec_escape(control_text);
4623 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4624 std::ostringstream os;
4626 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4627 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4628 << strgettext("Continue") << "]";
4630 if (!simple_singleplayer_mode) {
4631 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4632 << strgettext("Change Password") << "]";
4634 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4638 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4639 << strgettext("Sound Volume") << "]";
4640 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4641 << strgettext("Change Keys") << "]";
4643 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4644 << strgettext("Exit to Menu") << "]";
4645 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4646 << strgettext("Exit to OS") << "]"
4647 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4648 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4650 << strgettext("Game info:") << "\n";
4651 const std::string &address = client->getAddressName();
4652 static const std::string mode = strgettext("- Mode: ");
4653 if (!simple_singleplayer_mode) {
4654 Address serverAddress = client->getServerAddress();
4655 if (!address.empty()) {
4656 os << mode << strgettext("Remote server") << "\n"
4657 << strgettext("- Address: ") << address;
4659 os << mode << strgettext("Hosting server");
4661 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4663 os << mode << strgettext("Singleplayer") << "\n";
4665 if (simple_singleplayer_mode || address.empty()) {
4666 static const std::string on = strgettext("On");
4667 static const std::string off = strgettext("Off");
4668 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4669 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4670 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4671 os << strgettext("- Damage: ") << damage << "\n"
4672 << strgettext("- Creative Mode: ") << creative << "\n";
4673 if (!simple_singleplayer_mode) {
4674 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4675 os << strgettext("- PvP: ") << pvp << "\n"
4676 << strgettext("- Public: ") << announced << "\n";
4677 std::string server_name = g_settings->get("server_name");
4678 str_formspec_escape(server_name);
4679 if (announced == on && !server_name.empty())
4680 os << strgettext("- Server Name: ") << server_name;
4687 /* Note: FormspecFormSource and LocalFormspecHandler *
4688 * are deleted by guiFormSpecMenu */
4689 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4690 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4692 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
4693 current_formspec->setFocus("btn_continue");
4694 current_formspec->doPause = true;
4697 /****************************************************************************/
4698 /****************************************************************************
4699 extern function for launching the game
4700 ****************************************************************************/
4701 /****************************************************************************/
4703 void the_game(bool *kill,
4705 InputHandler *input,
4706 const std::string &map_dir,
4707 const std::string &playername,
4708 const std::string &password,
4709 const std::string &address, // If empty local server is created
4712 std::string &error_message,
4713 ChatBackend &chat_backend,
4714 bool *reconnect_requested,
4715 const SubgameSpec &gamespec, // Used for local game
4716 bool simple_singleplayer_mode)
4720 /* Make a copy of the server address because if a local singleplayer server
4721 * is created then this is updated and we don't want to change the value
4722 * passed to us by the calling function
4724 std::string server_address = address;
4728 if (game.startup(kill, random_input, input, map_dir,
4729 playername, password, &server_address, port, error_message,
4730 reconnect_requested, &chat_backend, gamespec,
4731 simple_singleplayer_mode)) {
4736 } catch (SerializationError &e) {
4737 error_message = std::string("A serialization error occurred:\n")
4738 + e.what() + "\n\nThe server is probably "
4739 " running a different version of " PROJECT_NAME_C ".";
4740 errorstream << error_message << std::endl;
4741 } catch (ServerError &e) {
4742 error_message = e.what();
4743 errorstream << "ServerError: " << error_message << std::endl;
4744 } catch (ModError &e) {
4745 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4746 errorstream << "ModError: " << error_message << std::endl;