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.
23 #include "client/renderingengine.h"
26 #include "client/inputhandler.h"
27 #include "client/tile.h" // For TextureSource
28 #include "client/keys.h"
29 #include "client/joystick_controller.h"
30 #include "clientmap.h"
33 #include "content_cao.h"
34 #include "event_manager.h"
35 #include "fontengine.h"
40 #include "guiChatConsole.h"
41 #include "guiFormSpecMenu.h"
42 #include "guiKeyChangeMenu.h"
43 #include "guiPasswordChange.h"
44 #include "guiVolumeChange.h"
45 #include "mainmenumanager.h"
48 #include "nodedef.h" // Needed for determining pointing to nodes
49 #include "nodemetadata.h"
50 #include "particles.h"
52 #include "quicktune_shortcutter.h"
59 #include "util/basic_macros.h"
60 #include "util/directiontables.h"
61 #include "util/pointedthing.h"
62 #include "irrlicht_changes/static_text.h"
64 #include "script/scripting_client.h"
67 #include "sound_openal.h"
70 extern Settings *g_settings;
71 extern Profiler *g_profiler;
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.c_str());
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;
298 void put(const Profiler::GraphValues &values)
301 piece.values = values;
302 m_log.push_back(piece);
304 while (m_log.size() > m_log_max_size)
305 m_log.erase(m_log.begin());
308 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
309 gui::IGUIFont *font) const
311 // Do *not* use UNORDERED_MAP here as the order needs
312 // to be the same for each call to prevent flickering
313 std::map<std::string, Meta> m_meta;
315 for (std::deque<Piece>::const_iterator k = m_log.begin();
316 k != m_log.end(); ++k) {
317 const Piece &piece = *k;
319 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
320 i != piece.values.end(); ++i) {
321 const std::string &id = i->first;
322 const float &value = i->second;
323 std::map<std::string, Meta>::iterator j = m_meta.find(id);
325 if (j == m_meta.end()) {
326 m_meta[id] = Meta(value);
330 if (value < j->second.min)
331 j->second.min = value;
333 if (value > j->second.max)
334 j->second.max = value;
339 static const video::SColor usable_colors[] = {
340 video::SColor(255, 255, 100, 100),
341 video::SColor(255, 90, 225, 90),
342 video::SColor(255, 100, 100, 255),
343 video::SColor(255, 255, 150, 50),
344 video::SColor(255, 220, 220, 100)
346 static const u32 usable_colors_count =
347 sizeof(usable_colors) / sizeof(*usable_colors);
348 u32 next_color_i = 0;
350 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
351 i != m_meta.end(); ++i) {
352 Meta &meta = i->second;
353 video::SColor color(255, 200, 200, 200);
355 if (next_color_i < usable_colors_count)
356 color = usable_colors[next_color_i++];
362 s32 textx = x_left + m_log_max_size + 15;
363 s32 textx2 = textx + 200 - 15;
366 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
367 i != m_meta.end(); ++i) {
368 const std::string &id = i->first;
369 const Meta &meta = i->second;
371 s32 y = y_bottom - meta_i * 50;
372 float show_min = meta.min;
373 float show_max = meta.max;
375 if (show_min >= -0.0001 && show_max >= -0.0001) {
376 if (show_min <= show_max * 0.5)
382 snprintf(buf, 10, "%.3g", show_max);
383 font->draw(utf8_to_wide(buf).c_str(),
384 core::rect<s32>(textx, y - graphh,
385 textx2, y - graphh + texth),
387 snprintf(buf, 10, "%.3g", show_min);
388 font->draw(utf8_to_wide(buf).c_str(),
389 core::rect<s32>(textx, y - texth,
392 font->draw(utf8_to_wide(id).c_str(),
393 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
394 textx2, y - graphh / 2 + texth / 2),
397 s32 graph1h = graphh;
398 bool relativegraph = (show_min != 0 && show_min != show_max);
399 float lastscaledvalue = 0.0;
400 bool lastscaledvalue_exists = false;
402 for (std::deque<Piece>::const_iterator j = m_log.begin();
403 j != m_log.end(); ++j) {
404 const Piece &piece = *j;
406 bool value_exists = false;
407 Profiler::GraphValues::const_iterator k =
408 piece.values.find(id);
410 if (k != piece.values.end()) {
417 lastscaledvalue_exists = false;
421 float scaledvalue = 1.0;
423 if (show_max != show_min)
424 scaledvalue = (value - show_min) / (show_max - show_min);
426 if (scaledvalue == 1.0 && value == 0) {
428 lastscaledvalue_exists = false;
433 if (lastscaledvalue_exists) {
434 s32 ivalue1 = lastscaledvalue * graph1h;
435 s32 ivalue2 = scaledvalue * graph1h;
436 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
437 v2s32(x, graph1y - ivalue2), meta.color);
440 lastscaledvalue = scaledvalue;
441 lastscaledvalue_exists = true;
443 s32 ivalue = scaledvalue * graph1h;
444 driver->draw2DLine(v2s32(x, graph1y),
445 v2s32(x, graph1y - ivalue), meta.color);
456 class NodeDugEvent: public MtEvent
462 NodeDugEvent(v3s16 p, MapNode n):
466 const char *getType() const
474 ISoundManager *m_sound;
475 INodeDefManager *m_ndef;
477 bool makes_footstep_sound;
478 float m_player_step_timer;
480 SimpleSoundSpec m_player_step_sound;
481 SimpleSoundSpec m_player_leftpunch_sound;
482 SimpleSoundSpec m_player_rightpunch_sound;
484 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
487 makes_footstep_sound(true),
488 m_player_step_timer(0)
492 void playPlayerStep()
494 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
495 m_player_step_timer = 0.03;
496 if (makes_footstep_sound)
497 m_sound->playSound(m_player_step_sound, false);
501 static void viewBobbingStep(MtEvent *e, void *data)
503 SoundMaker *sm = (SoundMaker *)data;
504 sm->playPlayerStep();
507 static void playerRegainGround(MtEvent *e, void *data)
509 SoundMaker *sm = (SoundMaker *)data;
510 sm->playPlayerStep();
513 static void playerJump(MtEvent *e, void *data)
515 //SoundMaker *sm = (SoundMaker*)data;
518 static void cameraPunchLeft(MtEvent *e, void *data)
520 SoundMaker *sm = (SoundMaker *)data;
521 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
524 static void cameraPunchRight(MtEvent *e, void *data)
526 SoundMaker *sm = (SoundMaker *)data;
527 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
530 static void nodeDug(MtEvent *e, void *data)
532 SoundMaker *sm = (SoundMaker *)data;
533 NodeDugEvent *nde = (NodeDugEvent *)e;
534 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
537 static void playerDamage(MtEvent *e, void *data)
539 SoundMaker *sm = (SoundMaker *)data;
540 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
543 static void playerFallingDamage(MtEvent *e, void *data)
545 SoundMaker *sm = (SoundMaker *)data;
546 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
549 void registerReceiver(MtEventManager *mgr)
551 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
552 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
553 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
554 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
555 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
556 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
557 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
558 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
561 void step(float dtime)
563 m_player_step_timer -= dtime;
567 // Locally stored sounds don't need to be preloaded because of this
568 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
570 std::set<std::string> m_fetched;
572 void paths_insert(std::set<std::string> &dst_paths,
573 const std::string &base,
574 const std::string &name)
576 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
577 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
578 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
579 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
580 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
581 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
582 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
583 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
584 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
585 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
586 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
589 void fetchSounds(const std::string &name,
590 std::set<std::string> &dst_paths,
591 std::set<std::string> &dst_datas)
593 if (m_fetched.count(name))
596 m_fetched.insert(name);
598 paths_insert(dst_paths, porting::path_share, name);
599 paths_insert(dst_paths, porting::path_user, name);
604 // before 1.8 there isn't a "integer interface", only float
605 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
606 typedef f32 SamplerLayer_t;
608 typedef s32 SamplerLayer_t;
612 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
615 bool *m_force_fog_off;
618 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
619 CachedPixelShaderSetting<float> m_fog_distance;
620 CachedVertexShaderSetting<float> m_animation_timer_vertex;
621 CachedPixelShaderSetting<float> m_animation_timer_pixel;
622 CachedPixelShaderSetting<float, 3> m_day_light;
623 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
624 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
625 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
626 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
627 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
628 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
632 void onSettingsChange(const std::string &name)
634 if (name == "enable_fog")
635 m_fog_enabled = g_settings->getBool("enable_fog");
638 static void settingsCallback(const std::string &name, void *userdata)
640 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
643 void setSky(Sky *sky) { m_sky = sky; }
645 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
646 f32 *fog_range, Client *client) :
648 m_force_fog_off(force_fog_off),
649 m_fog_range(fog_range),
650 m_sky_bg_color("skyBgColor"),
651 m_fog_distance("fogDistance"),
652 m_animation_timer_vertex("animationTimer"),
653 m_animation_timer_pixel("animationTimer"),
654 m_day_light("dayLight"),
655 m_eye_position_pixel("eyePosition"),
656 m_eye_position_vertex("eyePosition"),
657 m_minimap_yaw("yawVec"),
658 m_base_texture("baseTexture"),
659 m_normal_texture("normalTexture"),
660 m_texture_flags("textureFlags"),
663 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
664 m_fog_enabled = g_settings->getBool("enable_fog");
667 ~GameGlobalShaderConstantSetter()
669 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
672 virtual void onSetConstants(video::IMaterialRendererServices *services,
679 video::SColor bgcolor = m_sky->getBgColor();
680 video::SColorf bgcolorf(bgcolor);
681 float bgcolorfa[4] = {
687 m_sky_bg_color.set(bgcolorfa, services);
690 float fog_distance = 10000 * BS;
692 if (m_fog_enabled && !*m_force_fog_off)
693 fog_distance = *m_fog_range;
695 m_fog_distance.set(&fog_distance, services);
697 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
698 video::SColorf sunlight;
699 get_sunlight_color(&sunlight, daynight_ratio);
704 m_day_light.set(dnc, services);
706 u32 animation_timer = porting::getTimeMs() % 100000;
707 float animation_timer_f = (float)animation_timer / 100000.f;
708 m_animation_timer_vertex.set(&animation_timer_f, services);
709 m_animation_timer_pixel.set(&animation_timer_f, services);
711 float eye_position_array[3];
712 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
713 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
714 eye_position_array[0] = epos.X;
715 eye_position_array[1] = epos.Y;
716 eye_position_array[2] = epos.Z;
718 epos.getAs3Values(eye_position_array);
720 m_eye_position_pixel.set(eye_position_array, services);
721 m_eye_position_vertex.set(eye_position_array, services);
723 if (m_client->getMinimap()) {
724 float minimap_yaw_array[3];
725 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
726 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
727 minimap_yaw_array[0] = minimap_yaw.X;
728 minimap_yaw_array[1] = minimap_yaw.Y;
729 minimap_yaw_array[2] = minimap_yaw.Z;
731 minimap_yaw.getAs3Values(minimap_yaw_array);
733 m_minimap_yaw.set(minimap_yaw_array, services);
736 SamplerLayer_t base_tex = 0,
739 m_base_texture.set(&base_tex, services);
740 m_normal_texture.set(&normal_tex, services);
741 m_texture_flags.set(&flags_tex, services);
746 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
749 bool *m_force_fog_off;
752 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
754 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
755 f32 *fog_range, Client *client) :
757 m_force_fog_off(force_fog_off),
758 m_fog_range(fog_range),
762 void setSky(Sky *sky) {
764 for (size_t i = 0; i < created_nosky.size(); ++i) {
765 created_nosky[i]->setSky(m_sky);
767 created_nosky.clear();
770 virtual IShaderConstantSetter* create()
772 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
773 m_sky, m_force_fog_off, m_fog_range, m_client);
775 created_nosky.push_back(scs);
781 bool nodePlacementPrediction(Client &client, const ItemDefinition &playeritem_def,
782 const ItemStack &playeritem, v3s16 nodepos, v3s16 neighbourpos)
784 std::string prediction = playeritem_def.node_placement_prediction;
785 INodeDefManager *nodedef = client.ndef();
786 ClientMap &map = client.getEnv().getClientMap();
788 bool is_valid_position;
790 node = map.getNodeNoEx(nodepos, &is_valid_position);
791 if (!is_valid_position)
794 if (prediction != "" && !nodedef->get(node).rightclickable) {
795 verbosestream << "Node placement prediction for "
796 << playeritem_def.name << " is "
797 << prediction << std::endl;
798 v3s16 p = neighbourpos;
800 // Place inside node itself if buildable_to
801 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
802 if (is_valid_position)
804 if (nodedef->get(n_under).buildable_to)
807 node = map.getNodeNoEx(p, &is_valid_position);
808 if (is_valid_position &&!nodedef->get(node).buildable_to)
813 // Find id of predicted node
815 bool found = nodedef->getId(prediction, id);
818 errorstream << "Node placement prediction failed for "
819 << playeritem_def.name << " (places "
821 << ") - Name not known" << std::endl;
825 const ContentFeatures &predicted_f = nodedef->get(id);
827 // Predict param2 for facedir and wallmounted nodes
830 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
831 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
832 v3s16 dir = nodepos - neighbourpos;
834 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
835 param2 = dir.Y < 0 ? 1 : 0;
836 } else if (abs(dir.X) > abs(dir.Z)) {
837 param2 = dir.X < 0 ? 3 : 2;
839 param2 = dir.Z < 0 ? 5 : 4;
843 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
844 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
845 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
847 if (abs(dir.X) > abs(dir.Z)) {
848 param2 = dir.X < 0 ? 3 : 1;
850 param2 = dir.Z < 0 ? 2 : 0;
856 //Check attachment if node is in group attached_node
857 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
858 static v3s16 wallmounted_dirs[8] = {
868 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
869 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
870 pp = p + wallmounted_dirs[param2];
872 pp = p + v3s16(0, -1, 0);
874 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
879 if ((predicted_f.param_type_2 == CPT2_COLOR
880 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
881 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
882 const std::string &indexstr = playeritem.metadata.getString(
884 if (!indexstr.empty()) {
885 s32 index = mystoi(indexstr);
886 if (predicted_f.param_type_2 == CPT2_COLOR) {
888 } else if (predicted_f.param_type_2
889 == CPT2_COLORED_WALLMOUNTED) {
890 // param2 = pure palette index + other
891 param2 = (index & 0xf8) | (param2 & 0x07);
892 } else if (predicted_f.param_type_2
893 == CPT2_COLORED_FACEDIR) {
894 // param2 = pure palette index + other
895 param2 = (index & 0xe0) | (param2 & 0x1f);
900 // Add node to client map
901 MapNode n(id, 0, param2);
904 LocalPlayer *player = client.getEnv().getLocalPlayer();
906 // Dont place node when player would be inside new node
907 // NOTE: This is to be eventually implemented by a mod as client-side Lua
908 if (!nodedef->get(n).walkable ||
909 g_settings->getBool("enable_build_where_you_stand") ||
910 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
911 (nodedef->get(n).walkable &&
912 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
913 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
915 // This triggers the required mesh update too
916 client.addNode(p, n);
919 } catch (InvalidPositionException &e) {
920 errorstream << "Node placement prediction failed for "
921 << playeritem_def.name << " (places "
923 << ") - Position not loaded" << std::endl;
930 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
931 Client *client, JoystickController *joystick,
932 IFormSource *fs_src, TextDest *txt_dest)
935 if (*cur_formspec == 0) {
936 *cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
937 client, client->getTextureSource(), fs_src, txt_dest);
938 (*cur_formspec)->doPause = false;
941 Caution: do not call (*cur_formspec)->drop() here --
942 the reference might outlive the menu, so we will
943 periodically check if *cur_formspec is the only
944 remaining reference (i.e. the menu was removed)
945 and delete it in that case.
949 (*cur_formspec)->setFormSource(fs_src);
950 (*cur_formspec)->setTextDest(txt_dest);
956 #define SIZE_TAG "size[11,5.5]"
958 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
961 /******************************************************************************/
962 static void updateChat(Client &client, f32 dtime, bool show_debug,
963 const v2u32 &screensize, bool show_chat, u32 show_profiler,
964 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
966 // Add chat log output for errors to be shown in chat
967 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
969 // Get new messages from error log buffer
970 while (!chat_log_error_buf.empty()) {
971 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
972 if (!g_settings->getBool("disable_escape_sequences")) {
973 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
975 chat_backend.addMessage(L"", error_message);
978 // Get new messages from client
979 std::wstring message;
981 while (client.getChatMessage(message)) {
982 chat_backend.addUnparsedMessage(message);
985 // Remove old messages
986 chat_backend.step(dtime);
988 // Display all messages in a static text element
989 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
990 EnrichedString recent_chat = chat_backend.getRecentChat();
991 unsigned int line_height = g_fontengine->getLineHeight();
993 setStaticText(guitext_chat, recent_chat);
995 // Update gui element size and position
999 chat_y += 2 * line_height;
1001 // first pass to calculate height of text to be set
1002 const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
1003 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
1004 window_size.X - 20);
1005 core::rect<s32> rect(10, chat_y, width, chat_y + window_size.Y);
1006 guitext_chat->setRelativePosition(rect);
1008 //now use real height of text and adjust rect according to this size
1009 rect = core::rect<s32>(10, chat_y, width,
1010 chat_y + guitext_chat->getTextHeight());
1013 guitext_chat->setRelativePosition(rect);
1014 // Don't show chat if disabled or empty or profiler is enabled
1015 guitext_chat->setVisible(
1016 show_chat && recent_chat_count != 0 && !show_profiler);
1020 /****************************************************************************
1021 Fast key cache for main game loop
1022 ****************************************************************************/
1024 /* This is faster than using getKeySetting with the tradeoff that functions
1025 * using it must make sure that it's initialised before using it and there is
1026 * no error handling (for example bounds checking). This is really intended for
1027 * use only in the main running loop of the client (the_game()) where the faster
1028 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1029 * (e.g. formspecs) should continue using getKeySetting().
1037 populate_nonchanging();
1042 // Keys that are not settings dependent
1043 void populate_nonchanging();
1045 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1046 InputHandler *handler;
1049 void KeyCache::populate_nonchanging()
1051 key[KeyType::ESC] = EscapeKey;
1054 void KeyCache::populate()
1056 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1057 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1058 key[KeyType::LEFT] = getKeySetting("keymap_left");
1059 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1060 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1061 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1062 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1064 key[KeyType::AUTOFORWARD] = getKeySetting("keymap_autoforward");
1066 key[KeyType::DROP] = getKeySetting("keymap_drop");
1067 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1068 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1069 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1070 key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
1071 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1072 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1073 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1074 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1075 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1076 key[KeyType::HOTBAR_PREV] = getKeySetting("keymap_hotbar_previous");
1077 key[KeyType::HOTBAR_NEXT] = getKeySetting("keymap_hotbar_next");
1078 key[KeyType::MUTE] = getKeySetting("keymap_mute");
1079 key[KeyType::INC_VOLUME] = getKeySetting("keymap_increase_volume");
1080 key[KeyType::DEC_VOLUME] = getKeySetting("keymap_decrease_volume");
1081 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1082 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1083 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1084 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1085 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1086 = getKeySetting("keymap_toggle_force_fog_off");
1087 key[KeyType::TOGGLE_UPDATE_CAMERA]
1088 = getKeySetting("keymap_toggle_update_camera");
1089 key[KeyType::TOGGLE_DEBUG]
1090 = getKeySetting("keymap_toggle_debug");
1091 key[KeyType::TOGGLE_PROFILER]
1092 = getKeySetting("keymap_toggle_profiler");
1093 key[KeyType::CAMERA_MODE]
1094 = getKeySetting("keymap_camera_mode");
1095 key[KeyType::INCREASE_VIEWING_RANGE]
1096 = getKeySetting("keymap_increase_viewing_range_min");
1097 key[KeyType::DECREASE_VIEWING_RANGE]
1098 = getKeySetting("keymap_decrease_viewing_range_min");
1099 key[KeyType::RANGESELECT]
1100 = getKeySetting("keymap_rangeselect");
1101 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1103 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1104 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1105 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1106 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1108 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1111 // First clear all keys, then re-add the ones we listen for
1112 handler->dontListenForKeys();
1113 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1114 handler->listenForKey(key[i]);
1116 handler->listenForKey(EscapeKey);
1117 handler->listenForKey(CancelKey);
1118 for (size_t i = 0; i < 10; i++) {
1119 handler->listenForKey(NumberKey[i]);
1125 /****************************************************************************
1127 ****************************************************************************/
1129 const float object_hit_delay = 0.2;
1132 u32 last_time, busy_time, sleep_time;
1136 /* The reason the following structs are not anonymous structs within the
1137 * class is that they are not used by the majority of member functions and
1138 * many functions that do require objects of thse types do not modify them
1139 * (so they can be passed as a const qualified parameter)
1141 struct CameraOrientation {
1142 f32 camera_yaw; // "right/left"
1143 f32 camera_pitch; // "up/down"
1146 struct GameRunData {
1149 PointedThing pointed_old;
1154 bool update_wielded_item_trigger;
1155 bool reset_jump_timer;
1156 float nodig_delay_timer;
1158 float dig_time_complete;
1159 float repeat_rightclick_timer;
1160 float object_hit_delay_timer;
1161 float time_from_last_punch;
1162 ClientActiveObject *selected_object;
1166 float update_draw_list_timer;
1167 float statustext_time;
1171 v3f update_draw_list_last_cam_dir;
1173 u32 profiler_current_page;
1174 u32 profiler_max_page; // Number of pages
1177 float time_of_day_smooth;
1181 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1187 Jitter dtime_jitter, busy_time_jitter;
1190 /****************************************************************************
1192 ****************************************************************************/
1194 /* This is not intended to be a public class. If a public class becomes
1195 * desirable then it may be better to create another 'wrapper' class that
1196 * hides most of the stuff in this class (nothing in this class is required
1197 * by any other file) but exposes the public methods/data only.
1204 bool startup(bool *kill,
1206 InputHandler *input,
1207 const std::string &map_dir,
1208 const std::string &playername,
1209 const std::string &password,
1210 // If address is "", local server is used and address is updated
1211 std::string *address,
1213 std::string &error_message,
1215 ChatBackend *chat_backend,
1216 const SubgameSpec &gamespec, // Used for local game
1217 bool simple_singleplayer_mode);
1224 void extendedResourceCleanup();
1226 // Basic initialisation
1227 bool init(const std::string &map_dir, std::string *address,
1229 const SubgameSpec &gamespec);
1231 bool createSingleplayerServer(const std::string &map_dir,
1232 const SubgameSpec &gamespec, u16 port, std::string *address);
1235 bool createClient(const std::string &playername,
1236 const std::string &password, std::string *address, u16 port);
1239 // Client connection
1240 bool connectToServer(const std::string &playername,
1241 const std::string &password, std::string *address, u16 port,
1242 bool *connect_ok, bool *aborted);
1243 bool getServerContent(bool *aborted);
1247 void updateInteractTimers(f32 dtime);
1248 bool checkConnection();
1249 bool handleCallbacks();
1250 void processQueues();
1251 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1252 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1253 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1256 void processUserInput(f32 dtime);
1257 void processKeyInput();
1258 void processItemSelection(u16 *new_playeritem);
1260 void dropSelectedItem();
1261 void openInventory();
1262 void openConsole(float scale, const wchar_t *line=NULL);
1263 void toggleFreeMove();
1264 void toggleFreeMoveAlt();
1266 void toggleNoClip();
1267 void toggleCinematic();
1268 void toggleAutoforward();
1272 void toggleMinimap(bool shift_pressed);
1275 void toggleUpdateCamera();
1276 void toggleProfiler();
1278 void increaseViewRange();
1279 void decreaseViewRange();
1280 void toggleFullViewRange();
1282 void updateCameraDirection(CameraOrientation *cam, float dtime);
1283 void updateCameraOrientation(CameraOrientation *cam, float dtime);
1284 void updatePlayerControl(const CameraOrientation &cam);
1285 void step(f32 *dtime);
1286 void processClientEvents(CameraOrientation *cam);
1287 void updateCamera(u32 busy_time, f32 dtime);
1288 void updateSound(f32 dtime);
1289 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
1291 * Returns the object or node the player is pointing at.
1292 * Also updates the selected thing in the Hud.
1294 * @param[in] shootline the shootline, starting from
1295 * the camera position. This also gives the maximal distance
1297 * @param[in] liquids_pointable if false, liquids are ignored
1298 * @param[in] look_for_object if false, objects are ignored
1299 * @param[in] camera_offset offset of the camera
1300 * @param[out] selected_object the selected object or
1303 PointedThing updatePointedThing(
1304 const core::line3d<f32> &shootline, bool liquids_pointable,
1305 bool look_for_object, const v3s16 &camera_offset);
1306 void handlePointingAtNothing(const ItemStack &playerItem);
1307 void handlePointingAtNode(const PointedThing &pointed,
1308 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
1309 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1310 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
1311 const v3f &player_position, bool show_debug);
1312 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
1313 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1314 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
1315 const CameraOrientation &cam);
1316 void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
1317 void updateProfilerGraphs(ProfilerGraph *graph);
1320 void limitFps(FpsControl *fps_timings, f32 *dtime);
1322 void showOverlayMessage(const char *msg, float dtime, int percent,
1323 bool draw_clouds = true);
1325 static void settingChangedCallback(const std::string &setting_name, void *data);
1326 void readSettings();
1328 inline bool getLeftClicked()
1330 return input->getLeftClicked() ||
1331 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1333 inline bool getRightClicked()
1335 return input->getRightClicked() ||
1336 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1338 inline bool isLeftPressed()
1340 return input->getLeftState() ||
1341 input->joystick.isKeyDown(KeyType::MOUSE_L);
1343 inline bool isRightPressed()
1345 return input->getRightState() ||
1346 input->joystick.isKeyDown(KeyType::MOUSE_R);
1348 inline bool getLeftReleased()
1350 return input->getLeftReleased() ||
1351 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1354 inline bool isKeyDown(GameKeyType k)
1356 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1358 inline bool wasKeyDown(GameKeyType k)
1360 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1364 void handleAndroidChatInput();
1368 void showPauseMenu();
1370 InputHandler *input;
1375 IWritableTextureSource *texture_src;
1376 IWritableShaderSource *shader_src;
1378 // When created, these will be filled with data received from the server
1379 IWritableItemDefManager *itemdef_manager;
1380 IWritableNodeDefManager *nodedef_manager;
1382 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1383 ISoundManager *sound;
1384 bool sound_is_dummy;
1385 SoundMaker *soundmaker;
1387 ChatBackend *chat_backend;
1389 GUIFormSpecMenu *current_formspec;
1390 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1391 std::string cur_formname;
1393 EventManager *eventmgr;
1394 QuicktuneShortcutter *quicktune;
1396 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1397 MapDrawControl *draw_control;
1399 Clouds *clouds; // Free using ->Drop()
1400 Sky *sky; // Free using ->Drop()
1401 Inventory *local_inventory;
1405 GameRunData runData;
1409 This class does take ownership/responsibily for cleaning up etc of any of
1410 these items (e.g. device)
1412 IrrlichtDevice *device;
1413 video::IVideoDriver *driver;
1414 scene::ISceneManager *smgr;
1416 std::string *error_message;
1417 bool *reconnect_requested;
1418 scene::ISceneNode *skybox;
1421 bool simple_singleplayer_mode;
1424 /* Pre-calculated values
1426 int crack_animation_length;
1430 gui::IGUIStaticText *guitext; // First line of debug text
1431 gui::IGUIStaticText *guitext2; // Second line of debug text
1432 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1433 gui::IGUIStaticText *guitext_status;
1434 gui::IGUIStaticText *guitext_chat; // Chat text
1435 gui::IGUIStaticText *guitext_profiler; // Profiler text
1437 std::wstring infotext;
1438 std::wstring m_statustext;
1442 IntervalLimiter profiler_interval;
1445 * TODO: Local caching of settings is not optimal and should at some stage
1446 * be updated to use a global settings object for getting thse values
1447 * (as opposed to the this local caching). This can be addressed in
1450 bool m_cache_doubletap_jump;
1451 bool m_cache_enable_clouds;
1452 bool m_cache_enable_joysticks;
1453 bool m_cache_enable_particles;
1454 bool m_cache_enable_fog;
1455 bool m_cache_enable_noclip;
1456 bool m_cache_enable_free_move;
1457 f32 m_cache_mouse_sensitivity;
1458 f32 m_cache_joystick_frustum_sensitivity;
1459 f32 m_repeat_right_click_time;
1460 f32 m_cache_cam_smoothing;
1461 f32 m_cache_fog_start;
1463 bool m_invert_mouse;
1464 bool m_first_loop_after_window_activation;
1465 bool m_camera_offset_changed;
1468 bool m_cache_hold_aux1;
1469 bool m_android_chat_open;
1478 itemdef_manager(NULL),
1479 nodedef_manager(NULL),
1481 sound_is_dummy(false),
1484 current_formspec(NULL),
1488 gui_chat_console(NULL),
1493 local_inventory(NULL),
1496 m_invert_mouse(false),
1497 m_first_loop_after_window_activation(false),
1498 m_camera_offset_changed(false)
1500 g_settings->registerChangedCallback("doubletap_jump",
1501 &settingChangedCallback, this);
1502 g_settings->registerChangedCallback("enable_clouds",
1503 &settingChangedCallback, this);
1504 g_settings->registerChangedCallback("doubletap_joysticks",
1505 &settingChangedCallback, this);
1506 g_settings->registerChangedCallback("enable_particles",
1507 &settingChangedCallback, this);
1508 g_settings->registerChangedCallback("enable_fog",
1509 &settingChangedCallback, this);
1510 g_settings->registerChangedCallback("mouse_sensitivity",
1511 &settingChangedCallback, this);
1512 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1513 &settingChangedCallback, this);
1514 g_settings->registerChangedCallback("repeat_rightclick_time",
1515 &settingChangedCallback, this);
1516 g_settings->registerChangedCallback("noclip",
1517 &settingChangedCallback, this);
1518 g_settings->registerChangedCallback("free_move",
1519 &settingChangedCallback, this);
1520 g_settings->registerChangedCallback("cinematic",
1521 &settingChangedCallback, this);
1522 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1523 &settingChangedCallback, this);
1524 g_settings->registerChangedCallback("camera_smoothing",
1525 &settingChangedCallback, this);
1530 m_cache_hold_aux1 = false; // This is initialised properly later
1537 /****************************************************************************
1539 ****************************************************************************/
1545 if (!sound_is_dummy)
1548 delete server; // deleted first to stop all server threads
1551 delete local_inventory;
1557 delete nodedef_manager;
1558 delete itemdef_manager;
1559 delete draw_control;
1561 extendedResourceCleanup();
1563 g_settings->deregisterChangedCallback("doubletap_jump",
1564 &settingChangedCallback, this);
1565 g_settings->deregisterChangedCallback("enable_clouds",
1566 &settingChangedCallback, this);
1567 g_settings->deregisterChangedCallback("enable_particles",
1568 &settingChangedCallback, this);
1569 g_settings->deregisterChangedCallback("enable_fog",
1570 &settingChangedCallback, this);
1571 g_settings->deregisterChangedCallback("mouse_sensitivity",
1572 &settingChangedCallback, this);
1573 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1574 &settingChangedCallback, this);
1575 g_settings->deregisterChangedCallback("noclip",
1576 &settingChangedCallback, this);
1577 g_settings->deregisterChangedCallback("free_move",
1578 &settingChangedCallback, this);
1579 g_settings->deregisterChangedCallback("cinematic",
1580 &settingChangedCallback, this);
1581 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1582 &settingChangedCallback, this);
1583 g_settings->deregisterChangedCallback("camera_smoothing",
1584 &settingChangedCallback, this);
1587 bool Game::startup(bool *kill,
1589 InputHandler *input,
1590 const std::string &map_dir,
1591 const std::string &playername,
1592 const std::string &password,
1593 std::string *address, // can change if simple_singleplayer_mode
1595 std::string &error_message,
1597 ChatBackend *chat_backend,
1598 const SubgameSpec &gamespec,
1599 bool simple_singleplayer_mode)
1602 this->device = RenderingEngine::get_raw_device();
1604 this->error_message = &error_message;
1605 this->reconnect_requested = reconnect;
1606 this->random_input = random_input;
1607 this->input = input;
1608 this->chat_backend = chat_backend;
1609 this->simple_singleplayer_mode = simple_singleplayer_mode;
1611 keycache.handler = input;
1612 keycache.populate();
1614 driver = device->getVideoDriver();
1615 smgr = RenderingEngine::get_scene_manager();
1617 RenderingEngine::get_scene_manager()->getParameters()->
1618 setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1620 memset(&runData, 0, sizeof(runData));
1621 runData.time_from_last_punch = 10.0;
1622 runData.profiler_max_page = 3;
1623 runData.update_wielded_item_trigger = true;
1625 memset(&flags, 0, sizeof(flags));
1626 flags.show_chat = true;
1627 flags.show_hud = true;
1628 flags.show_debug = g_settings->getBool("show_debug");
1629 m_invert_mouse = g_settings->getBool("invert_mouse");
1630 m_first_loop_after_window_activation = true;
1632 if (!init(map_dir, address, port, gamespec))
1635 if (!createClient(playername, password, address, port))
1644 ProfilerGraph graph;
1645 RunStats stats = { 0 };
1646 CameraOrientation cam_view_target = { 0 };
1647 CameraOrientation cam_view = { 0 };
1648 FpsControl draw_times = { 0 };
1649 f32 dtime; // in seconds
1651 /* Clear the profiler */
1652 Profiler::GraphValues dummyvalues;
1653 g_profiler->graphGet(dummyvalues);
1655 draw_times.last_time = RenderingEngine::get_timer_time();
1657 set_light_table(g_settings->getFloat("display_gamma"));
1660 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1661 && client->checkPrivilege("fast");
1664 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1665 g_settings->getU16("screen_h"));
1667 while (RenderingEngine::run()
1668 && !(*kill || g_gamecallback->shutdown_requested
1669 || (server && server->getShutdownRequested()))) {
1671 const irr::core::dimension2d<u32> ¤t_screen_size =
1672 RenderingEngine::get_video_driver()->getScreenSize();
1673 // Verify if window size has changed and save it if it's the case
1674 // Ensure evaluating settings->getBool after verifying screensize
1675 // First condition is cheaper
1676 if (previous_screen_size != current_screen_size &&
1677 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1678 g_settings->getBool("autosave_screensize")) {
1679 g_settings->setU16("screen_w", current_screen_size.Width);
1680 g_settings->setU16("screen_h", current_screen_size.Height);
1681 previous_screen_size = current_screen_size;
1684 /* Must be called immediately after a device->run() call because it
1685 * uses device->getTimer()->getTime()
1687 limitFps(&draw_times, &dtime);
1689 updateStats(&stats, draw_times, dtime);
1690 updateInteractTimers(dtime);
1692 if (!checkConnection())
1694 if (!handleCallbacks())
1700 hud->resizeHotbar();
1702 updateProfilers(stats, draw_times, dtime);
1703 processUserInput(dtime);
1704 // Update camera before player movement to avoid camera lag of one frame
1705 updateCameraDirection(&cam_view_target, dtime);
1706 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1707 cam_view.camera_yaw) * m_cache_cam_smoothing;
1708 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1709 cam_view.camera_pitch) * m_cache_cam_smoothing;
1710 updatePlayerControl(cam_view);
1712 processClientEvents(&cam_view_target);
1713 updateCamera(draw_times.busy_time, dtime);
1715 processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
1716 updateFrame(&graph, &stats, dtime, cam_view);
1717 updateProfilerGraphs(&graph);
1719 // Update if minimap has been disabled by the server
1720 flags.show_minimap &= client->shouldShowMinimap();
1725 void Game::shutdown()
1727 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1728 if (g_settings->get("3d_mode") == "pageflip") {
1729 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1732 if (current_formspec)
1733 current_formspec->quitMenu();
1735 showOverlayMessage("Shutting down...", 0, 0, false);
1740 if (gui_chat_console)
1741 gui_chat_console->drop();
1747 while (g_menumgr.menuCount() > 0) {
1748 g_menumgr.m_stack.front()->setVisible(false);
1749 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1752 if (current_formspec) {
1753 current_formspec->drop();
1754 current_formspec = NULL;
1757 chat_backend->addMessage(L"", L"# Disconnected.");
1758 chat_backend->addMessage(L"", L"");
1762 while (!client->isShutdown()) {
1763 assert(texture_src != NULL);
1764 assert(shader_src != NULL);
1765 texture_src->processQueue();
1766 shader_src->processQueue();
1773 /****************************************************************************/
1774 /****************************************************************************
1776 ****************************************************************************/
1777 /****************************************************************************/
1780 const std::string &map_dir,
1781 std::string *address,
1783 const SubgameSpec &gamespec)
1785 texture_src = createTextureSource();
1787 showOverlayMessage("Loading...", 0, 0);
1789 shader_src = createShaderSource();
1791 itemdef_manager = createItemDefManager();
1792 nodedef_manager = createNodeDefManager();
1794 eventmgr = new EventManager();
1795 quicktune = new QuicktuneShortcutter();
1797 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1798 && eventmgr && quicktune))
1804 // Create a server if not connecting to an existing one
1805 if (*address == "") {
1806 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1813 bool Game::initSound()
1816 if (g_settings->getBool("enable_sound")) {
1817 infostream << "Attempting to use OpenAL audio" << std::endl;
1818 sound = createOpenALSoundManager(&soundfetcher);
1820 infostream << "Failed to initialize OpenAL audio" << std::endl;
1822 infostream << "Sound disabled." << std::endl;
1826 infostream << "Using dummy audio." << std::endl;
1827 sound = &dummySoundManager;
1828 sound_is_dummy = true;
1831 soundmaker = new SoundMaker(sound, nodedef_manager);
1835 soundmaker->registerReceiver(eventmgr);
1840 bool Game::createSingleplayerServer(const std::string &map_dir,
1841 const SubgameSpec &gamespec, u16 port, std::string *address)
1843 showOverlayMessage("Creating server...", 0, 5);
1845 std::string bind_str = g_settings->get("bind_address");
1846 Address bind_addr(0, 0, 0, 0, port);
1848 if (g_settings->getBool("ipv6_server")) {
1849 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1853 bind_addr.Resolve(bind_str.c_str());
1854 } catch (ResolveError &e) {
1855 infostream << "Resolving bind address \"" << bind_str
1856 << "\" failed: " << e.what()
1857 << " -- Listening on all addresses." << std::endl;
1860 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1861 *error_message = "Unable to listen on " +
1862 bind_addr.serializeString() +
1863 " because IPv6 is disabled";
1864 errorstream << *error_message << std::endl;
1868 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1869 bind_addr.isIPv6(), false);
1871 server->start(bind_addr);
1876 bool Game::createClient(const std::string &playername,
1877 const std::string &password, std::string *address, u16 port)
1879 showOverlayMessage("Creating client...", 0, 10);
1881 draw_control = new MapDrawControl;
1885 bool could_connect, connect_aborted;
1887 if (!connectToServer(playername, password, address, port,
1888 &could_connect, &connect_aborted))
1891 if (!could_connect) {
1892 if (error_message->empty() && !connect_aborted) {
1893 // Should not happen if error messages are set properly
1894 *error_message = "Connection failed for unknown reason";
1895 errorstream << *error_message << std::endl;
1900 if (!getServerContent(&connect_aborted)) {
1901 if (error_message->empty() && !connect_aborted) {
1902 // Should not happen if error messages are set properly
1903 *error_message = "Connection failed for unknown reason";
1904 errorstream << *error_message << std::endl;
1909 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1910 &flags.force_fog_off, &runData.fog_range, client);
1911 shader_src->addShaderConstantSetterFactory(scsf);
1913 // Update cached textures, meshes and materials
1914 client->afterContentReceived();
1918 camera = new Camera(*draw_control, client);
1919 if (!camera || !camera->successfullyCreated(*error_message))
1921 client->setCamera(camera);
1925 if (m_cache_enable_clouds) {
1926 clouds = new Clouds(smgr, -1, time(0));
1928 *error_message = "Memory allocation error (clouds)";
1929 errorstream << *error_message << std::endl;
1936 sky = new Sky(-1, texture_src);
1938 skybox = NULL; // This is used/set later on in the main run loop
1940 local_inventory = new Inventory(itemdef_manager);
1942 if (!(sky && local_inventory)) {
1943 *error_message = "Memory allocation error (sky or local inventory)";
1944 errorstream << *error_message << std::endl;
1948 /* Pre-calculated values
1950 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1952 v2u32 size = t->getOriginalSize();
1953 crack_animation_length = size.Y / size.X;
1955 crack_animation_length = 5;
1961 /* Set window caption
1963 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1965 str += utf8_to_wide(g_version_hash);
1967 str += driver->getName();
1969 device->setWindowCaption(str.c_str());
1971 LocalPlayer *player = client->getEnv().getLocalPlayer();
1972 player->hurt_tilt_timer = 0;
1973 player->hurt_tilt_strength = 0;
1975 hud = new Hud(guienv, client, player, local_inventory);
1978 *error_message = "Memory error: could not create HUD";
1979 errorstream << *error_message << std::endl;
1983 mapper = client->getMinimap();
1985 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1990 bool Game::initGui()
1992 // First line of debug text
1993 guitext = addStaticText(guienv,
1994 utf8_to_wide(PROJECT_NAME_C).c_str(),
1995 core::rect<s32>(0, 0, 0, 0),
1996 false, false, guiroot);
1998 // Second line of debug text
1999 guitext2 = addStaticText(guienv,
2001 core::rect<s32>(0, 0, 0, 0),
2002 false, false, guiroot);
2004 // At the middle of the screen
2005 // Object infos are shown in this
2006 guitext_info = addStaticText(guienv,
2008 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2009 false, true, guiroot);
2011 // Status text (displays info when showing and hiding GUI stuff, etc.)
2012 guitext_status = addStaticText(guienv,
2014 core::rect<s32>(0, 0, 0, 0),
2015 false, false, guiroot);
2016 guitext_status->setVisible(false);
2019 guitext_chat = addStaticText(
2022 core::rect<s32>(0, 0, 0, 0),
2023 //false, false); // Disable word wrap as of now
2024 false, true, guiroot);
2026 // Remove stale "recent" chat messages from previous connections
2027 chat_backend->clearRecentChat();
2029 // Chat backend and console
2030 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2031 -1, chat_backend, client, &g_menumgr);
2032 if (!gui_chat_console) {
2033 *error_message = "Could not allocate memory for chat console";
2034 errorstream << *error_message << std::endl;
2038 // Profiler text (size is updated when text is updated)
2039 guitext_profiler = addStaticText(guienv,
2041 core::rect<s32>(0, 0, 0, 0),
2042 false, false, guiroot);
2043 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2044 guitext_profiler->setVisible(false);
2045 guitext_profiler->setWordWrap(true);
2047 #ifdef HAVE_TOUCHSCREENGUI
2049 if (g_touchscreengui)
2050 g_touchscreengui->init(texture_src);
2057 bool Game::connectToServer(const std::string &playername,
2058 const std::string &password, std::string *address, u16 port,
2059 bool *connect_ok, bool *aborted)
2061 *connect_ok = false; // Let's not be overly optimistic
2063 bool local_server_mode = false;
2065 showOverlayMessage("Resolving address...", 0, 15);
2067 Address connect_address(0, 0, 0, 0, port);
2070 connect_address.Resolve(address->c_str());
2072 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2073 //connect_address.Resolve("localhost");
2074 if (connect_address.isIPv6()) {
2075 IPv6AddressBytes addr_bytes;
2076 addr_bytes.bytes[15] = 1;
2077 connect_address.setAddress(&addr_bytes);
2079 connect_address.setAddress(127, 0, 0, 1);
2081 local_server_mode = true;
2083 } catch (ResolveError &e) {
2084 *error_message = std::string("Couldn't resolve address: ") + e.what();
2085 errorstream << *error_message << std::endl;
2089 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2090 *error_message = "Unable to connect to " +
2091 connect_address.serializeString() +
2092 " because IPv6 is disabled";
2093 errorstream << *error_message << std::endl;
2097 client = new Client(playername.c_str(), password, *address,
2098 *draw_control, texture_src, shader_src,
2099 itemdef_manager, nodedef_manager, sound, eventmgr,
2100 connect_address.isIPv6(), &flags);
2105 infostream << "Connecting to server at ";
2106 connect_address.print(&infostream);
2107 infostream << std::endl;
2109 client->connect(connect_address,
2110 simple_singleplayer_mode || local_server_mode);
2113 Wait for server to accept connection
2119 FpsControl fps_control = { 0 };
2121 f32 wait_time = 0; // in seconds
2123 fps_control.last_time = RenderingEngine::get_timer_time();
2128 while (RenderingEngine::run()) {
2130 limitFps(&fps_control, &dtime);
2132 // Update client and server
2133 client->step(dtime);
2136 server->step(dtime);
2139 if (client->getState() == LC_Init) {
2145 if (client->accessDenied()) {
2146 *error_message = "Access denied. Reason: "
2147 + client->accessDeniedReason();
2148 *reconnect_requested = client->reconnectRequested();
2149 errorstream << *error_message << std::endl;
2153 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2155 infostream << "Connect aborted [Escape]" << std::endl;
2160 // Only time out if we aren't waiting for the server we started
2161 if ((*address != "") && (wait_time > 10)) {
2162 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2163 // If no pre v25 init was sent, and no answer was received,
2164 // but the low level connection could be established
2165 // (meaning that we have a peer id), then we probably wanted
2166 // to connect to a legacy server. In this case, tell the user
2167 // to enable the option to be able to connect.
2168 if (!sent_old_init &&
2169 (client->getProtoVersion() == 0) &&
2170 client->connectedToServer()) {
2171 *error_message = "Connection failure: init packet not "
2172 "recognized by server.\n"
2173 "Most likely the server uses an old protocol version (<v25).\n"
2174 "Please ask the server owner to update to 0.4.13 or later.\n"
2175 "To still connect to the server in the meantime,\n"
2176 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2177 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2178 "entry in the advanced settings menu.";
2180 *error_message = "Connection timed out.";
2182 errorstream << *error_message << std::endl;
2187 showOverlayMessage("Connecting to server...", dtime, 20);
2189 } catch (con::PeerNotFoundException &e) {
2190 // TODO: Should something be done here? At least an info/error
2198 bool Game::getServerContent(bool *aborted)
2202 FpsControl fps_control = { 0 };
2203 f32 dtime; // in seconds
2205 fps_control.last_time = RenderingEngine::get_timer_time();
2207 while (RenderingEngine::run()) {
2209 limitFps(&fps_control, &dtime);
2211 // Update client and server
2212 client->step(dtime);
2215 server->step(dtime);
2218 if (client->mediaReceived() && client->itemdefReceived() &&
2219 client->nodedefReceived()) {
2224 if (!checkConnection())
2227 if (client->getState() < LC_Init) {
2228 *error_message = "Client disconnected";
2229 errorstream << *error_message << std::endl;
2233 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2235 infostream << "Connect aborted [Escape]" << std::endl;
2242 if (!client->itemdefReceived()) {
2243 const wchar_t *text = wgettext("Item definitions...");
2245 RenderingEngine::draw_load_screen(text, guienv, texture_src,
2248 } else if (!client->nodedefReceived()) {
2249 const wchar_t *text = wgettext("Node definitions...");
2251 RenderingEngine::draw_load_screen(text, guienv, texture_src,
2255 std::stringstream message;
2256 std::fixed(message);
2257 message.precision(0);
2258 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2259 message.precision(2);
2261 if ((USE_CURL == 0) ||
2262 (!g_settings->getBool("enable_remote_media_server"))) {
2263 float cur = client->getCurRate();
2264 std::string cur_unit = gettext("KiB/s");
2268 cur_unit = gettext("MiB/s");
2271 message << " (" << cur << ' ' << cur_unit << ")";
2274 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2275 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
2276 texture_src, dtime, progress);
2284 /****************************************************************************/
2285 /****************************************************************************
2287 ****************************************************************************/
2288 /****************************************************************************/
2290 inline void Game::updateInteractTimers(f32 dtime)
2292 if (runData.nodig_delay_timer >= 0)
2293 runData.nodig_delay_timer -= dtime;
2295 if (runData.object_hit_delay_timer >= 0)
2296 runData.object_hit_delay_timer -= dtime;
2298 runData.time_from_last_punch += dtime;
2302 /* returns false if game should exit, otherwise true
2304 inline bool Game::checkConnection()
2306 if (client->accessDenied()) {
2307 *error_message = "Access denied. Reason: "
2308 + client->accessDeniedReason();
2309 *reconnect_requested = client->reconnectRequested();
2310 errorstream << *error_message << std::endl;
2318 /* returns false if game should exit, otherwise true
2320 inline bool Game::handleCallbacks()
2322 if (g_gamecallback->disconnect_requested) {
2323 g_gamecallback->disconnect_requested = false;
2327 if (g_gamecallback->changepassword_requested) {
2328 (new GUIPasswordChange(guienv, guiroot, -1,
2329 &g_menumgr, client))->drop();
2330 g_gamecallback->changepassword_requested = false;
2333 if (g_gamecallback->changevolume_requested) {
2334 (new GUIVolumeChange(guienv, guiroot, -1,
2335 &g_menumgr))->drop();
2336 g_gamecallback->changevolume_requested = false;
2339 if (g_gamecallback->keyconfig_requested) {
2340 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2341 &g_menumgr))->drop();
2342 g_gamecallback->keyconfig_requested = false;
2345 if (g_gamecallback->keyconfig_changed) {
2346 keycache.populate(); // update the cache with new settings
2347 g_gamecallback->keyconfig_changed = false;
2354 void Game::processQueues()
2356 texture_src->processQueue();
2357 itemdef_manager->processQueue(client);
2358 shader_src->processQueue();
2362 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2364 float profiler_print_interval =
2365 g_settings->getFloat("profiler_print_interval");
2366 bool print_to_log = true;
2368 if (profiler_print_interval == 0) {
2369 print_to_log = false;
2370 profiler_print_interval = 5;
2373 if (profiler_interval.step(dtime, profiler_print_interval)) {
2375 infostream << "Profiler:" << std::endl;
2376 g_profiler->print(infostream);
2379 update_profiler_gui(guitext_profiler, g_fontengine,
2380 runData.profiler_current_page, runData.profiler_max_page,
2381 driver->getScreenSize().Height);
2383 g_profiler->clear();
2386 addProfilerGraphs(stats, draw_times, dtime);
2390 void Game::addProfilerGraphs(const RunStats &stats,
2391 const FpsControl &draw_times, f32 dtime)
2393 g_profiler->graphAdd("mainloop_other",
2394 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2396 if (draw_times.sleep_time != 0)
2397 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2398 g_profiler->graphAdd("mainloop_dtime", dtime);
2400 g_profiler->add("Elapsed time", dtime);
2401 g_profiler->avg("FPS", 1. / dtime);
2405 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2412 /* Time average and jitter calculation
2414 jp = &stats->dtime_jitter;
2415 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2417 jitter = dtime - jp->avg;
2419 if (jitter > jp->max)
2422 jp->counter += dtime;
2424 if (jp->counter > 0.0) {
2426 jp->max_sample = jp->max;
2427 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2431 /* Busytime average and jitter calculation
2433 jp = &stats->busy_time_jitter;
2434 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2436 jitter = draw_times.busy_time - jp->avg;
2438 if (jitter > jp->max)
2440 if (jitter < jp->min)
2443 jp->counter += dtime;
2445 if (jp->counter > 0.0) {
2447 jp->max_sample = jp->max;
2448 jp->min_sample = jp->min;
2456 /****************************************************************************
2458 ****************************************************************************/
2460 void Game::processUserInput(f32 dtime)
2462 // Reset input if window not active or some menu is active
2463 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
2465 #ifdef HAVE_TOUCHSCREENGUI
2466 g_touchscreengui->hide();
2469 #ifdef HAVE_TOUCHSCREENGUI
2470 else if (g_touchscreengui) {
2471 /* on touchscreengui step may generate own input events which ain't
2472 * what we want in case we just did clear them */
2473 g_touchscreengui->step(dtime);
2477 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2478 gui_chat_console->closeConsoleAtOnce();
2481 // Input handler step() (used by the random input generator)
2485 if (current_formspec != NULL)
2486 current_formspec->getAndroidUIInput();
2488 handleAndroidChatInput();
2491 // Increase timer for double tap of "keymap_jump"
2492 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2493 runData.jump_timer += dtime;
2496 processItemSelection(&runData.new_playeritem);
2500 void Game::processKeyInput()
2502 if (wasKeyDown(KeyType::DROP)) {
2504 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
2505 toggleAutoforward();
2506 } else if (wasKeyDown(KeyType::INVENTORY)) {
2508 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2509 if (!gui_chat_console->isOpenInhibited()) {
2512 } else if (wasKeyDown(KeyType::CHAT)) {
2513 openConsole(0.2, L"");
2514 } else if (wasKeyDown(KeyType::CMD)) {
2515 openConsole(0.2, L"/");
2516 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2517 openConsole(0.2, L".");
2518 } else if (wasKeyDown(KeyType::CONSOLE)) {
2519 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2520 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2522 } else if (wasKeyDown(KeyType::JUMP)) {
2523 toggleFreeMoveAlt();
2524 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2526 } else if (wasKeyDown(KeyType::NOCLIP)) {
2528 } else if (wasKeyDown(KeyType::MUTE)) {
2529 float volume = g_settings->getFloat("sound_volume");
2530 if (volume < 0.001f) {
2531 g_settings->setFloat("sound_volume", 1.0f);
2532 m_statustext = narrow_to_wide(gettext("Volume changed to 100%"));
2534 g_settings->setFloat("sound_volume", 0.0f);
2535 m_statustext = narrow_to_wide(gettext("Volume changed to 0%"));
2537 runData.statustext_time = 0;
2538 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
2539 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
2541 g_settings->setFloat("sound_volume", new_volume);
2542 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2543 m_statustext = narrow_to_wide(buf);
2544 runData.statustext_time = 0;
2545 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
2546 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
2548 g_settings->setFloat("sound_volume", new_volume);
2549 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2550 m_statustext = narrow_to_wide(buf);
2551 runData.statustext_time = 0;
2552 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2554 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2555 client->makeScreenshot();
2556 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2558 } else if (wasKeyDown(KeyType::MINIMAP)) {
2559 toggleMinimap(isKeyDown(KeyType::SNEAK));
2560 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2562 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2564 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2565 toggleUpdateCamera();
2566 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2568 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2570 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2571 increaseViewRange();
2572 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2573 decreaseViewRange();
2574 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2575 toggleFullViewRange();
2576 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2578 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2580 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2582 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2584 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2585 // Print debug stacks
2586 dstream << "-----------------------------------------"
2588 dstream << "Printing debug stacks:" << std::endl;
2589 dstream << "-----------------------------------------"
2591 debug_stacks_print();
2594 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2595 runData.reset_jump_timer = false;
2596 runData.jump_timer = 0.0f;
2599 if (quicktune->hasMessage()) {
2600 m_statustext = utf8_to_wide(quicktune->getMessage());
2601 runData.statustext_time = 0.0f;
2605 void Game::processItemSelection(u16 *new_playeritem)
2607 LocalPlayer *player = client->getEnv().getLocalPlayer();
2609 /* Item selection using mouse wheel
2611 *new_playeritem = client->getPlayerItem();
2613 s32 wheel = input->getMouseWheel();
2614 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2615 player->hud_hotbar_itemcount - 1);
2619 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2620 wasKeyDown(KeyType::HOTBAR_NEXT)) {
2624 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2625 wasKeyDown(KeyType::HOTBAR_PREV)) {
2630 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2632 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2635 /* Item selection using keyboard
2637 for (u16 i = 0; i < 10; i++) {
2638 static const KeyPress *item_keys[10] = {
2639 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2640 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2641 NumberKey + 9, NumberKey + 0,
2644 if (input->wasKeyDown(*item_keys[i])) {
2645 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2646 *new_playeritem = i;
2647 infostream << "Selected item: " << new_playeritem << std::endl;
2655 void Game::dropSelectedItem()
2657 IDropAction *a = new IDropAction();
2659 a->from_inv.setCurrentPlayer();
2660 a->from_list = "main";
2661 a->from_i = client->getPlayerItem();
2662 client->inventoryAction(a);
2666 void Game::openInventory()
2669 * Don't permit to open inventory is CAO or player doesn't exists.
2670 * This prevent showing an empty inventory at player load
2673 LocalPlayer *player = client->getEnv().getLocalPlayer();
2674 if (!player || !player->getCAO())
2677 infostream << "the_game: " << "Launching inventory" << std::endl;
2679 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2680 TextDest *txt_dst = new TextDestPlayerInventory(client);
2682 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
2685 InventoryLocation inventoryloc;
2686 inventoryloc.setCurrentPlayer();
2687 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2691 void Game::openConsole(float scale, const wchar_t *line)
2693 assert(scale > 0.0f && scale <= 1.0f);
2696 porting::showInputDialog(gettext("ok"), "", "", 2);
2697 m_android_chat_open = true;
2699 if (gui_chat_console->isOpenInhibited())
2701 gui_chat_console->openConsole(scale);
2703 gui_chat_console->setCloseOnEnter(true);
2704 gui_chat_console->replaceAndAddToHistory(line);
2710 void Game::handleAndroidChatInput()
2712 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2713 std::string text = porting::getInputDialogValue();
2714 client->typeChatMessage(utf8_to_wide(text));
2720 void Game::toggleFreeMove()
2722 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2724 bool free_move = !g_settings->getBool("free_move");
2725 g_settings->set("free_move", bool_to_cstr(free_move));
2727 runData.statustext_time = 0;
2728 m_statustext = msg[free_move];
2729 if (free_move && !client->checkPrivilege("fly"))
2730 m_statustext += L" (note: no 'fly' privilege)";
2734 void Game::toggleFreeMoveAlt()
2736 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2739 runData.reset_jump_timer = true;
2743 void Game::toggleFast()
2745 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2746 bool fast_move = !g_settings->getBool("fast_move");
2747 g_settings->set("fast_move", bool_to_cstr(fast_move));
2749 runData.statustext_time = 0;
2750 m_statustext = msg[fast_move];
2752 bool has_fast_privs = client->checkPrivilege("fast");
2754 if (fast_move && !has_fast_privs)
2755 m_statustext += L" (note: no 'fast' privilege)";
2758 m_cache_hold_aux1 = fast_move && has_fast_privs;
2763 void Game::toggleNoClip()
2765 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2766 bool noclip = !g_settings->getBool("noclip");
2767 g_settings->set("noclip", bool_to_cstr(noclip));
2769 runData.statustext_time = 0;
2770 m_statustext = msg[noclip];
2772 if (noclip && !client->checkPrivilege("noclip"))
2773 m_statustext += L" (note: no 'noclip' privilege)";
2776 void Game::toggleCinematic()
2778 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2779 bool cinematic = !g_settings->getBool("cinematic");
2780 g_settings->set("cinematic", bool_to_cstr(cinematic));
2782 runData.statustext_time = 0;
2783 m_statustext = msg[cinematic];
2786 // Autoforward by toggling continuous forward.
2787 void Game::toggleAutoforward()
2789 static const wchar_t *msg[] = { L"autoforward disabled", L"autoforward enabled" };
2790 bool autoforward_enabled = !g_settings->getBool("continuous_forward");
2791 g_settings->set("continuous_forward", bool_to_cstr(autoforward_enabled));
2793 runData.statustext_time = 0;
2794 m_statustext = msg[autoforward_enabled ? 1 : 0];
2797 void Game::toggleChat()
2799 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2801 flags.show_chat = !flags.show_chat;
2802 runData.statustext_time = 0;
2803 m_statustext = msg[flags.show_chat];
2807 void Game::toggleHud()
2809 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2811 flags.show_hud = !flags.show_hud;
2812 runData.statustext_time = 0;
2813 m_statustext = msg[flags.show_hud];
2816 void Game::toggleMinimap(bool shift_pressed)
2818 if (!mapper || !flags.show_hud || !g_settings->getBool("enable_minimap"))
2821 if (shift_pressed) {
2822 mapper->toggleMinimapShape();
2826 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2828 MinimapMode mode = MINIMAP_MODE_OFF;
2829 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2830 mode = mapper->getMinimapMode();
2831 mode = (MinimapMode)((int)mode + 1);
2834 flags.show_minimap = true;
2836 case MINIMAP_MODE_SURFACEx1:
2837 m_statustext = L"Minimap in surface mode, Zoom x1";
2839 case MINIMAP_MODE_SURFACEx2:
2840 m_statustext = L"Minimap in surface mode, Zoom x2";
2842 case MINIMAP_MODE_SURFACEx4:
2843 m_statustext = L"Minimap in surface mode, Zoom x4";
2845 case MINIMAP_MODE_RADARx1:
2846 m_statustext = L"Minimap in radar mode, Zoom x1";
2848 case MINIMAP_MODE_RADARx2:
2849 m_statustext = L"Minimap in radar mode, Zoom x2";
2851 case MINIMAP_MODE_RADARx4:
2852 m_statustext = L"Minimap in radar mode, Zoom x4";
2855 mode = MINIMAP_MODE_OFF;
2856 flags.show_minimap = false;
2857 m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2858 L"Minimap hidden" : L"Minimap disabled by server";
2861 runData.statustext_time = 0;
2862 mapper->setMinimapMode(mode);
2865 void Game::toggleFog()
2867 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2869 flags.force_fog_off = !flags.force_fog_off;
2870 runData.statustext_time = 0;
2871 m_statustext = msg[flags.force_fog_off];
2875 void Game::toggleDebug()
2877 // Initial / 4x toggle: Chat only
2878 // 1x toggle: Debug text with chat
2879 // 2x toggle: Debug text with profiler graph
2880 // 3x toggle: Debug text and wireframe
2881 if (!flags.show_debug) {
2882 flags.show_debug = true;
2883 flags.show_profiler_graph = false;
2884 draw_control->show_wireframe = false;
2885 m_statustext = L"Debug info shown";
2886 } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2887 flags.show_profiler_graph = true;
2888 m_statustext = L"Profiler graph shown";
2889 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2890 flags.show_profiler_graph = false;
2891 draw_control->show_wireframe = true;
2892 m_statustext = L"Wireframe shown";
2894 flags.show_debug = false;
2895 flags.show_profiler_graph = false;
2896 draw_control->show_wireframe = false;
2897 if (client->checkPrivilege("debug")) {
2898 m_statustext = L"Debug info, profiler graph, and wireframe hidden";
2900 m_statustext = L"Debug info and profiler graph hidden";
2903 runData.statustext_time = 0;
2907 void Game::toggleUpdateCamera()
2909 static const wchar_t *msg[] = {
2910 L"Camera update enabled",
2911 L"Camera update disabled"
2914 flags.disable_camera_update = !flags.disable_camera_update;
2915 runData.statustext_time = 0;
2916 m_statustext = msg[flags.disable_camera_update];
2920 void Game::toggleProfiler()
2922 runData.profiler_current_page =
2923 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2925 // FIXME: This updates the profiler with incomplete values
2926 update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2927 runData.profiler_max_page, driver->getScreenSize().Height);
2929 if (runData.profiler_current_page != 0) {
2930 std::wstringstream sstr;
2931 sstr << "Profiler shown (page " << runData.profiler_current_page
2932 << " of " << runData.profiler_max_page << ")";
2933 m_statustext = sstr.str();
2935 m_statustext = L"Profiler hidden";
2937 runData.statustext_time = 0;
2941 void Game::increaseViewRange()
2943 s16 range = g_settings->getS16("viewing_range");
2944 s16 range_new = range + 10;
2946 if (range_new > 4000) {
2948 m_statustext = utf8_to_wide("Viewing range is at maximum: "
2951 m_statustext = utf8_to_wide("Viewing range changed to "
2954 g_settings->set("viewing_range", itos(range_new));
2955 runData.statustext_time = 0;
2959 void Game::decreaseViewRange()
2961 s16 range = g_settings->getS16("viewing_range");
2962 s16 range_new = range - 10;
2964 if (range_new < 20) {
2966 m_statustext = utf8_to_wide("Viewing range is at minimum: "
2969 m_statustext = utf8_to_wide("Viewing range changed to "
2972 g_settings->set("viewing_range", itos(range_new));
2973 runData.statustext_time = 0;
2977 void Game::toggleFullViewRange()
2979 static const wchar_t *msg[] = {
2980 L"Disabled full viewing range",
2981 L"Enabled full viewing range"
2984 draw_control->range_all = !draw_control->range_all;
2985 infostream << msg[draw_control->range_all] << std::endl;
2986 m_statustext = msg[draw_control->range_all];
2987 runData.statustext_time = 0;
2991 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2993 if ((device->isWindowActive() && device->isWindowFocused()
2994 && !isMenuActive()) || random_input) {
2997 if (!random_input) {
2998 // Mac OSX gets upset if this is set every frame
2999 if (device->getCursorControl()->isVisible())
3000 device->getCursorControl()->setVisible(false);
3004 if (m_first_loop_after_window_activation)
3005 m_first_loop_after_window_activation = false;
3007 updateCameraOrientation(cam, dtime);
3009 input->setMousePos((driver->getScreenSize().Width / 2),
3010 (driver->getScreenSize().Height / 2));
3014 // Mac OSX gets upset if this is set every frame
3015 if (!device->getCursorControl()->isVisible())
3016 device->getCursorControl()->setVisible(true);
3019 m_first_loop_after_window_activation = true;
3024 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
3026 #ifdef HAVE_TOUCHSCREENGUI
3027 if (g_touchscreengui) {
3028 cam->camera_yaw += g_touchscreengui->getYawChange();
3029 cam->camera_pitch = g_touchscreengui->getPitch();
3033 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3034 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3036 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3040 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3041 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3043 #ifdef HAVE_TOUCHSCREENGUI
3047 if (m_cache_enable_joysticks) {
3048 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3049 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
3050 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
3053 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3057 void Game::updatePlayerControl(const CameraOrientation &cam)
3059 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3061 // DO NOT use the isKeyDown method for the forward, backward, left, right
3062 // buttons, as the code that uses the controls needs to be able to
3063 // distinguish between the two in order to know when to use joysticks.
3065 PlayerControl control(
3066 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3067 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3068 input->isKeyDown(keycache.key[KeyType::LEFT]),
3069 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3070 isKeyDown(KeyType::JUMP),
3071 isKeyDown(KeyType::SPECIAL1),
3072 isKeyDown(KeyType::SNEAK),
3073 isKeyDown(KeyType::ZOOM),
3078 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3079 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3083 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3084 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3085 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3086 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3087 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3088 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3089 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3090 ( (u32)(isLeftPressed() & 0x1) << 7) |
3091 ( (u32)(isRightPressed() & 0x1) << 8
3095 /* For Android, simulate holding down AUX1 (fast move) if the user has
3096 * the fast_move setting toggled on. If there is an aux1 key defined for
3097 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3100 if (m_cache_hold_aux1) {
3101 control.aux1 = control.aux1 ^ true;
3102 keypress_bits ^= ((u32)(1U << 5));
3106 client->setPlayerControl(control);
3107 LocalPlayer *player = client->getEnv().getLocalPlayer();
3108 player->keyPressed = keypress_bits;
3114 inline void Game::step(f32 *dtime)
3116 bool can_be_and_is_paused =
3117 (simple_singleplayer_mode && g_menumgr.pausesGame());
3119 if (can_be_and_is_paused) { // This is for a singleplayer server
3120 *dtime = 0; // No time passes
3122 if (server != NULL) {
3123 //TimeTaker timer("server->step(dtime)");
3124 server->step(*dtime);
3127 //TimeTaker timer("client.step(dtime)");
3128 client->step(*dtime);
3133 void Game::processClientEvents(CameraOrientation *cam)
3135 LocalPlayer *player = client->getEnv().getLocalPlayer();
3137 while (client->hasClientEvents()) {
3138 ClientEvent event = client->getClientEvent();
3140 switch (event.type) {
3141 case CE_PLAYER_DAMAGE:
3142 if (client->getHP() == 0)
3144 if (client->moddingEnabled()) {
3145 client->getScript()->on_damage_taken(event.player_damage.amount);
3148 runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3149 runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3151 player->hurt_tilt_timer = 1.5;
3152 player->hurt_tilt_strength =
3153 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3155 client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3158 case CE_PLAYER_FORCE_MOVE:
3159 cam->camera_yaw = event.player_force_move.yaw;
3160 cam->camera_pitch = event.player_force_move.pitch;
3163 case CE_DEATHSCREEN:
3164 // This should be enabled for death formspec in builtin
3165 client->getScript()->on_death();
3167 /* Handle visualization */
3168 runData.damage_flash = 0;
3169 player->hurt_tilt_timer = 0;
3170 player->hurt_tilt_strength = 0;
3173 case CE_SHOW_FORMSPEC:
3174 if (*(event.show_formspec.formspec) == "") {
3175 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3176 current_formspec->quitMenu();
3179 FormspecFormSource *fs_src =
3180 new FormspecFormSource(*(event.show_formspec.formspec));
3181 TextDestPlayerInventory *txt_dst =
3182 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3184 create_formspec_menu(¤t_formspec, client, &input->joystick,
3186 cur_formname = *(event.show_formspec.formname);
3189 delete event.show_formspec.formspec;
3190 delete event.show_formspec.formname;
3193 case CE_SHOW_LOCAL_FORMSPEC:
3195 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3196 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3197 create_formspec_menu(¤t_formspec, client, &input->joystick,
3200 delete event.show_formspec.formspec;
3201 delete event.show_formspec.formname;
3204 case CE_SPAWN_PARTICLE:
3205 case CE_ADD_PARTICLESPAWNER:
3206 case CE_DELETE_PARTICLESPAWNER:
3207 client->getParticleManager()->handleParticleEvent(&event, client, player);
3212 u32 id = event.hudadd.id;
3214 HudElement *e = player->getHud(id);
3217 delete event.hudadd.pos;
3218 delete event.hudadd.name;
3219 delete event.hudadd.scale;
3220 delete event.hudadd.text;
3221 delete event.hudadd.align;
3222 delete event.hudadd.offset;
3223 delete event.hudadd.world_pos;
3224 delete event.hudadd.size;
3229 e->type = (HudElementType)event.hudadd.type;
3230 e->pos = *event.hudadd.pos;
3231 e->name = *event.hudadd.name;
3232 e->scale = *event.hudadd.scale;
3233 e->text = *event.hudadd.text;
3234 e->number = event.hudadd.number;
3235 e->item = event.hudadd.item;
3236 e->dir = event.hudadd.dir;
3237 e->align = *event.hudadd.align;
3238 e->offset = *event.hudadd.offset;
3239 e->world_pos = *event.hudadd.world_pos;
3240 e->size = *event.hudadd.size;
3242 u32 new_id = player->addHud(e);
3243 //if this isn't true our huds aren't consistent
3244 sanity_check(new_id == id);
3247 delete event.hudadd.pos;
3248 delete event.hudadd.name;
3249 delete event.hudadd.scale;
3250 delete event.hudadd.text;
3251 delete event.hudadd.align;
3252 delete event.hudadd.offset;
3253 delete event.hudadd.world_pos;
3254 delete event.hudadd.size;
3259 HudElement *e = player->removeHud(event.hudrm.id);
3267 u32 id = event.hudchange.id;
3268 HudElement *e = player->getHud(id);
3271 delete event.hudchange.v3fdata;
3272 delete event.hudchange.v2fdata;
3273 delete event.hudchange.sdata;
3274 delete event.hudchange.v2s32data;
3278 switch (event.hudchange.stat) {
3280 e->pos = *event.hudchange.v2fdata;
3284 e->name = *event.hudchange.sdata;
3287 case HUD_STAT_SCALE:
3288 e->scale = *event.hudchange.v2fdata;
3292 e->text = *event.hudchange.sdata;
3295 case HUD_STAT_NUMBER:
3296 e->number = event.hudchange.data;
3300 e->item = event.hudchange.data;
3304 e->dir = event.hudchange.data;
3307 case HUD_STAT_ALIGN:
3308 e->align = *event.hudchange.v2fdata;
3311 case HUD_STAT_OFFSET:
3312 e->offset = *event.hudchange.v2fdata;
3315 case HUD_STAT_WORLD_POS:
3316 e->world_pos = *event.hudchange.v3fdata;
3320 e->size = *event.hudchange.v2s32data;
3325 delete event.hudchange.v3fdata;
3326 delete event.hudchange.v2fdata;
3327 delete event.hudchange.sdata;
3328 delete event.hudchange.v2s32data;
3332 sky->setVisible(false);
3333 // Whether clouds are visible in front of a custom skybox
3334 sky->setCloudsEnabled(event.set_sky.clouds);
3341 // Handle according to type
3342 if (*event.set_sky.type == "regular") {
3343 sky->setVisible(true);
3344 sky->setCloudsEnabled(true);
3345 } else if (*event.set_sky.type == "skybox" &&
3346 event.set_sky.params->size() == 6) {
3347 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3348 skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
3349 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3350 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3351 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3352 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3353 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3354 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3356 // Handle everything else as plain color
3358 if (*event.set_sky.type != "plain")
3359 infostream << "Unknown sky type: "
3360 << (*event.set_sky.type) << std::endl;
3362 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3365 delete event.set_sky.bgcolor;
3366 delete event.set_sky.type;
3367 delete event.set_sky.params;
3370 case CE_OVERRIDE_DAY_NIGHT_RATIO:
3371 client->getEnv().setDayNightRatioOverride(
3372 event.override_day_night_ratio.do_override,
3373 event.override_day_night_ratio.ratio_f * 1000);
3376 case CE_CLOUD_PARAMS:
3378 clouds->setDensity(event.cloud_params.density);
3379 clouds->setColorBright(video::SColor(event.cloud_params.color_bright));
3380 clouds->setColorAmbient(video::SColor(event.cloud_params.color_ambient));
3381 clouds->setHeight(event.cloud_params.height);
3382 clouds->setThickness(event.cloud_params.thickness);
3383 clouds->setSpeed(v2f(
3384 event.cloud_params.speed_x,
3385 event.cloud_params.speed_y));
3390 // unknown or unhandled type
3398 void Game::updateCamera(u32 busy_time, f32 dtime)
3400 LocalPlayer *player = client->getEnv().getLocalPlayer();
3403 For interaction purposes, get info about the held item
3405 - Is it a usable item?
3406 - Can it point to liquids?
3408 ItemStack playeritem;
3410 InventoryList *mlist = local_inventory->getList("main");
3412 if (mlist && client->getPlayerItem() < mlist->getSize())
3413 playeritem = mlist->getItem(client->getPlayerItem());
3416 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3417 InventoryList *hlist = local_inventory->getList("hand");
3419 playeritem = hlist->getItem(0);
3423 ToolCapabilities playeritem_toolcap =
3424 playeritem.getToolCapabilities(itemdef_manager);
3426 v3s16 old_camera_offset = camera->getOffset();
3428 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3429 GenericCAO *playercao = player->getCAO();
3431 // If playercao not loaded, don't change camera
3435 camera->toggleCameraMode();
3437 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3438 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3441 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3442 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3444 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3445 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3447 camera->step(dtime);
3449 v3f camera_position = camera->getPosition();
3450 v3f camera_direction = camera->getDirection();
3451 f32 camera_fov = camera->getFovMax();
3452 v3s16 camera_offset = camera->getOffset();
3454 m_camera_offset_changed = (camera_offset != old_camera_offset);
3456 if (!flags.disable_camera_update) {
3457 client->getEnv().getClientMap().updateCamera(camera_position,
3458 camera_direction, camera_fov, camera_offset);
3460 if (m_camera_offset_changed) {
3461 client->updateCameraOffset(camera_offset);
3462 client->getEnv().updateCameraOffset(camera_offset);
3465 clouds->updateCameraOffset(camera_offset);
3471 void Game::updateSound(f32 dtime)
3473 // Update sound listener
3474 v3s16 camera_offset = camera->getOffset();
3475 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3476 v3f(0, 0, 0), // velocity
3477 camera->getDirection(),
3478 camera->getCameraNode()->getUpVector());
3480 // Check if volume is in the proper range, else fix it.
3481 float old_volume = g_settings->getFloat("sound_volume");
3482 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
3483 sound->setListenerGain(new_volume);
3485 if (old_volume != new_volume) {
3486 g_settings->setFloat("sound_volume", new_volume);
3489 LocalPlayer *player = client->getEnv().getLocalPlayer();
3491 // Tell the sound maker whether to make footstep sounds
3492 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3494 // Update sound maker
3495 if (player->makes_footstep_sound)
3496 soundmaker->step(dtime);
3498 ClientMap &map = client->getEnv().getClientMap();
3499 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3500 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3504 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3506 LocalPlayer *player = client->getEnv().getLocalPlayer();
3508 ItemStack playeritem;
3510 InventoryList *mlist = local_inventory->getList("main");
3512 if (mlist && client->getPlayerItem() < mlist->getSize())
3513 playeritem = mlist->getItem(client->getPlayerItem());
3516 const ItemDefinition &playeritem_def =
3517 playeritem.getDefinition(itemdef_manager);
3518 InventoryList *hlist = local_inventory->getList("hand");
3519 const ItemDefinition &hand_def =
3520 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3522 v3f player_position = player->getPosition();
3523 v3f camera_position = camera->getPosition();
3524 v3f camera_direction = camera->getDirection();
3525 v3s16 camera_offset = camera->getOffset();
3529 Calculate what block is the crosshair pointing to
3532 f32 d = playeritem_def.range; // max. distance
3533 f32 d_hand = hand_def.range;
3535 if (d < 0 && d_hand >= 0)
3540 core::line3d<f32> shootline;
3542 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3543 shootline = core::line3d<f32>(camera_position,
3544 camera_position + camera_direction * BS * d);
3546 // prevent player pointing anything in front-view
3547 shootline = core::line3d<f32>(camera_position,camera_position);
3550 #ifdef HAVE_TOUCHSCREENGUI
3552 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3553 shootline = g_touchscreengui->getShootline();
3554 shootline.start += intToFloat(camera_offset, BS);
3555 shootline.end += intToFloat(camera_offset, BS);
3560 PointedThing pointed = updatePointedThing(shootline,
3561 playeritem_def.liquids_pointable,
3562 !runData.ldown_for_dig,
3565 if (pointed != runData.pointed_old) {
3566 infostream << "Pointing at " << pointed.dump() << std::endl;
3567 hud->updateSelectionMesh(camera_offset);
3572 - releasing left mouse button
3573 - pointing away from node
3575 if (runData.digging) {
3576 if (getLeftReleased()) {
3577 infostream << "Left button released"
3578 << " (stopped digging)" << std::endl;
3579 runData.digging = false;
3580 } else if (pointed != runData.pointed_old) {
3581 if (pointed.type == POINTEDTHING_NODE
3582 && runData.pointed_old.type == POINTEDTHING_NODE
3583 && pointed.node_undersurface
3584 == runData.pointed_old.node_undersurface) {
3585 // Still pointing to the same node, but a different face.
3588 infostream << "Pointing away from node"
3589 << " (stopped digging)" << std::endl;
3590 runData.digging = false;
3591 hud->updateSelectionMesh(camera_offset);
3595 if (!runData.digging) {
3596 client->interact(1, runData.pointed_old);
3597 client->setCrack(-1, v3s16(0, 0, 0));
3598 runData.dig_time = 0.0;
3600 } else if (runData.dig_instantly && getLeftReleased()) {
3601 // Remove e.g. torches faster when clicking instead of holding LMB
3602 runData.nodig_delay_timer = 0;
3603 runData.dig_instantly = false;
3606 if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3607 runData.ldown_for_dig = false;
3610 runData.left_punch = false;
3612 soundmaker->m_player_leftpunch_sound.name = "";
3614 if (isRightPressed())
3615 runData.repeat_rightclick_timer += dtime;
3617 runData.repeat_rightclick_timer = 0;
3619 if (playeritem_def.usable && isLeftPressed()) {
3620 if (getLeftClicked() && (!client->moddingEnabled()
3621 || !client->getScript()->on_item_use(playeritem, pointed)))
3622 client->interact(4, pointed);
3623 } else if (pointed.type == POINTEDTHING_NODE) {
3624 ToolCapabilities playeritem_toolcap =
3625 playeritem.getToolCapabilities(itemdef_manager);
3626 if (playeritem.name.empty() && hand_def.tool_capabilities != NULL) {
3627 playeritem_toolcap = *hand_def.tool_capabilities;
3629 handlePointingAtNode(pointed, playeritem_def, playeritem,
3630 playeritem_toolcap, dtime);
3631 } else if (pointed.type == POINTEDTHING_OBJECT) {
3632 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3633 } else if (isLeftPressed()) {
3634 // When button is held down in air, show continuous animation
3635 runData.left_punch = true;
3636 } else if (getRightClicked()) {
3637 handlePointingAtNothing(playeritem);
3640 runData.pointed_old = pointed;
3642 if (runData.left_punch || getLeftClicked())
3643 camera->setDigging(0); // left click animation
3645 input->resetLeftClicked();
3646 input->resetRightClicked();
3648 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3649 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3651 input->resetLeftReleased();
3652 input->resetRightReleased();
3654 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3655 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3659 PointedThing Game::updatePointedThing(
3660 const core::line3d<f32> &shootline,
3661 bool liquids_pointable,
3662 bool look_for_object,
3663 const v3s16 &camera_offset)
3665 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3666 selectionboxes->clear();
3667 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3668 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3669 "show_entity_selectionbox");
3671 ClientEnvironment &env = client->getEnv();
3672 ClientMap &map = env.getClientMap();
3673 INodeDefManager *nodedef = map.getNodeDefManager();
3675 runData.selected_object = NULL;
3677 RaycastState s(shootline, look_for_object, liquids_pointable);
3678 PointedThing result;
3679 env.continueRaycast(&s, &result);
3680 if (result.type == POINTEDTHING_OBJECT) {
3681 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3682 aabb3f selection_box;
3683 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3684 runData.selected_object->getSelectionBox(&selection_box)) {
3685 v3f pos = runData.selected_object->getPosition();
3686 selectionboxes->push_back(aabb3f(selection_box));
3687 hud->setSelectionPos(pos, camera_offset);
3689 } else if (result.type == POINTEDTHING_NODE) {
3690 // Update selection boxes
3691 MapNode n = map.getNodeNoEx(result.node_undersurface);
3692 std::vector<aabb3f> boxes;
3693 n.getSelectionBoxes(nodedef, &boxes,
3694 n.getNeighbors(result.node_undersurface, &map));
3697 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3698 i != boxes.end(); ++i) {
3700 box.MinEdge -= v3f(d, d, d);
3701 box.MaxEdge += v3f(d, d, d);
3702 selectionboxes->push_back(box);
3704 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3706 hud->setSelectedFaceNormal(v3f(
3707 result.intersection_normal.X,
3708 result.intersection_normal.Y,
3709 result.intersection_normal.Z));
3712 // Update selection mesh light level and vertex colors
3713 if (selectionboxes->size() > 0) {
3714 v3f pf = hud->getSelectionPos();
3715 v3s16 p = floatToInt(pf, BS);
3717 // Get selection mesh light level
3718 MapNode n = map.getNodeNoEx(p);
3719 u16 node_light = getInteriorLight(n, -1, nodedef);
3720 u16 light_level = node_light;
3722 for (u8 i = 0; i < 6; i++) {
3723 n = map.getNodeNoEx(p + g_6dirs[i]);
3724 node_light = getInteriorLight(n, -1, nodedef);
3725 if (node_light > light_level)
3726 light_level = node_light;
3729 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3731 final_color_blend(&c, light_level, daynight_ratio);
3733 // Modify final color a bit with time
3734 u32 timer = porting::getTimeMs() % 5000;
3735 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3736 float sin_r = 0.08 * sin(timerf);
3737 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3738 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3739 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3740 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3741 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3743 // Set mesh final color
3744 hud->setSelectionMeshColor(c);
3750 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3752 infostream << "Right Clicked in Air" << std::endl;
3753 PointedThing fauxPointed;
3754 fauxPointed.type = POINTEDTHING_NOTHING;
3755 client->interact(5, fauxPointed);
3759 void Game::handlePointingAtNode(const PointedThing &pointed,
3760 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
3761 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3763 v3s16 nodepos = pointed.node_undersurface;
3764 v3s16 neighbourpos = pointed.node_abovesurface;
3767 Check information text of node
3770 ClientMap &map = client->getEnv().getClientMap();
3772 if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3773 && client->checkPrivilege("interact")) {
3774 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3777 // This should be done after digging handling
3778 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3781 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3783 MapNode n = map.getNodeNoEx(nodepos);
3785 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3786 infotext = L"Unknown node: ";
3787 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3791 if ((getRightClicked() ||
3792 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3793 client->checkPrivilege("interact")) {
3794 runData.repeat_rightclick_timer = 0;
3795 infostream << "Ground right-clicked" << std::endl;
3797 if (meta && meta->getString("formspec") != "" && !random_input
3798 && !isKeyDown(KeyType::SNEAK)) {
3799 infostream << "Launching custom inventory view" << std::endl;
3801 InventoryLocation inventoryloc;
3802 inventoryloc.setNodeMeta(nodepos);
3804 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3805 &client->getEnv().getClientMap(), nodepos);
3806 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3808 create_formspec_menu(¤t_formspec, client,
3809 &input->joystick, fs_src, txt_dst);
3812 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3814 // Report right click to server
3816 camera->setDigging(1); // right click animation (always shown for feedback)
3818 // If the wielded item has node placement prediction,
3820 bool placed = nodePlacementPrediction(*client,
3821 playeritem_def, playeritem,
3822 nodepos, neighbourpos);
3826 client->interact(3, pointed);
3828 soundmaker->m_player_rightpunch_sound =
3829 playeritem_def.sound_place;
3831 if (client->moddingEnabled())
3832 client->getScript()->on_placenode(pointed, playeritem_def);
3834 soundmaker->m_player_rightpunch_sound =
3837 if (playeritem_def.node_placement_prediction == "" ||
3838 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3839 client->interact(3, pointed); // Report to server
3841 soundmaker->m_player_rightpunch_sound =
3842 playeritem_def.sound_place_failed;
3850 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3851 const v3f &player_position, bool show_debug)
3853 infotext = unescape_enriched(
3854 utf8_to_wide(runData.selected_object->infoText()));
3857 if (infotext != L"") {
3860 infotext += unescape_enriched(utf8_to_wide(
3861 runData.selected_object->debugInfoText()));
3864 if (isLeftPressed()) {
3865 bool do_punch = false;
3866 bool do_punch_damage = false;
3868 if (runData.object_hit_delay_timer <= 0.0) {
3870 do_punch_damage = true;
3871 runData.object_hit_delay_timer = object_hit_delay;
3874 if (getLeftClicked())
3878 infostream << "Left-clicked object" << std::endl;
3879 runData.left_punch = true;
3882 if (do_punch_damage) {
3883 // Report direct punch
3884 v3f objpos = runData.selected_object->getPosition();
3885 v3f dir = (objpos - player_position).normalize();
3886 ItemStack item = playeritem;
3887 if (playeritem.name.empty()) {
3888 InventoryList *hlist = local_inventory->getList("hand");
3890 item = hlist->getItem(0);
3894 bool disable_send = runData.selected_object->directReportPunch(
3895 dir, &item, runData.time_from_last_punch);
3896 runData.time_from_last_punch = 0;
3899 client->interact(0, pointed);
3901 } else if (getRightClicked()) {
3902 infostream << "Right-clicked object" << std::endl;
3903 client->interact(3, pointed); // place
3908 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3909 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3911 LocalPlayer *player = client->getEnv().getLocalPlayer();
3912 ClientMap &map = client->getEnv().getClientMap();
3913 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3915 // NOTE: Similar piece of code exists on the server side for
3917 // Get digging parameters
3918 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3919 &playeritem_toolcap);
3921 // If can't dig, try hand
3922 if (!params.diggable) {
3923 InventoryList *hlist = local_inventory->getList("hand");
3924 const ItemDefinition &hand =
3925 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3926 const ToolCapabilities *tp = hand.tool_capabilities;
3929 params = getDigParams(nodedef_manager->get(n).groups, tp);
3932 if (!params.diggable) {
3933 // I guess nobody will wait for this long
3934 runData.dig_time_complete = 10000000.0;
3936 runData.dig_time_complete = params.time;
3938 if (m_cache_enable_particles) {
3939 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3940 client->getParticleManager()->addPunchingParticles(client,
3941 player, nodepos, n, features);
3945 if (!runData.digging) {
3946 infostream << "Started digging" << std::endl;
3947 runData.dig_instantly = runData.dig_time_complete == 0;
3948 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3950 client->interact(0, pointed);
3951 runData.digging = true;
3952 runData.ldown_for_dig = true;
3955 if (!runData.dig_instantly) {
3956 runData.dig_index = (float)crack_animation_length
3958 / runData.dig_time_complete;
3960 // This is for e.g. torches
3961 runData.dig_index = crack_animation_length;
3964 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3966 if (sound_dig.exists() && params.diggable) {
3967 if (sound_dig.name == "__group") {
3968 if (params.main_group != "") {
3969 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3970 soundmaker->m_player_leftpunch_sound.name =
3971 std::string("default_dig_") +
3975 soundmaker->m_player_leftpunch_sound = sound_dig;
3979 // Don't show cracks if not diggable
3980 if (runData.dig_time_complete >= 100000.0) {
3981 } else if (runData.dig_index < crack_animation_length) {
3982 //TimeTaker timer("client.setTempMod");
3983 //infostream<<"dig_index="<<dig_index<<std::endl;
3984 client->setCrack(runData.dig_index, nodepos);
3986 infostream << "Digging completed" << std::endl;
3987 client->setCrack(-1, v3s16(0, 0, 0));
3989 runData.dig_time = 0;
3990 runData.digging = false;
3992 runData.nodig_delay_timer =
3993 runData.dig_time_complete / (float)crack_animation_length;
3995 // We don't want a corresponding delay to very time consuming nodes
3996 // and nodes without digging time (e.g. torches) get a fixed delay.
3997 if (runData.nodig_delay_timer > 0.3)
3998 runData.nodig_delay_timer = 0.3;
3999 else if (runData.dig_instantly)
4000 runData.nodig_delay_timer = 0.15;
4002 bool is_valid_position;
4003 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
4004 if (is_valid_position) {
4005 if (client->moddingEnabled() &&
4006 client->getScript()->on_dignode(nodepos, wasnode)) {
4009 client->removeNode(nodepos);
4012 client->interact(2, pointed);
4014 if (m_cache_enable_particles) {
4015 const ContentFeatures &features =
4016 client->getNodeDefManager()->get(wasnode);
4017 client->getParticleManager()->addDiggingParticles(client,
4018 player, nodepos, wasnode, features);
4022 // Send event to trigger sound
4023 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4024 client->event()->put(e);
4027 if (runData.dig_time_complete < 100000.0) {
4028 runData.dig_time += dtime;
4030 runData.dig_time = 0;
4031 client->setCrack(-1, nodepos);
4034 camera->setDigging(0); // left click animation
4038 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
4039 const CameraOrientation &cam)
4041 LocalPlayer *player = client->getEnv().getLocalPlayer();
4047 if (draw_control->range_all) {
4048 runData.fog_range = 100000 * BS;
4050 runData.fog_range = draw_control->wanted_range * BS;
4054 Calculate general brightness
4056 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4057 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4058 float direct_brightness;
4061 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4062 direct_brightness = time_brightness;
4063 sunlight_seen = true;
4065 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4066 float old_brightness = sky->getBrightness();
4067 direct_brightness = client->getEnv().getClientMap()
4068 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
4069 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4073 float time_of_day_smooth = runData.time_of_day_smooth;
4074 float time_of_day = client->getEnv().getTimeOfDayF();
4076 static const float maxsm = 0.05;
4077 static const float todsm = 0.05;
4079 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4080 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4081 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4082 time_of_day_smooth = time_of_day;
4084 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4085 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4086 + (time_of_day + 1.0) * todsm;
4088 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4089 + time_of_day * todsm;
4091 runData.time_of_day = time_of_day;
4092 runData.time_of_day_smooth = time_of_day_smooth;
4094 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4095 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4096 player->getPitch());
4102 if (sky->getCloudsVisible()) {
4103 clouds->setVisible(true);
4104 clouds->step(dtime);
4105 // camera->getPosition is not enough for 3rd person views
4106 v3f camera_node_position = camera->getCameraNode()->getPosition();
4107 v3s16 camera_offset = camera->getOffset();
4108 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
4109 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
4110 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
4111 clouds->update(camera_node_position,
4112 sky->getCloudColor());
4113 if (clouds->isCameraInsideCloud() && m_cache_enable_fog &&
4114 !flags.force_fog_off) {
4115 // if inside clouds, and fog enabled, use that as sky
4117 video::SColor clouds_dark = clouds->getColor()
4118 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
4119 sky->overrideColors(clouds_dark, clouds->getColor());
4120 sky->setBodiesVisible(false);
4121 runData.fog_range = 20.0f * BS;
4122 // do not draw clouds after all
4123 clouds->setVisible(false);
4126 clouds->setVisible(false);
4133 client->getParticleManager()->step(dtime);
4139 if (m_cache_enable_fog && !flags.force_fog_off) {
4142 video::EFT_FOG_LINEAR,
4143 runData.fog_range * m_cache_fog_start,
4144 runData.fog_range * 1.0,
4152 video::EFT_FOG_LINEAR,
4162 Get chat messages from client
4165 v2u32 screensize = driver->getScreenSize();
4167 updateChat(*client, dtime, flags.show_debug, screensize,
4168 flags.show_chat, runData.profiler_current_page,
4169 *chat_backend, guitext_chat);
4175 if (client->getPlayerItem() != runData.new_playeritem)
4176 client->selectPlayerItem(runData.new_playeritem);
4178 // Update local inventory if it has changed
4179 if (client->getLocalInventoryUpdated()) {
4180 //infostream<<"Updating local inventory"<<std::endl;
4181 client->getLocalInventory(*local_inventory);
4182 runData.update_wielded_item_trigger = true;
4185 if (runData.update_wielded_item_trigger) {
4186 // Update wielded tool
4187 InventoryList *mlist = local_inventory->getList("main");
4189 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4190 ItemStack item = mlist->getItem(client->getPlayerItem());
4191 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4192 InventoryList *hlist = local_inventory->getList("hand");
4194 item = hlist->getItem(0);
4196 camera->wield(item);
4199 runData.update_wielded_item_trigger = false;
4203 Update block draw list every 200ms or when camera direction has
4206 runData.update_draw_list_timer += dtime;
4208 v3f camera_direction = camera->getDirection();
4209 if (runData.update_draw_list_timer >= 0.2
4210 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4211 || m_camera_offset_changed) {
4212 runData.update_draw_list_timer = 0;
4213 client->getEnv().getClientMap().updateDrawList(driver);
4214 runData.update_draw_list_last_cam_dir = camera_direction;
4217 updateGui(*stats, dtime, cam);
4220 make sure menu is on top
4221 1. Delete formspec menu reference if menu was removed
4222 2. Else, make sure formspec menu is on top
4224 if (current_formspec) {
4225 if (current_formspec->getReferenceCount() == 1) {
4226 current_formspec->drop();
4227 current_formspec = NULL;
4228 } else if (isMenuActive()) {
4229 guiroot->bringToFront(current_formspec);
4236 const video::SColor &skycolor = sky->getSkyColor();
4238 TimeTaker tt_draw("mainloop: draw");
4239 driver->beginScene(true, true, skycolor);
4241 RenderingEngine::draw_scene(camera, client, player, hud, mapper,
4242 guienv, screensize, skycolor, flags.show_hud,
4243 flags.show_minimap);
4248 if (flags.show_profiler_graph)
4249 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4254 if (runData.damage_flash > 0.0) {
4255 video::SColor color(runData.damage_flash, 180, 0, 0);
4256 driver->draw2DRectangle(color,
4257 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4260 runData.damage_flash -= 100.0 * dtime;
4266 if (player->hurt_tilt_timer > 0.0) {
4267 player->hurt_tilt_timer -= dtime * 5;
4269 if (player->hurt_tilt_timer < 0)
4270 player->hurt_tilt_strength = 0;
4274 Update minimap pos and rotation
4276 if (mapper && flags.show_minimap && flags.show_hud) {
4277 mapper->setPos(floatToInt(player->getPosition(), BS));
4278 mapper->setAngle(player->getYaw());
4286 stats->drawtime = tt_draw.stop(true);
4287 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4291 inline static const char *yawToDirectionString(int yaw)
4293 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4295 yaw = wrapDegrees_0_360(yaw);
4296 yaw = (yaw + 45) % 360 / 90;
4298 return direction[yaw];
4302 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4304 v2u32 screensize = driver->getScreenSize();
4305 LocalPlayer *player = client->getEnv().getLocalPlayer();
4306 v3f player_position = player->getPosition();
4308 if (flags.show_debug) {
4309 static float drawtime_avg = 0;
4310 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4312 u16 fps = 1.0 / stats.dtime_jitter.avg;
4314 std::ostringstream os(std::ios_base::binary);
4316 << PROJECT_NAME_C " " << g_version_hash
4317 << "; " << fps << " FPS"
4318 << ", (R: range_all=" << draw_control->range_all << ")"
4319 << std::setprecision(0)
4320 << ", drawtime = " << drawtime_avg << " ms"
4321 << std::setprecision(1)
4322 << ", dtime_jitter = "
4323 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4324 << std::setprecision(1)
4325 << ", v_range = " << draw_control->wanted_range
4326 << std::setprecision(3)
4327 << ", RTT = " << client->getRTT() << " s";
4328 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4329 guitext->setVisible(true);
4331 guitext->setVisible(false);
4334 if (guitext->isVisible()) {
4335 core::rect<s32> rect(
4337 screensize.X, 5 + g_fontengine->getTextHeight()
4339 guitext->setRelativePosition(rect);
4342 if (flags.show_debug) {
4343 std::ostringstream os(std::ios_base::binary);
4344 os << std::setprecision(1) << std::fixed
4345 << "(" << (player_position.X / BS)
4346 << ", " << (player_position.Y / BS)
4347 << ", " << (player_position.Z / BS)
4348 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw)) << "°"
4349 << " " << yawToDirectionString(cam.camera_yaw)
4350 << ") (seed = " << ((u64)client->getMapSeed())
4353 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4354 ClientMap &map = client->getEnv().getClientMap();
4355 const INodeDefManager *nodedef = client->getNodeDefManager();
4356 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4357 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4358 const ContentFeatures &features = nodedef->get(n);
4359 os << " (pointing_at = \"" << nodedef->get(n).name
4360 << "\", param1 = " << (u64) n.getParam1()
4361 << ", param2 = " << (u64) n.getParam2()
4362 << ", tiledef[0] = \"" << features.tiledef[0].name.c_str()
4367 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4368 guitext2->setVisible(true);
4370 core::rect<s32> rect(
4371 5, 5 + g_fontengine->getTextHeight(),
4372 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4374 guitext2->setRelativePosition(rect);
4376 guitext2->setVisible(false);
4379 setStaticText(guitext_info, infotext.c_str());
4380 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4382 float statustext_time_max = 1.5;
4384 if (!m_statustext.empty()) {
4385 runData.statustext_time += dtime;
4387 if (runData.statustext_time >= statustext_time_max) {
4389 runData.statustext_time = 0;
4393 setStaticText(guitext_status, m_statustext.c_str());
4394 guitext_status->setVisible(!m_statustext.empty());
4396 if (!m_statustext.empty()) {
4397 s32 status_width = guitext_status->getTextWidth();
4398 s32 status_height = guitext_status->getTextHeight();
4399 s32 status_y = screensize.Y - 150;
4400 s32 status_x = (screensize.X - status_width) / 2;
4401 core::rect<s32> rect(
4402 status_x , status_y - status_height,
4403 status_x + status_width, status_y
4405 guitext_status->setRelativePosition(rect);
4408 video::SColor initial_color(255, 0, 0, 0);
4410 if (guienv->getSkin())
4411 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4413 video::SColor final_color = initial_color;
4414 final_color.setAlpha(0);
4415 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4416 initial_color, final_color,
4417 pow(runData.statustext_time / statustext_time_max, 2.0f));
4418 guitext_status->setOverrideColor(fade_color);
4419 guitext_status->enableOverrideColor(true);
4424 /* Log times and stuff for visualization */
4425 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4427 Profiler::GraphValues values;
4428 g_profiler->graphGet(values);
4434 /****************************************************************************
4436 ****************************************************************************/
4438 /* On some computers framerate doesn't seem to be automatically limited
4440 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4442 // not using getRealTime is necessary for wine
4443 device->getTimer()->tick(); // Maker sure device time is up-to-date
4444 u32 time = device->getTimer()->getTime();
4445 u32 last_time = fps_timings->last_time;
4447 if (time > last_time) // Make sure time hasn't overflowed
4448 fps_timings->busy_time = time - last_time;
4450 fps_timings->busy_time = 0;
4452 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4453 ? g_settings->getFloat("pause_fps_max")
4454 : g_settings->getFloat("fps_max"));
4456 if (fps_timings->busy_time < frametime_min) {
4457 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4458 device->sleep(fps_timings->sleep_time);
4460 fps_timings->sleep_time = 0;
4463 /* Get the new value of the device timer. Note that device->sleep() may
4464 * not sleep for the entire requested time as sleep may be interrupted and
4465 * therefore it is arguably more accurate to get the new time from the
4466 * device rather than calculating it by adding sleep_time to time.
4469 device->getTimer()->tick(); // Update device timer
4470 time = device->getTimer()->getTime();
4472 if (time > last_time) // Make sure last_time hasn't overflowed
4473 *dtime = (time - last_time) / 1000.0;
4477 fps_timings->last_time = time;
4480 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
4482 const wchar_t *wmsg = wgettext(msg);
4483 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
4488 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4490 ((Game *)data)->readSettings();
4493 void Game::readSettings()
4495 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4496 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4497 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4498 m_cache_enable_particles = g_settings->getBool("enable_particles");
4499 m_cache_enable_fog = g_settings->getBool("enable_fog");
4500 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4501 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4502 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4504 m_cache_enable_noclip = g_settings->getBool("noclip");
4505 m_cache_enable_free_move = g_settings->getBool("free_move");
4507 m_cache_fog_start = g_settings->getFloat("fog_start");
4509 m_cache_cam_smoothing = 0;
4510 if (g_settings->getBool("cinematic"))
4511 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4513 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4515 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4516 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4517 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4521 /****************************************************************************/
4522 /****************************************************************************
4524 ****************************************************************************/
4525 /****************************************************************************/
4527 void Game::extendedResourceCleanup()
4529 // Extended resource accounting
4530 infostream << "Irrlicht resources after cleanup:" << std::endl;
4531 infostream << "\tRemaining meshes : "
4532 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
4533 infostream << "\tRemaining textures : "
4534 << driver->getTextureCount() << std::endl;
4536 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4537 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4538 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4542 clearTextureNameCache();
4543 infostream << "\tRemaining materials: "
4544 << driver-> getMaterialRendererCount()
4545 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4548 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4549 void Game::showPauseMenu()
4552 static const std::string control_text = strgettext("Default Controls:\n"
4553 "No menu visible:\n"
4554 "- single tap: button activate\n"
4555 "- double tap: place/use\n"
4556 "- slide finger: look around\n"
4557 "Menu/Inventory visible:\n"
4558 "- double tap (outside):\n"
4560 "- touch stack, touch slot:\n"
4562 "- touch&drag, tap 2nd finger\n"
4563 " --> place single item to slot\n"
4566 static const std::string control_text_template = strgettext("Controls:\n"
4567 "- %s: move forwards\n"
4568 "- %s: move backwards\n"
4570 "- %s: move right\n"
4571 "- %s: jump/climb\n"
4572 "- %s: sneak/go down\n"
4575 "- Mouse: turn/look\n"
4576 "- Mouse left: dig/punch\n"
4577 "- Mouse right: place/use\n"
4578 "- Mouse wheel: select item\n"
4582 char control_text_buf[600];
4584 snprintf(control_text_buf, ARRLEN(control_text_buf), control_text_template.c_str(),
4585 GET_KEY_NAME(keymap_forward),
4586 GET_KEY_NAME(keymap_backward),
4587 GET_KEY_NAME(keymap_left),
4588 GET_KEY_NAME(keymap_right),
4589 GET_KEY_NAME(keymap_jump),
4590 GET_KEY_NAME(keymap_sneak),
4591 GET_KEY_NAME(keymap_drop),
4592 GET_KEY_NAME(keymap_inventory),
4593 GET_KEY_NAME(keymap_chat)
4596 std::string control_text = std::string(control_text_buf);
4597 str_formspec_escape(control_text);
4600 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4601 std::ostringstream os;
4603 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4604 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4605 << strgettext("Continue") << "]";
4607 if (!simple_singleplayer_mode) {
4608 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4609 << strgettext("Change Password") << "]";
4611 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4615 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4616 << strgettext("Sound Volume") << "]";
4617 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4618 << strgettext("Change Keys") << "]";
4620 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4621 << strgettext("Exit to Menu") << "]";
4622 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4623 << strgettext("Exit to OS") << "]"
4624 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4625 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4627 << strgettext("Game info:") << "\n";
4628 const std::string &address = client->getAddressName();
4629 static const std::string mode = strgettext("- Mode: ");
4630 if (!simple_singleplayer_mode) {
4631 Address serverAddress = client->getServerAddress();
4632 if (address != "") {
4633 os << mode << strgettext("Remote server") << "\n"
4634 << strgettext("- Address: ") << address;
4636 os << mode << strgettext("Hosting server");
4638 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4640 os << mode << strgettext("Singleplayer") << "\n";
4642 if (simple_singleplayer_mode || address == "") {
4643 static const std::string on = strgettext("On");
4644 static const std::string off = strgettext("Off");
4645 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4646 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4647 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4648 os << strgettext("- Damage: ") << damage << "\n"
4649 << strgettext("- Creative Mode: ") << creative << "\n";
4650 if (!simple_singleplayer_mode) {
4651 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4652 os << strgettext("- PvP: ") << pvp << "\n"
4653 << strgettext("- Public: ") << announced << "\n";
4654 std::string server_name = g_settings->get("server_name");
4655 str_formspec_escape(server_name);
4656 if (announced == on && server_name != "")
4657 os << strgettext("- Server Name: ") << server_name;
4664 /* Note: FormspecFormSource and LocalFormspecHandler *
4665 * are deleted by guiFormSpecMenu */
4666 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4667 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4669 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
4670 current_formspec->setFocus("btn_continue");
4671 current_formspec->doPause = true;
4674 /****************************************************************************/
4675 /****************************************************************************
4676 extern function for launching the game
4677 ****************************************************************************/
4678 /****************************************************************************/
4680 void the_game(bool *kill,
4682 InputHandler *input,
4683 const std::string &map_dir,
4684 const std::string &playername,
4685 const std::string &password,
4686 const std::string &address, // If empty local server is created
4689 std::string &error_message,
4690 ChatBackend &chat_backend,
4691 bool *reconnect_requested,
4692 const SubgameSpec &gamespec, // Used for local game
4693 bool simple_singleplayer_mode)
4697 /* Make a copy of the server address because if a local singleplayer server
4698 * is created then this is updated and we don't want to change the value
4699 * passed to us by the calling function
4701 std::string server_address = address;
4705 if (game.startup(kill, random_input, input, map_dir,
4706 playername, password, &server_address, port, error_message,
4707 reconnect_requested, &chat_backend, gamespec,
4708 simple_singleplayer_mode)) {
4713 } catch (SerializationError &e) {
4714 error_message = std::string("A serialization error occurred:\n")
4715 + e.what() + "\n\nThe server is probably "
4716 " running a different version of " PROJECT_NAME_C ".";
4717 errorstream << error_message << std::endl;
4718 } catch (ServerError &e) {
4719 error_message = e.what();
4720 errorstream << "ServerError: " << error_message << std::endl;
4721 } catch (ModError &e) {
4722 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4723 errorstream << "ModError: " << error_message << std::endl;