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 = L"";
980 while (client.getChatMessage(message)) {
981 chat_backend.addUnparsedMessage(message);
984 // Remove old messages
985 chat_backend.step(dtime);
987 // Display all messages in a static text element
988 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
989 EnrichedString recent_chat = chat_backend.getRecentChat();
990 unsigned int line_height = g_fontengine->getLineHeight();
992 setStaticText(guitext_chat, recent_chat);
994 // Update gui element size and position
998 chat_y += 3 * line_height;
1000 // first pass to calculate height of text to be set
1001 const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
1002 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
1003 window_size.X - 20);
1004 core::rect<s32> rect(10, chat_y, width, chat_y + window_size.Y);
1005 guitext_chat->setRelativePosition(rect);
1007 //now use real height of text and adjust rect according to this size
1008 rect = core::rect<s32>(10, chat_y, width,
1009 chat_y + guitext_chat->getTextHeight());
1012 guitext_chat->setRelativePosition(rect);
1013 // Don't show chat if disabled or empty or profiler is enabled
1014 guitext_chat->setVisible(
1015 show_chat && recent_chat_count != 0 && !show_profiler);
1019 /****************************************************************************
1020 Fast key cache for main game loop
1021 ****************************************************************************/
1023 /* This is faster than using getKeySetting with the tradeoff that functions
1024 * using it must make sure that it's initialised before using it and there is
1025 * no error handling (for example bounds checking). This is really intended for
1026 * use only in the main running loop of the client (the_game()) where the faster
1027 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1028 * (e.g. formspecs) should continue using getKeySetting().
1036 populate_nonchanging();
1041 // Keys that are not settings dependent
1042 void populate_nonchanging();
1044 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1045 InputHandler *handler;
1048 void KeyCache::populate_nonchanging()
1050 key[KeyType::ESC] = EscapeKey;
1053 void KeyCache::populate()
1055 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1056 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1057 key[KeyType::LEFT] = getKeySetting("keymap_left");
1058 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1059 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1060 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1061 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1063 key[KeyType::AUTOFORWARD] = getKeySetting("keymap_autoforward");
1065 key[KeyType::DROP] = getKeySetting("keymap_drop");
1066 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1067 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1068 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1069 key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
1070 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1071 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1072 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1073 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1074 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1075 key[KeyType::HOTBAR_PREV] = getKeySetting("keymap_hotbar_previous");
1076 key[KeyType::HOTBAR_NEXT] = getKeySetting("keymap_hotbar_next");
1077 key[KeyType::MUTE] = getKeySetting("keymap_mute");
1078 key[KeyType::INC_VOLUME] = getKeySetting("keymap_increase_volume");
1079 key[KeyType::DEC_VOLUME] = getKeySetting("keymap_decrease_volume");
1080 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1081 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1082 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1083 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1084 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1085 = getKeySetting("keymap_toggle_force_fog_off");
1086 key[KeyType::TOGGLE_UPDATE_CAMERA]
1087 = getKeySetting("keymap_toggle_update_camera");
1088 key[KeyType::TOGGLE_DEBUG]
1089 = getKeySetting("keymap_toggle_debug");
1090 key[KeyType::TOGGLE_PROFILER]
1091 = getKeySetting("keymap_toggle_profiler");
1092 key[KeyType::CAMERA_MODE]
1093 = getKeySetting("keymap_camera_mode");
1094 key[KeyType::INCREASE_VIEWING_RANGE]
1095 = getKeySetting("keymap_increase_viewing_range_min");
1096 key[KeyType::DECREASE_VIEWING_RANGE]
1097 = getKeySetting("keymap_decrease_viewing_range_min");
1098 key[KeyType::RANGESELECT]
1099 = getKeySetting("keymap_rangeselect");
1100 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1102 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1103 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1104 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1105 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1107 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1110 // First clear all keys, then re-add the ones we listen for
1111 handler->dontListenForKeys();
1112 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1113 handler->listenForKey(key[i]);
1115 handler->listenForKey(EscapeKey);
1116 handler->listenForKey(CancelKey);
1117 for (size_t i = 0; i < 10; i++) {
1118 handler->listenForKey(NumberKey[i]);
1124 /****************************************************************************
1126 ****************************************************************************/
1128 const float object_hit_delay = 0.2;
1131 u32 last_time, busy_time, sleep_time;
1135 /* The reason the following structs are not anonymous structs within the
1136 * class is that they are not used by the majority of member functions and
1137 * many functions that do require objects of thse types do not modify them
1138 * (so they can be passed as a const qualified parameter)
1140 struct CameraOrientation {
1141 f32 camera_yaw; // "right/left"
1142 f32 camera_pitch; // "up/down"
1145 struct GameRunData {
1148 PointedThing pointed_old;
1153 bool update_wielded_item_trigger;
1154 bool reset_jump_timer;
1155 float nodig_delay_timer;
1157 float dig_time_complete;
1158 float repeat_rightclick_timer;
1159 float object_hit_delay_timer;
1160 float time_from_last_punch;
1161 ClientActiveObject *selected_object;
1165 float update_draw_list_timer;
1166 float statustext_time;
1170 v3f update_draw_list_last_cam_dir;
1172 u32 profiler_current_page;
1173 u32 profiler_max_page; // Number of pages
1176 float time_of_day_smooth;
1180 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1186 Jitter dtime_jitter, busy_time_jitter;
1189 /****************************************************************************
1191 ****************************************************************************/
1193 /* This is not intended to be a public class. If a public class becomes
1194 * desirable then it may be better to create another 'wrapper' class that
1195 * hides most of the stuff in this class (nothing in this class is required
1196 * by any other file) but exposes the public methods/data only.
1203 bool startup(bool *kill,
1205 InputHandler *input,
1206 const std::string &map_dir,
1207 const std::string &playername,
1208 const std::string &password,
1209 // If address is "", local server is used and address is updated
1210 std::string *address,
1212 std::string &error_message,
1214 ChatBackend *chat_backend,
1215 const SubgameSpec &gamespec, // Used for local game
1216 bool simple_singleplayer_mode);
1223 void extendedResourceCleanup();
1225 // Basic initialisation
1226 bool init(const std::string &map_dir, std::string *address,
1228 const SubgameSpec &gamespec);
1230 bool createSingleplayerServer(const std::string &map_dir,
1231 const SubgameSpec &gamespec, u16 port, std::string *address);
1234 bool createClient(const std::string &playername,
1235 const std::string &password, std::string *address, u16 port);
1238 // Client connection
1239 bool connectToServer(const std::string &playername,
1240 const std::string &password, std::string *address, u16 port,
1241 bool *connect_ok, bool *aborted);
1242 bool getServerContent(bool *aborted);
1246 void updateInteractTimers(f32 dtime);
1247 bool checkConnection();
1248 bool handleCallbacks();
1249 void processQueues();
1250 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1251 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1252 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1255 void processUserInput(f32 dtime);
1256 void processKeyInput();
1257 void processItemSelection(u16 *new_playeritem);
1259 void dropSelectedItem();
1260 void openInventory();
1261 void openConsole(float scale, const wchar_t *line=NULL);
1262 void toggleFreeMove();
1263 void toggleFreeMoveAlt();
1265 void toggleNoClip();
1266 void toggleCinematic();
1267 void toggleAutoforward();
1271 void toggleMinimap(bool shift_pressed);
1274 void toggleUpdateCamera();
1275 void toggleProfiler();
1277 void increaseViewRange();
1278 void decreaseViewRange();
1279 void toggleFullViewRange();
1281 void updateCameraDirection(CameraOrientation *cam, float dtime);
1282 void updateCameraOrientation(CameraOrientation *cam, float dtime);
1283 void updatePlayerControl(const CameraOrientation &cam);
1284 void step(f32 *dtime);
1285 void processClientEvents(CameraOrientation *cam);
1286 void updateCamera(u32 busy_time, f32 dtime);
1287 void updateSound(f32 dtime);
1288 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
1290 * Returns the object or node the player is pointing at.
1291 * Also updates the selected thing in the Hud.
1293 * @param[in] shootline the shootline, starting from
1294 * the camera position. This also gives the maximal distance
1296 * @param[in] liquids_pointable if false, liquids are ignored
1297 * @param[in] look_for_object if false, objects are ignored
1298 * @param[in] camera_offset offset of the camera
1299 * @param[out] selected_object the selected object or
1302 PointedThing updatePointedThing(
1303 const core::line3d<f32> &shootline, bool liquids_pointable,
1304 bool look_for_object, const v3s16 &camera_offset);
1305 void handlePointingAtNothing(const ItemStack &playerItem);
1306 void handlePointingAtNode(const PointedThing &pointed,
1307 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
1308 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1309 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
1310 const v3f &player_position, bool show_debug);
1311 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
1312 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1313 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
1314 const CameraOrientation &cam);
1315 void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
1316 void updateProfilerGraphs(ProfilerGraph *graph);
1319 void limitFps(FpsControl *fps_timings, f32 *dtime);
1321 void showOverlayMessage(const char *msg, float dtime, int percent,
1322 bool draw_clouds = true);
1324 static void settingChangedCallback(const std::string &setting_name, void *data);
1325 void readSettings();
1327 inline bool getLeftClicked()
1329 return input->getLeftClicked() ||
1330 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1332 inline bool getRightClicked()
1334 return input->getRightClicked() ||
1335 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1337 inline bool isLeftPressed()
1339 return input->getLeftState() ||
1340 input->joystick.isKeyDown(KeyType::MOUSE_L);
1342 inline bool isRightPressed()
1344 return input->getRightState() ||
1345 input->joystick.isKeyDown(KeyType::MOUSE_R);
1347 inline bool getLeftReleased()
1349 return input->getLeftReleased() ||
1350 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1353 inline bool isKeyDown(GameKeyType k)
1355 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1357 inline bool wasKeyDown(GameKeyType k)
1359 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1363 void handleAndroidChatInput();
1367 void showPauseMenu();
1369 InputHandler *input;
1374 IWritableTextureSource *texture_src;
1375 IWritableShaderSource *shader_src;
1377 // When created, these will be filled with data received from the server
1378 IWritableItemDefManager *itemdef_manager;
1379 IWritableNodeDefManager *nodedef_manager;
1381 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1382 ISoundManager *sound;
1383 bool sound_is_dummy;
1384 SoundMaker *soundmaker;
1386 ChatBackend *chat_backend;
1388 GUIFormSpecMenu *current_formspec;
1389 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1390 std::string cur_formname;
1392 EventManager *eventmgr;
1393 QuicktuneShortcutter *quicktune;
1395 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1396 MapDrawControl *draw_control;
1398 Clouds *clouds; // Free using ->Drop()
1399 Sky *sky; // Free using ->Drop()
1400 Inventory *local_inventory;
1404 GameRunData runData;
1408 This class does take ownership/responsibily for cleaning up etc of any of
1409 these items (e.g. device)
1411 IrrlichtDevice *device;
1412 video::IVideoDriver *driver;
1413 scene::ISceneManager *smgr;
1415 std::string *error_message;
1416 bool *reconnect_requested;
1417 scene::ISceneNode *skybox;
1420 bool simple_singleplayer_mode;
1423 /* Pre-calculated values
1425 int crack_animation_length;
1429 gui::IGUIStaticText *guitext; // First line of debug text
1430 gui::IGUIStaticText *guitext2; // Second line of debug text
1431 gui::IGUIStaticText *guitext3; // Third 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 // Third line of debug text
2005 guitext3 = addStaticText(guienv,
2007 core::rect<s32>(0, 0, 0, 0),
2008 false, false, guiroot);
2010 // At the middle of the screen
2011 // Object infos are shown in this
2012 guitext_info = addStaticText(guienv,
2014 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2015 false, true, guiroot);
2017 // Status text (displays info when showing and hiding GUI stuff, etc.)
2018 guitext_status = addStaticText(guienv,
2020 core::rect<s32>(0, 0, 0, 0),
2021 false, false, guiroot);
2022 guitext_status->setVisible(false);
2025 guitext_chat = addStaticText(
2028 core::rect<s32>(0, 0, 0, 0),
2029 //false, false); // Disable word wrap as of now
2030 false, true, guiroot);
2032 // Remove stale "recent" chat messages from previous connections
2033 chat_backend->clearRecentChat();
2035 // Chat backend and console
2036 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2037 -1, chat_backend, client, &g_menumgr);
2038 if (!gui_chat_console) {
2039 *error_message = "Could not allocate memory for chat console";
2040 errorstream << *error_message << std::endl;
2044 // Profiler text (size is updated when text is updated)
2045 guitext_profiler = addStaticText(guienv,
2047 core::rect<s32>(0, 0, 0, 0),
2048 false, false, guiroot);
2049 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2050 guitext_profiler->setVisible(false);
2051 guitext_profiler->setWordWrap(true);
2053 #ifdef HAVE_TOUCHSCREENGUI
2055 if (g_touchscreengui)
2056 g_touchscreengui->init(texture_src);
2063 bool Game::connectToServer(const std::string &playername,
2064 const std::string &password, std::string *address, u16 port,
2065 bool *connect_ok, bool *aborted)
2067 *connect_ok = false; // Let's not be overly optimistic
2069 bool local_server_mode = false;
2071 showOverlayMessage("Resolving address...", 0, 15);
2073 Address connect_address(0, 0, 0, 0, port);
2076 connect_address.Resolve(address->c_str());
2078 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2079 //connect_address.Resolve("localhost");
2080 if (connect_address.isIPv6()) {
2081 IPv6AddressBytes addr_bytes;
2082 addr_bytes.bytes[15] = 1;
2083 connect_address.setAddress(&addr_bytes);
2085 connect_address.setAddress(127, 0, 0, 1);
2087 local_server_mode = true;
2089 } catch (ResolveError &e) {
2090 *error_message = std::string("Couldn't resolve address: ") + e.what();
2091 errorstream << *error_message << std::endl;
2095 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2096 *error_message = "Unable to connect to " +
2097 connect_address.serializeString() +
2098 " because IPv6 is disabled";
2099 errorstream << *error_message << std::endl;
2103 client = new Client(playername.c_str(), password, *address,
2104 *draw_control, texture_src, shader_src,
2105 itemdef_manager, nodedef_manager, sound, eventmgr,
2106 connect_address.isIPv6(), &flags);
2111 infostream << "Connecting to server at ";
2112 connect_address.print(&infostream);
2113 infostream << std::endl;
2115 client->connect(connect_address,
2116 simple_singleplayer_mode || local_server_mode);
2119 Wait for server to accept connection
2125 FpsControl fps_control = { 0 };
2127 f32 wait_time = 0; // in seconds
2129 fps_control.last_time = RenderingEngine::get_timer_time();
2134 while (RenderingEngine::run()) {
2136 limitFps(&fps_control, &dtime);
2138 // Update client and server
2139 client->step(dtime);
2142 server->step(dtime);
2145 if (client->getState() == LC_Init) {
2151 if (client->accessDenied()) {
2152 *error_message = "Access denied. Reason: "
2153 + client->accessDeniedReason();
2154 *reconnect_requested = client->reconnectRequested();
2155 errorstream << *error_message << std::endl;
2159 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2161 infostream << "Connect aborted [Escape]" << std::endl;
2166 // Only time out if we aren't waiting for the server we started
2167 if ((*address != "") && (wait_time > 10)) {
2168 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2169 // If no pre v25 init was sent, and no answer was received,
2170 // but the low level connection could be established
2171 // (meaning that we have a peer id), then we probably wanted
2172 // to connect to a legacy server. In this case, tell the user
2173 // to enable the option to be able to connect.
2174 if (!sent_old_init &&
2175 (client->getProtoVersion() == 0) &&
2176 client->connectedToServer()) {
2177 *error_message = "Connection failure: init packet not "
2178 "recognized by server.\n"
2179 "Most likely the server uses an old protocol version (<v25).\n"
2180 "Please ask the server owner to update to 0.4.13 or later.\n"
2181 "To still connect to the server in the meantime,\n"
2182 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2183 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2184 "entry in the advanced settings menu.";
2186 *error_message = "Connection timed out.";
2188 errorstream << *error_message << std::endl;
2193 showOverlayMessage("Connecting to server...", dtime, 20);
2195 } catch (con::PeerNotFoundException &e) {
2196 // TODO: Should something be done here? At least an info/error
2204 bool Game::getServerContent(bool *aborted)
2208 FpsControl fps_control = { 0 };
2209 f32 dtime; // in seconds
2211 fps_control.last_time = RenderingEngine::get_timer_time();
2213 while (RenderingEngine::run()) {
2215 limitFps(&fps_control, &dtime);
2217 // Update client and server
2218 client->step(dtime);
2221 server->step(dtime);
2224 if (client->mediaReceived() && client->itemdefReceived() &&
2225 client->nodedefReceived()) {
2230 if (!checkConnection())
2233 if (client->getState() < LC_Init) {
2234 *error_message = "Client disconnected";
2235 errorstream << *error_message << std::endl;
2239 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2241 infostream << "Connect aborted [Escape]" << std::endl;
2248 if (!client->itemdefReceived()) {
2249 const wchar_t *text = wgettext("Item definitions...");
2251 RenderingEngine::draw_load_screen(text, guienv, texture_src,
2254 } else if (!client->nodedefReceived()) {
2255 const wchar_t *text = wgettext("Node definitions...");
2257 RenderingEngine::draw_load_screen(text, guienv, texture_src,
2261 std::stringstream message;
2262 std::fixed(message);
2263 message.precision(0);
2264 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2265 message.precision(2);
2267 if ((USE_CURL == 0) ||
2268 (!g_settings->getBool("enable_remote_media_server"))) {
2269 float cur = client->getCurRate();
2270 std::string cur_unit = gettext("KiB/s");
2274 cur_unit = gettext("MiB/s");
2277 message << " (" << cur << ' ' << cur_unit << ")";
2280 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2281 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
2282 texture_src, dtime, progress);
2290 /****************************************************************************/
2291 /****************************************************************************
2293 ****************************************************************************/
2294 /****************************************************************************/
2296 inline void Game::updateInteractTimers(f32 dtime)
2298 if (runData.nodig_delay_timer >= 0)
2299 runData.nodig_delay_timer -= dtime;
2301 if (runData.object_hit_delay_timer >= 0)
2302 runData.object_hit_delay_timer -= dtime;
2304 runData.time_from_last_punch += dtime;
2308 /* returns false if game should exit, otherwise true
2310 inline bool Game::checkConnection()
2312 if (client->accessDenied()) {
2313 *error_message = "Access denied. Reason: "
2314 + client->accessDeniedReason();
2315 *reconnect_requested = client->reconnectRequested();
2316 errorstream << *error_message << std::endl;
2324 /* returns false if game should exit, otherwise true
2326 inline bool Game::handleCallbacks()
2328 if (g_gamecallback->disconnect_requested) {
2329 g_gamecallback->disconnect_requested = false;
2333 if (g_gamecallback->changepassword_requested) {
2334 (new GUIPasswordChange(guienv, guiroot, -1,
2335 &g_menumgr, client))->drop();
2336 g_gamecallback->changepassword_requested = false;
2339 if (g_gamecallback->changevolume_requested) {
2340 (new GUIVolumeChange(guienv, guiroot, -1,
2341 &g_menumgr))->drop();
2342 g_gamecallback->changevolume_requested = false;
2345 if (g_gamecallback->keyconfig_requested) {
2346 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2347 &g_menumgr))->drop();
2348 g_gamecallback->keyconfig_requested = false;
2351 if (g_gamecallback->keyconfig_changed) {
2352 keycache.populate(); // update the cache with new settings
2353 g_gamecallback->keyconfig_changed = false;
2360 void Game::processQueues()
2362 texture_src->processQueue();
2363 itemdef_manager->processQueue(client);
2364 shader_src->processQueue();
2368 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2370 float profiler_print_interval =
2371 g_settings->getFloat("profiler_print_interval");
2372 bool print_to_log = true;
2374 if (profiler_print_interval == 0) {
2375 print_to_log = false;
2376 profiler_print_interval = 5;
2379 if (profiler_interval.step(dtime, profiler_print_interval)) {
2381 infostream << "Profiler:" << std::endl;
2382 g_profiler->print(infostream);
2385 update_profiler_gui(guitext_profiler, g_fontengine,
2386 runData.profiler_current_page, runData.profiler_max_page,
2387 driver->getScreenSize().Height);
2389 g_profiler->clear();
2392 addProfilerGraphs(stats, draw_times, dtime);
2396 void Game::addProfilerGraphs(const RunStats &stats,
2397 const FpsControl &draw_times, f32 dtime)
2399 g_profiler->graphAdd("mainloop_other",
2400 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2402 if (draw_times.sleep_time != 0)
2403 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2404 g_profiler->graphAdd("mainloop_dtime", dtime);
2406 g_profiler->add("Elapsed time", dtime);
2407 g_profiler->avg("FPS", 1. / dtime);
2411 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2418 /* Time average and jitter calculation
2420 jp = &stats->dtime_jitter;
2421 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2423 jitter = dtime - jp->avg;
2425 if (jitter > jp->max)
2428 jp->counter += dtime;
2430 if (jp->counter > 0.0) {
2432 jp->max_sample = jp->max;
2433 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2437 /* Busytime average and jitter calculation
2439 jp = &stats->busy_time_jitter;
2440 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2442 jitter = draw_times.busy_time - jp->avg;
2444 if (jitter > jp->max)
2446 if (jitter < jp->min)
2449 jp->counter += dtime;
2451 if (jp->counter > 0.0) {
2453 jp->max_sample = jp->max;
2454 jp->min_sample = jp->min;
2462 /****************************************************************************
2464 ****************************************************************************/
2466 void Game::processUserInput(f32 dtime)
2468 // Reset input if window not active or some menu is active
2469 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
2471 #ifdef HAVE_TOUCHSCREENGUI
2472 g_touchscreengui->hide();
2475 #ifdef HAVE_TOUCHSCREENGUI
2476 else if (g_touchscreengui) {
2477 /* on touchscreengui step may generate own input events which ain't
2478 * what we want in case we just did clear them */
2479 g_touchscreengui->step(dtime);
2483 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2484 gui_chat_console->closeConsoleAtOnce();
2487 // Input handler step() (used by the random input generator)
2491 if (current_formspec != NULL)
2492 current_formspec->getAndroidUIInput();
2494 handleAndroidChatInput();
2497 // Increase timer for double tap of "keymap_jump"
2498 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2499 runData.jump_timer += dtime;
2502 processItemSelection(&runData.new_playeritem);
2506 void Game::processKeyInput()
2508 if (wasKeyDown(KeyType::DROP)) {
2510 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
2511 toggleAutoforward();
2512 } else if (wasKeyDown(KeyType::INVENTORY)) {
2514 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2515 if (!gui_chat_console->isOpenInhibited()) {
2518 } else if (wasKeyDown(KeyType::CHAT)) {
2519 openConsole(0.2, L"");
2520 } else if (wasKeyDown(KeyType::CMD)) {
2521 openConsole(0.2, L"/");
2522 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2523 openConsole(0.2, L".");
2524 } else if (wasKeyDown(KeyType::CONSOLE)) {
2525 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2526 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2528 } else if (wasKeyDown(KeyType::JUMP)) {
2529 toggleFreeMoveAlt();
2530 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2532 } else if (wasKeyDown(KeyType::NOCLIP)) {
2534 } else if (wasKeyDown(KeyType::MUTE)) {
2535 float volume = g_settings->getFloat("sound_volume");
2536 if (volume < 0.001f) {
2537 g_settings->setFloat("sound_volume", 1.0f);
2538 m_statustext = narrow_to_wide(gettext("Volume changed to 100%"));
2540 g_settings->setFloat("sound_volume", 0.0f);
2541 m_statustext = narrow_to_wide(gettext("Volume changed to 0%"));
2543 runData.statustext_time = 0;
2544 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
2545 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
2547 g_settings->setFloat("sound_volume", new_volume);
2548 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2549 m_statustext = narrow_to_wide(buf);
2550 runData.statustext_time = 0;
2551 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
2552 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
2554 g_settings->setFloat("sound_volume", new_volume);
2555 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2556 m_statustext = narrow_to_wide(buf);
2557 runData.statustext_time = 0;
2558 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2560 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2561 client->makeScreenshot();
2562 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2564 } else if (wasKeyDown(KeyType::MINIMAP)) {
2565 toggleMinimap(isKeyDown(KeyType::SNEAK));
2566 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2568 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2570 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2571 toggleUpdateCamera();
2572 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2574 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2576 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2577 increaseViewRange();
2578 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2579 decreaseViewRange();
2580 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2581 toggleFullViewRange();
2582 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2584 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2586 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2588 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2590 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2591 // Print debug stacks
2592 dstream << "-----------------------------------------"
2594 dstream << "Printing debug stacks:" << std::endl;
2595 dstream << "-----------------------------------------"
2597 debug_stacks_print();
2600 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2601 runData.reset_jump_timer = false;
2602 runData.jump_timer = 0.0f;
2605 if (quicktune->hasMessage()) {
2606 m_statustext = utf8_to_wide(quicktune->getMessage());
2607 runData.statustext_time = 0.0f;
2611 void Game::processItemSelection(u16 *new_playeritem)
2613 LocalPlayer *player = client->getEnv().getLocalPlayer();
2615 /* Item selection using mouse wheel
2617 *new_playeritem = client->getPlayerItem();
2619 s32 wheel = input->getMouseWheel();
2620 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2621 player->hud_hotbar_itemcount - 1);
2625 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2626 wasKeyDown(KeyType::HOTBAR_NEXT)) {
2630 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2631 wasKeyDown(KeyType::HOTBAR_PREV)) {
2636 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2638 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2641 /* Item selection using keyboard
2643 for (u16 i = 0; i < 10; i++) {
2644 static const KeyPress *item_keys[10] = {
2645 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2646 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2647 NumberKey + 9, NumberKey + 0,
2650 if (input->wasKeyDown(*item_keys[i])) {
2651 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2652 *new_playeritem = i;
2653 infostream << "Selected item: " << new_playeritem << std::endl;
2661 void Game::dropSelectedItem()
2663 IDropAction *a = new IDropAction();
2665 a->from_inv.setCurrentPlayer();
2666 a->from_list = "main";
2667 a->from_i = client->getPlayerItem();
2668 client->inventoryAction(a);
2672 void Game::openInventory()
2675 * Don't permit to open inventory is CAO or player doesn't exists.
2676 * This prevent showing an empty inventory at player load
2679 LocalPlayer *player = client->getEnv().getLocalPlayer();
2680 if (!player || !player->getCAO())
2683 infostream << "the_game: " << "Launching inventory" << std::endl;
2685 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2686 TextDest *txt_dst = new TextDestPlayerInventory(client);
2688 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
2691 InventoryLocation inventoryloc;
2692 inventoryloc.setCurrentPlayer();
2693 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2697 void Game::openConsole(float scale, const wchar_t *line)
2699 assert(scale > 0.0f && scale <= 1.0f);
2702 porting::showInputDialog(gettext("ok"), "", "", 2);
2703 m_android_chat_open = true;
2705 if (gui_chat_console->isOpenInhibited())
2707 gui_chat_console->openConsole(scale);
2709 gui_chat_console->setCloseOnEnter(true);
2710 gui_chat_console->replaceAndAddToHistory(line);
2716 void Game::handleAndroidChatInput()
2718 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2719 std::string text = porting::getInputDialogValue();
2720 client->typeChatMessage(utf8_to_wide(text));
2726 void Game::toggleFreeMove()
2728 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2730 bool free_move = !g_settings->getBool("free_move");
2731 g_settings->set("free_move", bool_to_cstr(free_move));
2733 runData.statustext_time = 0;
2734 m_statustext = msg[free_move];
2735 if (free_move && !client->checkPrivilege("fly"))
2736 m_statustext += L" (note: no 'fly' privilege)";
2740 void Game::toggleFreeMoveAlt()
2742 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2745 runData.reset_jump_timer = true;
2749 void Game::toggleFast()
2751 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2752 bool fast_move = !g_settings->getBool("fast_move");
2753 g_settings->set("fast_move", bool_to_cstr(fast_move));
2755 runData.statustext_time = 0;
2756 m_statustext = msg[fast_move];
2758 bool has_fast_privs = client->checkPrivilege("fast");
2760 if (fast_move && !has_fast_privs)
2761 m_statustext += L" (note: no 'fast' privilege)";
2764 m_cache_hold_aux1 = fast_move && has_fast_privs;
2769 void Game::toggleNoClip()
2771 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2772 bool noclip = !g_settings->getBool("noclip");
2773 g_settings->set("noclip", bool_to_cstr(noclip));
2775 runData.statustext_time = 0;
2776 m_statustext = msg[noclip];
2778 if (noclip && !client->checkPrivilege("noclip"))
2779 m_statustext += L" (note: no 'noclip' privilege)";
2782 void Game::toggleCinematic()
2784 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2785 bool cinematic = !g_settings->getBool("cinematic");
2786 g_settings->set("cinematic", bool_to_cstr(cinematic));
2788 runData.statustext_time = 0;
2789 m_statustext = msg[cinematic];
2792 // Autoforward by toggling continuous forward.
2793 void Game::toggleAutoforward()
2795 static const wchar_t *msg[] = { L"autoforward disabled", L"autoforward enabled" };
2796 bool autoforward_enabled = !g_settings->getBool("continuous_forward");
2797 g_settings->set("continuous_forward", bool_to_cstr(autoforward_enabled));
2799 runData.statustext_time = 0;
2800 m_statustext = msg[autoforward_enabled ? 1 : 0];
2803 void Game::toggleChat()
2805 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2807 flags.show_chat = !flags.show_chat;
2808 runData.statustext_time = 0;
2809 m_statustext = msg[flags.show_chat];
2813 void Game::toggleHud()
2815 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2817 flags.show_hud = !flags.show_hud;
2818 runData.statustext_time = 0;
2819 m_statustext = msg[flags.show_hud];
2822 void Game::toggleMinimap(bool shift_pressed)
2824 if (!mapper || !flags.show_hud || !g_settings->getBool("enable_minimap"))
2827 if (shift_pressed) {
2828 mapper->toggleMinimapShape();
2832 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2834 MinimapMode mode = MINIMAP_MODE_OFF;
2835 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2836 mode = mapper->getMinimapMode();
2837 mode = (MinimapMode)((int)mode + 1);
2840 flags.show_minimap = true;
2842 case MINIMAP_MODE_SURFACEx1:
2843 m_statustext = L"Minimap in surface mode, Zoom x1";
2845 case MINIMAP_MODE_SURFACEx2:
2846 m_statustext = L"Minimap in surface mode, Zoom x2";
2848 case MINIMAP_MODE_SURFACEx4:
2849 m_statustext = L"Minimap in surface mode, Zoom x4";
2851 case MINIMAP_MODE_RADARx1:
2852 m_statustext = L"Minimap in radar mode, Zoom x1";
2854 case MINIMAP_MODE_RADARx2:
2855 m_statustext = L"Minimap in radar mode, Zoom x2";
2857 case MINIMAP_MODE_RADARx4:
2858 m_statustext = L"Minimap in radar mode, Zoom x4";
2861 mode = MINIMAP_MODE_OFF;
2862 flags.show_minimap = false;
2863 m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2864 L"Minimap hidden" : L"Minimap disabled by server";
2867 runData.statustext_time = 0;
2868 mapper->setMinimapMode(mode);
2871 void Game::toggleFog()
2873 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2875 flags.force_fog_off = !flags.force_fog_off;
2876 runData.statustext_time = 0;
2877 m_statustext = msg[flags.force_fog_off];
2881 void Game::toggleDebug()
2883 // Initial / 4x toggle: Chat only
2884 // 1x toggle: Debug text with chat
2885 // 2x toggle: Debug text with profiler graph
2886 // 3x toggle: Debug text and wireframe
2887 if (!flags.show_debug) {
2888 flags.show_debug = true;
2889 flags.show_profiler_graph = false;
2890 draw_control->show_wireframe = false;
2891 m_statustext = L"Debug info shown";
2892 } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2893 flags.show_profiler_graph = true;
2894 m_statustext = L"Profiler graph shown";
2895 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2896 flags.show_profiler_graph = false;
2897 draw_control->show_wireframe = true;
2898 m_statustext = L"Wireframe shown";
2900 flags.show_debug = false;
2901 flags.show_profiler_graph = false;
2902 draw_control->show_wireframe = false;
2903 if (client->checkPrivilege("debug")) {
2904 m_statustext = L"Debug info, profiler graph, and wireframe hidden";
2906 m_statustext = L"Debug info and profiler graph hidden";
2909 runData.statustext_time = 0;
2913 void Game::toggleUpdateCamera()
2915 static const wchar_t *msg[] = {
2916 L"Camera update enabled",
2917 L"Camera update disabled"
2920 flags.disable_camera_update = !flags.disable_camera_update;
2921 runData.statustext_time = 0;
2922 m_statustext = msg[flags.disable_camera_update];
2926 void Game::toggleProfiler()
2928 runData.profiler_current_page =
2929 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2931 // FIXME: This updates the profiler with incomplete values
2932 update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2933 runData.profiler_max_page, driver->getScreenSize().Height);
2935 if (runData.profiler_current_page != 0) {
2936 std::wstringstream sstr;
2937 sstr << "Profiler shown (page " << runData.profiler_current_page
2938 << " of " << runData.profiler_max_page << ")";
2939 m_statustext = sstr.str();
2941 m_statustext = L"Profiler hidden";
2943 runData.statustext_time = 0;
2947 void Game::increaseViewRange()
2949 s16 range = g_settings->getS16("viewing_range");
2950 s16 range_new = range + 10;
2952 if (range_new > 4000) {
2954 m_statustext = utf8_to_wide("Viewing range is at maximum: "
2957 m_statustext = utf8_to_wide("Viewing range changed to "
2960 g_settings->set("viewing_range", itos(range_new));
2961 runData.statustext_time = 0;
2965 void Game::decreaseViewRange()
2967 s16 range = g_settings->getS16("viewing_range");
2968 s16 range_new = range - 10;
2970 if (range_new < 20) {
2972 m_statustext = utf8_to_wide("Viewing range is at minimum: "
2975 m_statustext = utf8_to_wide("Viewing range changed to "
2978 g_settings->set("viewing_range", itos(range_new));
2979 runData.statustext_time = 0;
2983 void Game::toggleFullViewRange()
2985 static const wchar_t *msg[] = {
2986 L"Disabled full viewing range",
2987 L"Enabled full viewing range"
2990 draw_control->range_all = !draw_control->range_all;
2991 infostream << msg[draw_control->range_all] << std::endl;
2992 m_statustext = msg[draw_control->range_all];
2993 runData.statustext_time = 0;
2997 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2999 if ((device->isWindowActive() && device->isWindowFocused()
3000 && !isMenuActive()) || random_input) {
3003 if (!random_input) {
3004 // Mac OSX gets upset if this is set every frame
3005 if (device->getCursorControl()->isVisible())
3006 device->getCursorControl()->setVisible(false);
3010 if (m_first_loop_after_window_activation)
3011 m_first_loop_after_window_activation = false;
3013 updateCameraOrientation(cam, dtime);
3015 input->setMousePos((driver->getScreenSize().Width / 2),
3016 (driver->getScreenSize().Height / 2));
3020 // Mac OSX gets upset if this is set every frame
3021 if (!device->getCursorControl()->isVisible())
3022 device->getCursorControl()->setVisible(true);
3025 m_first_loop_after_window_activation = true;
3030 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
3032 #ifdef HAVE_TOUCHSCREENGUI
3033 if (g_touchscreengui) {
3034 cam->camera_yaw += g_touchscreengui->getYawChange();
3035 cam->camera_pitch = g_touchscreengui->getPitch();
3039 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3040 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3042 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3046 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3047 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3049 #ifdef HAVE_TOUCHSCREENGUI
3053 if (m_cache_enable_joysticks) {
3054 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3055 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
3056 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
3059 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3063 void Game::updatePlayerControl(const CameraOrientation &cam)
3065 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3067 // DO NOT use the isKeyDown method for the forward, backward, left, right
3068 // buttons, as the code that uses the controls needs to be able to
3069 // distinguish between the two in order to know when to use joysticks.
3071 PlayerControl control(
3072 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3073 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3074 input->isKeyDown(keycache.key[KeyType::LEFT]),
3075 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3076 isKeyDown(KeyType::JUMP),
3077 isKeyDown(KeyType::SPECIAL1),
3078 isKeyDown(KeyType::SNEAK),
3079 isKeyDown(KeyType::ZOOM),
3084 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3085 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3089 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3090 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3091 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3092 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3093 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3094 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3095 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3096 ( (u32)(isLeftPressed() & 0x1) << 7) |
3097 ( (u32)(isRightPressed() & 0x1) << 8
3101 /* For Android, simulate holding down AUX1 (fast move) if the user has
3102 * the fast_move setting toggled on. If there is an aux1 key defined for
3103 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3106 if (m_cache_hold_aux1) {
3107 control.aux1 = control.aux1 ^ true;
3108 keypress_bits ^= ((u32)(1U << 5));
3112 client->setPlayerControl(control);
3113 LocalPlayer *player = client->getEnv().getLocalPlayer();
3114 player->keyPressed = keypress_bits;
3120 inline void Game::step(f32 *dtime)
3122 bool can_be_and_is_paused =
3123 (simple_singleplayer_mode && g_menumgr.pausesGame());
3125 if (can_be_and_is_paused) { // This is for a singleplayer server
3126 *dtime = 0; // No time passes
3128 if (server != NULL) {
3129 //TimeTaker timer("server->step(dtime)");
3130 server->step(*dtime);
3133 //TimeTaker timer("client.step(dtime)");
3134 client->step(*dtime);
3139 void Game::processClientEvents(CameraOrientation *cam)
3141 LocalPlayer *player = client->getEnv().getLocalPlayer();
3143 while (client->hasClientEvents()) {
3144 ClientEvent event = client->getClientEvent();
3146 switch (event.type) {
3147 case CE_PLAYER_DAMAGE:
3148 if (client->getHP() == 0)
3150 if (client->moddingEnabled()) {
3151 client->getScript()->on_damage_taken(event.player_damage.amount);
3154 runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3155 runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3157 player->hurt_tilt_timer = 1.5;
3158 player->hurt_tilt_strength =
3159 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3161 client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3164 case CE_PLAYER_FORCE_MOVE:
3165 cam->camera_yaw = event.player_force_move.yaw;
3166 cam->camera_pitch = event.player_force_move.pitch;
3169 case CE_DEATHSCREEN:
3170 // This should be enabled for death formspec in builtin
3171 client->getScript()->on_death();
3173 /* Handle visualization */
3174 runData.damage_flash = 0;
3175 player->hurt_tilt_timer = 0;
3176 player->hurt_tilt_strength = 0;
3179 case CE_SHOW_FORMSPEC:
3180 if (*(event.show_formspec.formspec) == "") {
3181 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3182 current_formspec->quitMenu();
3185 FormspecFormSource *fs_src =
3186 new FormspecFormSource(*(event.show_formspec.formspec));
3187 TextDestPlayerInventory *txt_dst =
3188 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3190 create_formspec_menu(¤t_formspec, client, &input->joystick,
3192 cur_formname = *(event.show_formspec.formname);
3195 delete event.show_formspec.formspec;
3196 delete event.show_formspec.formname;
3199 case CE_SHOW_LOCAL_FORMSPEC:
3201 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3202 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3203 create_formspec_menu(¤t_formspec, client, &input->joystick,
3206 delete event.show_formspec.formspec;
3207 delete event.show_formspec.formname;
3210 case CE_SPAWN_PARTICLE:
3211 case CE_ADD_PARTICLESPAWNER:
3212 case CE_DELETE_PARTICLESPAWNER:
3213 client->getParticleManager()->handleParticleEvent(&event, client, player);
3218 u32 id = event.hudadd.id;
3220 HudElement *e = player->getHud(id);
3223 delete event.hudadd.pos;
3224 delete event.hudadd.name;
3225 delete event.hudadd.scale;
3226 delete event.hudadd.text;
3227 delete event.hudadd.align;
3228 delete event.hudadd.offset;
3229 delete event.hudadd.world_pos;
3230 delete event.hudadd.size;
3235 e->type = (HudElementType)event.hudadd.type;
3236 e->pos = *event.hudadd.pos;
3237 e->name = *event.hudadd.name;
3238 e->scale = *event.hudadd.scale;
3239 e->text = *event.hudadd.text;
3240 e->number = event.hudadd.number;
3241 e->item = event.hudadd.item;
3242 e->dir = event.hudadd.dir;
3243 e->align = *event.hudadd.align;
3244 e->offset = *event.hudadd.offset;
3245 e->world_pos = *event.hudadd.world_pos;
3246 e->size = *event.hudadd.size;
3248 u32 new_id = player->addHud(e);
3249 //if this isn't true our huds aren't consistent
3250 sanity_check(new_id == id);
3253 delete event.hudadd.pos;
3254 delete event.hudadd.name;
3255 delete event.hudadd.scale;
3256 delete event.hudadd.text;
3257 delete event.hudadd.align;
3258 delete event.hudadd.offset;
3259 delete event.hudadd.world_pos;
3260 delete event.hudadd.size;
3265 HudElement *e = player->removeHud(event.hudrm.id);
3273 u32 id = event.hudchange.id;
3274 HudElement *e = player->getHud(id);
3277 delete event.hudchange.v3fdata;
3278 delete event.hudchange.v2fdata;
3279 delete event.hudchange.sdata;
3280 delete event.hudchange.v2s32data;
3284 switch (event.hudchange.stat) {
3286 e->pos = *event.hudchange.v2fdata;
3290 e->name = *event.hudchange.sdata;
3293 case HUD_STAT_SCALE:
3294 e->scale = *event.hudchange.v2fdata;
3298 e->text = *event.hudchange.sdata;
3301 case HUD_STAT_NUMBER:
3302 e->number = event.hudchange.data;
3306 e->item = event.hudchange.data;
3310 e->dir = event.hudchange.data;
3313 case HUD_STAT_ALIGN:
3314 e->align = *event.hudchange.v2fdata;
3317 case HUD_STAT_OFFSET:
3318 e->offset = *event.hudchange.v2fdata;
3321 case HUD_STAT_WORLD_POS:
3322 e->world_pos = *event.hudchange.v3fdata;
3326 e->size = *event.hudchange.v2s32data;
3331 delete event.hudchange.v3fdata;
3332 delete event.hudchange.v2fdata;
3333 delete event.hudchange.sdata;
3334 delete event.hudchange.v2s32data;
3338 sky->setVisible(false);
3339 // Whether clouds are visible in front of a custom skybox
3340 sky->setCloudsEnabled(event.set_sky.clouds);
3347 // Handle according to type
3348 if (*event.set_sky.type == "regular") {
3349 sky->setVisible(true);
3350 sky->setCloudsEnabled(true);
3351 } else if (*event.set_sky.type == "skybox" &&
3352 event.set_sky.params->size() == 6) {
3353 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3354 skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
3355 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3356 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3357 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3358 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3359 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3360 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3362 // Handle everything else as plain color
3364 if (*event.set_sky.type != "plain")
3365 infostream << "Unknown sky type: "
3366 << (*event.set_sky.type) << std::endl;
3368 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3371 delete event.set_sky.bgcolor;
3372 delete event.set_sky.type;
3373 delete event.set_sky.params;
3376 case CE_OVERRIDE_DAY_NIGHT_RATIO:
3377 client->getEnv().setDayNightRatioOverride(
3378 event.override_day_night_ratio.do_override,
3379 event.override_day_night_ratio.ratio_f * 1000);
3382 case CE_CLOUD_PARAMS:
3384 clouds->setDensity(event.cloud_params.density);
3385 clouds->setColorBright(video::SColor(event.cloud_params.color_bright));
3386 clouds->setColorAmbient(video::SColor(event.cloud_params.color_ambient));
3387 clouds->setHeight(event.cloud_params.height);
3388 clouds->setThickness(event.cloud_params.thickness);
3389 clouds->setSpeed(v2f(
3390 event.cloud_params.speed_x,
3391 event.cloud_params.speed_y));
3396 // unknown or unhandled type
3404 void Game::updateCamera(u32 busy_time, f32 dtime)
3406 LocalPlayer *player = client->getEnv().getLocalPlayer();
3409 For interaction purposes, get info about the held item
3411 - Is it a usable item?
3412 - Can it point to liquids?
3414 ItemStack playeritem;
3416 InventoryList *mlist = local_inventory->getList("main");
3418 if (mlist && client->getPlayerItem() < mlist->getSize())
3419 playeritem = mlist->getItem(client->getPlayerItem());
3422 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3423 InventoryList *hlist = local_inventory->getList("hand");
3425 playeritem = hlist->getItem(0);
3429 ToolCapabilities playeritem_toolcap =
3430 playeritem.getToolCapabilities(itemdef_manager);
3432 v3s16 old_camera_offset = camera->getOffset();
3434 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3435 GenericCAO *playercao = player->getCAO();
3437 // If playercao not loaded, don't change camera
3441 camera->toggleCameraMode();
3443 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3444 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3447 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3448 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3450 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3451 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3453 camera->step(dtime);
3455 v3f camera_position = camera->getPosition();
3456 v3f camera_direction = camera->getDirection();
3457 f32 camera_fov = camera->getFovMax();
3458 v3s16 camera_offset = camera->getOffset();
3460 m_camera_offset_changed = (camera_offset != old_camera_offset);
3462 if (!flags.disable_camera_update) {
3463 client->getEnv().getClientMap().updateCamera(camera_position,
3464 camera_direction, camera_fov, camera_offset);
3466 if (m_camera_offset_changed) {
3467 client->updateCameraOffset(camera_offset);
3468 client->getEnv().updateCameraOffset(camera_offset);
3471 clouds->updateCameraOffset(camera_offset);
3477 void Game::updateSound(f32 dtime)
3479 // Update sound listener
3480 v3s16 camera_offset = camera->getOffset();
3481 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3482 v3f(0, 0, 0), // velocity
3483 camera->getDirection(),
3484 camera->getCameraNode()->getUpVector());
3486 // Check if volume is in the proper range, else fix it.
3487 float old_volume = g_settings->getFloat("sound_volume");
3488 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
3489 sound->setListenerGain(new_volume);
3491 if (old_volume != new_volume) {
3492 g_settings->setFloat("sound_volume", new_volume);
3495 LocalPlayer *player = client->getEnv().getLocalPlayer();
3497 // Tell the sound maker whether to make footstep sounds
3498 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3500 // Update sound maker
3501 if (player->makes_footstep_sound)
3502 soundmaker->step(dtime);
3504 ClientMap &map = client->getEnv().getClientMap();
3505 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3506 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3510 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3512 LocalPlayer *player = client->getEnv().getLocalPlayer();
3514 ItemStack playeritem;
3516 InventoryList *mlist = local_inventory->getList("main");
3518 if (mlist && client->getPlayerItem() < mlist->getSize())
3519 playeritem = mlist->getItem(client->getPlayerItem());
3522 const ItemDefinition &playeritem_def =
3523 playeritem.getDefinition(itemdef_manager);
3524 InventoryList *hlist = local_inventory->getList("hand");
3525 const ItemDefinition &hand_def =
3526 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3528 v3f player_position = player->getPosition();
3529 v3f camera_position = camera->getPosition();
3530 v3f camera_direction = camera->getDirection();
3531 v3s16 camera_offset = camera->getOffset();
3535 Calculate what block is the crosshair pointing to
3538 f32 d = playeritem_def.range; // max. distance
3539 f32 d_hand = hand_def.range;
3541 if (d < 0 && d_hand >= 0)
3546 core::line3d<f32> shootline;
3548 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3549 shootline = core::line3d<f32>(camera_position,
3550 camera_position + camera_direction * BS * d);
3552 // prevent player pointing anything in front-view
3553 shootline = core::line3d<f32>(camera_position,camera_position);
3556 #ifdef HAVE_TOUCHSCREENGUI
3558 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3559 shootline = g_touchscreengui->getShootline();
3560 shootline.start += intToFloat(camera_offset, BS);
3561 shootline.end += intToFloat(camera_offset, BS);
3566 PointedThing pointed = updatePointedThing(shootline,
3567 playeritem_def.liquids_pointable,
3568 !runData.ldown_for_dig,
3571 if (pointed != runData.pointed_old) {
3572 infostream << "Pointing at " << pointed.dump() << std::endl;
3573 hud->updateSelectionMesh(camera_offset);
3578 - releasing left mouse button
3579 - pointing away from node
3581 if (runData.digging) {
3582 if (getLeftReleased()) {
3583 infostream << "Left button released"
3584 << " (stopped digging)" << std::endl;
3585 runData.digging = false;
3586 } else if (pointed != runData.pointed_old) {
3587 if (pointed.type == POINTEDTHING_NODE
3588 && runData.pointed_old.type == POINTEDTHING_NODE
3589 && pointed.node_undersurface
3590 == runData.pointed_old.node_undersurface) {
3591 // Still pointing to the same node, but a different face.
3594 infostream << "Pointing away from node"
3595 << " (stopped digging)" << std::endl;
3596 runData.digging = false;
3597 hud->updateSelectionMesh(camera_offset);
3601 if (!runData.digging) {
3602 client->interact(1, runData.pointed_old);
3603 client->setCrack(-1, v3s16(0, 0, 0));
3604 runData.dig_time = 0.0;
3606 } else if (runData.dig_instantly && getLeftReleased()) {
3607 // Remove e.g. torches faster when clicking instead of holding LMB
3608 runData.nodig_delay_timer = 0;
3609 runData.dig_instantly = false;
3612 if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3613 runData.ldown_for_dig = false;
3616 runData.left_punch = false;
3618 soundmaker->m_player_leftpunch_sound.name = "";
3620 if (isRightPressed())
3621 runData.repeat_rightclick_timer += dtime;
3623 runData.repeat_rightclick_timer = 0;
3625 if (playeritem_def.usable && isLeftPressed()) {
3626 if (getLeftClicked() && (!client->moddingEnabled()
3627 || !client->getScript()->on_item_use(playeritem, pointed)))
3628 client->interact(4, pointed);
3629 } else if (pointed.type == POINTEDTHING_NODE) {
3630 ToolCapabilities playeritem_toolcap =
3631 playeritem.getToolCapabilities(itemdef_manager);
3632 if (playeritem.name.empty() && hand_def.tool_capabilities != NULL) {
3633 playeritem_toolcap = *hand_def.tool_capabilities;
3635 handlePointingAtNode(pointed, playeritem_def, playeritem,
3636 playeritem_toolcap, dtime);
3637 } else if (pointed.type == POINTEDTHING_OBJECT) {
3638 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3639 } else if (isLeftPressed()) {
3640 // When button is held down in air, show continuous animation
3641 runData.left_punch = true;
3642 } else if (getRightClicked()) {
3643 handlePointingAtNothing(playeritem);
3646 runData.pointed_old = pointed;
3648 if (runData.left_punch || getLeftClicked())
3649 camera->setDigging(0); // left click animation
3651 input->resetLeftClicked();
3652 input->resetRightClicked();
3654 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3655 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3657 input->resetLeftReleased();
3658 input->resetRightReleased();
3660 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3661 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3665 PointedThing Game::updatePointedThing(
3666 const core::line3d<f32> &shootline,
3667 bool liquids_pointable,
3668 bool look_for_object,
3669 const v3s16 &camera_offset)
3671 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3672 selectionboxes->clear();
3673 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3674 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3675 "show_entity_selectionbox");
3677 ClientEnvironment &env = client->getEnv();
3678 ClientMap &map = env.getClientMap();
3679 INodeDefManager *nodedef = map.getNodeDefManager();
3681 runData.selected_object = NULL;
3683 RaycastState s(shootline, look_for_object, liquids_pointable);
3684 PointedThing result;
3685 env.continueRaycast(&s, &result);
3686 if (result.type == POINTEDTHING_OBJECT) {
3687 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3688 aabb3f selection_box;
3689 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3690 runData.selected_object->getSelectionBox(&selection_box)) {
3691 v3f pos = runData.selected_object->getPosition();
3692 selectionboxes->push_back(aabb3f(selection_box));
3693 hud->setSelectionPos(pos, camera_offset);
3695 } else if (result.type == POINTEDTHING_NODE) {
3696 // Update selection boxes
3697 MapNode n = map.getNodeNoEx(result.node_undersurface);
3698 std::vector<aabb3f> boxes;
3699 n.getSelectionBoxes(nodedef, &boxes,
3700 n.getNeighbors(result.node_undersurface, &map));
3703 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3704 i != boxes.end(); ++i) {
3706 box.MinEdge -= v3f(d, d, d);
3707 box.MaxEdge += v3f(d, d, d);
3708 selectionboxes->push_back(box);
3710 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3712 hud->setSelectedFaceNormal(v3f(
3713 result.intersection_normal.X,
3714 result.intersection_normal.Y,
3715 result.intersection_normal.Z));
3718 // Update selection mesh light level and vertex colors
3719 if (selectionboxes->size() > 0) {
3720 v3f pf = hud->getSelectionPos();
3721 v3s16 p = floatToInt(pf, BS);
3723 // Get selection mesh light level
3724 MapNode n = map.getNodeNoEx(p);
3725 u16 node_light = getInteriorLight(n, -1, nodedef);
3726 u16 light_level = node_light;
3728 for (u8 i = 0; i < 6; i++) {
3729 n = map.getNodeNoEx(p + g_6dirs[i]);
3730 node_light = getInteriorLight(n, -1, nodedef);
3731 if (node_light > light_level)
3732 light_level = node_light;
3735 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3737 final_color_blend(&c, light_level, daynight_ratio);
3739 // Modify final color a bit with time
3740 u32 timer = porting::getTimeMs() % 5000;
3741 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3742 float sin_r = 0.08 * sin(timerf);
3743 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3744 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3745 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3746 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3747 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3749 // Set mesh final color
3750 hud->setSelectionMeshColor(c);
3756 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3758 infostream << "Right Clicked in Air" << std::endl;
3759 PointedThing fauxPointed;
3760 fauxPointed.type = POINTEDTHING_NOTHING;
3761 client->interact(5, fauxPointed);
3765 void Game::handlePointingAtNode(const PointedThing &pointed,
3766 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
3767 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3769 v3s16 nodepos = pointed.node_undersurface;
3770 v3s16 neighbourpos = pointed.node_abovesurface;
3773 Check information text of node
3776 ClientMap &map = client->getEnv().getClientMap();
3778 if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3779 && client->checkPrivilege("interact")) {
3780 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3783 // This should be done after digging handling
3784 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3787 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3789 MapNode n = map.getNodeNoEx(nodepos);
3791 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3792 infotext = L"Unknown node: ";
3793 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3797 if ((getRightClicked() ||
3798 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3799 client->checkPrivilege("interact")) {
3800 runData.repeat_rightclick_timer = 0;
3801 infostream << "Ground right-clicked" << std::endl;
3803 if (meta && meta->getString("formspec") != "" && !random_input
3804 && !isKeyDown(KeyType::SNEAK)) {
3805 infostream << "Launching custom inventory view" << std::endl;
3807 InventoryLocation inventoryloc;
3808 inventoryloc.setNodeMeta(nodepos);
3810 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3811 &client->getEnv().getClientMap(), nodepos);
3812 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3814 create_formspec_menu(¤t_formspec, client,
3815 &input->joystick, fs_src, txt_dst);
3818 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3820 // Report right click to server
3822 camera->setDigging(1); // right click animation (always shown for feedback)
3824 // If the wielded item has node placement prediction,
3826 bool placed = nodePlacementPrediction(*client,
3827 playeritem_def, playeritem,
3828 nodepos, neighbourpos);
3832 client->interact(3, pointed);
3834 soundmaker->m_player_rightpunch_sound =
3835 playeritem_def.sound_place;
3837 if (client->moddingEnabled())
3838 client->getScript()->on_placenode(pointed, playeritem_def);
3840 soundmaker->m_player_rightpunch_sound =
3843 if (playeritem_def.node_placement_prediction == "" ||
3844 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3845 client->interact(3, pointed); // Report to server
3847 soundmaker->m_player_rightpunch_sound =
3848 playeritem_def.sound_place_failed;
3856 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3857 const v3f &player_position, bool show_debug)
3859 infotext = unescape_enriched(
3860 utf8_to_wide(runData.selected_object->infoText()));
3863 if (infotext != L"") {
3866 infotext += unescape_enriched(utf8_to_wide(
3867 runData.selected_object->debugInfoText()));
3870 if (isLeftPressed()) {
3871 bool do_punch = false;
3872 bool do_punch_damage = false;
3874 if (runData.object_hit_delay_timer <= 0.0) {
3876 do_punch_damage = true;
3877 runData.object_hit_delay_timer = object_hit_delay;
3880 if (getLeftClicked())
3884 infostream << "Left-clicked object" << std::endl;
3885 runData.left_punch = true;
3888 if (do_punch_damage) {
3889 // Report direct punch
3890 v3f objpos = runData.selected_object->getPosition();
3891 v3f dir = (objpos - player_position).normalize();
3892 ItemStack item = playeritem;
3893 if (playeritem.name.empty()) {
3894 InventoryList *hlist = local_inventory->getList("hand");
3896 item = hlist->getItem(0);
3900 bool disable_send = runData.selected_object->directReportPunch(
3901 dir, &item, runData.time_from_last_punch);
3902 runData.time_from_last_punch = 0;
3905 client->interact(0, pointed);
3907 } else if (getRightClicked()) {
3908 infostream << "Right-clicked object" << std::endl;
3909 client->interact(3, pointed); // place
3914 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3915 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3917 LocalPlayer *player = client->getEnv().getLocalPlayer();
3918 ClientMap &map = client->getEnv().getClientMap();
3919 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3921 // NOTE: Similar piece of code exists on the server side for
3923 // Get digging parameters
3924 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3925 &playeritem_toolcap);
3927 // If can't dig, try hand
3928 if (!params.diggable) {
3929 InventoryList *hlist = local_inventory->getList("hand");
3930 const ItemDefinition &hand =
3931 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3932 const ToolCapabilities *tp = hand.tool_capabilities;
3935 params = getDigParams(nodedef_manager->get(n).groups, tp);
3938 if (!params.diggable) {
3939 // I guess nobody will wait for this long
3940 runData.dig_time_complete = 10000000.0;
3942 runData.dig_time_complete = params.time;
3944 if (m_cache_enable_particles) {
3945 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3946 client->getParticleManager()->addPunchingParticles(client,
3947 player, nodepos, n, features);
3951 if (!runData.digging) {
3952 infostream << "Started digging" << std::endl;
3953 runData.dig_instantly = runData.dig_time_complete == 0;
3954 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3956 client->interact(0, pointed);
3957 runData.digging = true;
3958 runData.ldown_for_dig = true;
3961 if (!runData.dig_instantly) {
3962 runData.dig_index = (float)crack_animation_length
3964 / runData.dig_time_complete;
3966 // This is for e.g. torches
3967 runData.dig_index = crack_animation_length;
3970 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3972 if (sound_dig.exists() && params.diggable) {
3973 if (sound_dig.name == "__group") {
3974 if (params.main_group != "") {
3975 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3976 soundmaker->m_player_leftpunch_sound.name =
3977 std::string("default_dig_") +
3981 soundmaker->m_player_leftpunch_sound = sound_dig;
3985 // Don't show cracks if not diggable
3986 if (runData.dig_time_complete >= 100000.0) {
3987 } else if (runData.dig_index < crack_animation_length) {
3988 //TimeTaker timer("client.setTempMod");
3989 //infostream<<"dig_index="<<dig_index<<std::endl;
3990 client->setCrack(runData.dig_index, nodepos);
3992 infostream << "Digging completed" << std::endl;
3993 client->setCrack(-1, v3s16(0, 0, 0));
3995 runData.dig_time = 0;
3996 runData.digging = false;
3998 runData.nodig_delay_timer =
3999 runData.dig_time_complete / (float)crack_animation_length;
4001 // We don't want a corresponding delay to very time consuming nodes
4002 // and nodes without digging time (e.g. torches) get a fixed delay.
4003 if (runData.nodig_delay_timer > 0.3)
4004 runData.nodig_delay_timer = 0.3;
4005 else if (runData.dig_instantly)
4006 runData.nodig_delay_timer = 0.15;
4008 bool is_valid_position;
4009 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
4010 if (is_valid_position) {
4011 if (client->moddingEnabled() &&
4012 client->getScript()->on_dignode(nodepos, wasnode)) {
4015 client->removeNode(nodepos);
4018 client->interact(2, pointed);
4020 if (m_cache_enable_particles) {
4021 const ContentFeatures &features =
4022 client->getNodeDefManager()->get(wasnode);
4023 client->getParticleManager()->addDiggingParticles(client,
4024 player, nodepos, wasnode, features);
4028 // Send event to trigger sound
4029 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4030 client->event()->put(e);
4033 if (runData.dig_time_complete < 100000.0) {
4034 runData.dig_time += dtime;
4036 runData.dig_time = 0;
4037 client->setCrack(-1, nodepos);
4040 camera->setDigging(0); // left click animation
4044 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
4045 const CameraOrientation &cam)
4047 LocalPlayer *player = client->getEnv().getLocalPlayer();
4053 if (draw_control->range_all) {
4054 runData.fog_range = 100000 * BS;
4056 runData.fog_range = draw_control->wanted_range * BS;
4060 Calculate general brightness
4062 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4063 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4064 float direct_brightness;
4067 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4068 direct_brightness = time_brightness;
4069 sunlight_seen = true;
4071 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4072 float old_brightness = sky->getBrightness();
4073 direct_brightness = client->getEnv().getClientMap()
4074 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
4075 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4079 float time_of_day_smooth = runData.time_of_day_smooth;
4080 float time_of_day = client->getEnv().getTimeOfDayF();
4082 static const float maxsm = 0.05;
4083 static const float todsm = 0.05;
4085 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4086 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4087 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4088 time_of_day_smooth = time_of_day;
4090 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4091 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4092 + (time_of_day + 1.0) * todsm;
4094 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4095 + time_of_day * todsm;
4097 runData.time_of_day = time_of_day;
4098 runData.time_of_day_smooth = time_of_day_smooth;
4100 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4101 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4102 player->getPitch());
4108 if (sky->getCloudsVisible()) {
4109 clouds->setVisible(true);
4110 clouds->step(dtime);
4111 // camera->getPosition is not enough for 3rd person views
4112 v3f camera_node_position = camera->getCameraNode()->getPosition();
4113 v3s16 camera_offset = camera->getOffset();
4114 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
4115 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
4116 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
4117 clouds->update(camera_node_position,
4118 sky->getCloudColor());
4119 if (clouds->isCameraInsideCloud() && m_cache_enable_fog &&
4120 !flags.force_fog_off) {
4121 // if inside clouds, and fog enabled, use that as sky
4123 video::SColor clouds_dark = clouds->getColor()
4124 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
4125 sky->overrideColors(clouds_dark, clouds->getColor());
4126 sky->setBodiesVisible(false);
4127 runData.fog_range = 20.0f * BS;
4128 // do not draw clouds after all
4129 clouds->setVisible(false);
4132 clouds->setVisible(false);
4139 client->getParticleManager()->step(dtime);
4145 if (m_cache_enable_fog && !flags.force_fog_off) {
4148 video::EFT_FOG_LINEAR,
4149 runData.fog_range * m_cache_fog_start,
4150 runData.fog_range * 1.0,
4158 video::EFT_FOG_LINEAR,
4168 Get chat messages from client
4171 v2u32 screensize = driver->getScreenSize();
4173 updateChat(*client, dtime, flags.show_debug, screensize,
4174 flags.show_chat, runData.profiler_current_page,
4175 *chat_backend, guitext_chat);
4181 if (client->getPlayerItem() != runData.new_playeritem)
4182 client->selectPlayerItem(runData.new_playeritem);
4184 // Update local inventory if it has changed
4185 if (client->getLocalInventoryUpdated()) {
4186 //infostream<<"Updating local inventory"<<std::endl;
4187 client->getLocalInventory(*local_inventory);
4188 runData.update_wielded_item_trigger = true;
4191 if (runData.update_wielded_item_trigger) {
4192 // Update wielded tool
4193 InventoryList *mlist = local_inventory->getList("main");
4195 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4196 ItemStack item = mlist->getItem(client->getPlayerItem());
4197 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4198 InventoryList *hlist = local_inventory->getList("hand");
4200 item = hlist->getItem(0);
4202 camera->wield(item);
4205 runData.update_wielded_item_trigger = false;
4209 Update block draw list every 200ms or when camera direction has
4212 runData.update_draw_list_timer += dtime;
4214 v3f camera_direction = camera->getDirection();
4215 if (runData.update_draw_list_timer >= 0.2
4216 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4217 || m_camera_offset_changed) {
4218 runData.update_draw_list_timer = 0;
4219 client->getEnv().getClientMap().updateDrawList(driver);
4220 runData.update_draw_list_last_cam_dir = camera_direction;
4223 updateGui(*stats, dtime, cam);
4226 make sure menu is on top
4227 1. Delete formspec menu reference if menu was removed
4228 2. Else, make sure formspec menu is on top
4230 if (current_formspec) {
4231 if (current_formspec->getReferenceCount() == 1) {
4232 current_formspec->drop();
4233 current_formspec = NULL;
4234 } else if (isMenuActive()) {
4235 guiroot->bringToFront(current_formspec);
4242 const video::SColor &skycolor = sky->getSkyColor();
4244 TimeTaker tt_draw("mainloop: draw");
4245 driver->beginScene(true, true, skycolor);
4247 RenderingEngine::draw_scene(camera, client, player, hud, mapper,
4248 guienv, screensize, skycolor, flags.show_hud,
4249 flags.show_minimap);
4254 if (flags.show_profiler_graph)
4255 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4260 if (runData.damage_flash > 0.0) {
4261 video::SColor color(runData.damage_flash, 180, 0, 0);
4262 driver->draw2DRectangle(color,
4263 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4266 runData.damage_flash -= 100.0 * dtime;
4272 if (player->hurt_tilt_timer > 0.0) {
4273 player->hurt_tilt_timer -= dtime * 5;
4275 if (player->hurt_tilt_timer < 0)
4276 player->hurt_tilt_strength = 0;
4280 Update minimap pos and rotation
4282 if (mapper && flags.show_minimap && flags.show_hud) {
4283 mapper->setPos(floatToInt(player->getPosition(), BS));
4284 mapper->setAngle(player->getYaw());
4292 stats->drawtime = tt_draw.stop(true);
4293 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4297 inline static const char *yawToDirectionString(int yaw)
4299 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4301 yaw = wrapDegrees_0_360(yaw);
4302 yaw = (yaw + 45) % 360 / 90;
4304 return direction[yaw];
4308 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4310 v2u32 screensize = driver->getScreenSize();
4311 LocalPlayer *player = client->getEnv().getLocalPlayer();
4312 v3f player_position = player->getPosition();
4314 if (flags.show_debug) {
4315 static float drawtime_avg = 0;
4316 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4317 u16 fps = 1.0 / stats.dtime_jitter.avg;
4319 std::ostringstream os(std::ios_base::binary);
4321 << PROJECT_NAME_C " " << g_version_hash
4322 << ", FPS = " << fps
4323 << ", range_all = " << draw_control->range_all
4324 << std::setprecision(0)
4325 << ", drawtime = " << drawtime_avg << " ms"
4326 << std::setprecision(1)
4327 << ", dtime_jitter = "
4328 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4329 << std::setprecision(1)
4330 << ", view_range = " << draw_control->wanted_range
4331 << std::setprecision(3)
4332 << ", RTT = " << client->getRTT() << " s";
4333 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4334 guitext->setVisible(true);
4336 guitext->setVisible(false);
4339 if (guitext->isVisible()) {
4340 core::rect<s32> rect(
4342 screensize.X, 5 + g_fontengine->getTextHeight()
4344 guitext->setRelativePosition(rect);
4347 if (flags.show_debug) {
4348 std::ostringstream os(std::ios_base::binary);
4349 os << std::setprecision(1) << std::fixed
4350 << "pos = (" << (player_position.X / BS)
4351 << ", " << (player_position.Y / BS)
4352 << ", " << (player_position.Z / BS)
4353 << "), yaw = " << (wrapDegrees_0_360(cam.camera_yaw)) << "°"
4354 << " " << yawToDirectionString(cam.camera_yaw)
4355 << ", seed = " << ((u64)client->getMapSeed());
4356 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4357 guitext2->setVisible(true);
4359 guitext2->setVisible(false);
4362 if (guitext2->isVisible()) {
4363 core::rect<s32> rect(
4364 5, 5 + g_fontengine->getTextHeight(),
4365 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4367 guitext2->setRelativePosition(rect);
4370 if (flags.show_debug && runData.pointed_old.type == POINTEDTHING_NODE) {
4371 ClientMap &map = client->getEnv().getClientMap();
4372 const INodeDefManager *nodedef = client->getNodeDefManager();
4373 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4375 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4376 std::ostringstream os(std::ios_base::binary);
4377 os << "pointing_at = (" << nodedef->get(n).name
4378 << ", param2 = " << (u64) n.getParam2()
4380 setStaticText(guitext3, utf8_to_wide(os.str()).c_str());
4381 guitext3->setVisible(true);
4383 guitext3->setVisible(false);
4386 guitext3->setVisible(false);
4389 if (guitext3->isVisible()) {
4390 core::rect<s32> rect(
4391 5, 5 + g_fontengine->getTextHeight() * 2,
4392 screensize.X, 5 + g_fontengine->getTextHeight() * 3
4394 guitext3->setRelativePosition(rect);
4397 setStaticText(guitext_info, infotext.c_str());
4398 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4400 float statustext_time_max = 1.5;
4402 if (!m_statustext.empty()) {
4403 runData.statustext_time += dtime;
4405 if (runData.statustext_time >= statustext_time_max) {
4407 runData.statustext_time = 0;
4411 setStaticText(guitext_status, m_statustext.c_str());
4412 guitext_status->setVisible(!m_statustext.empty());
4414 if (!m_statustext.empty()) {
4415 s32 status_width = guitext_status->getTextWidth();
4416 s32 status_height = guitext_status->getTextHeight();
4417 s32 status_y = screensize.Y - 150;
4418 s32 status_x = (screensize.X - status_width) / 2;
4419 core::rect<s32> rect(
4420 status_x , status_y - status_height,
4421 status_x + status_width, status_y
4423 guitext_status->setRelativePosition(rect);
4426 video::SColor initial_color(255, 0, 0, 0);
4428 if (guienv->getSkin())
4429 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4431 video::SColor final_color = initial_color;
4432 final_color.setAlpha(0);
4433 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4434 initial_color, final_color,
4435 pow(runData.statustext_time / statustext_time_max, 2.0f));
4436 guitext_status->setOverrideColor(fade_color);
4437 guitext_status->enableOverrideColor(true);
4442 /* Log times and stuff for visualization */
4443 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4445 Profiler::GraphValues values;
4446 g_profiler->graphGet(values);
4452 /****************************************************************************
4454 ****************************************************************************/
4456 /* On some computers framerate doesn't seem to be automatically limited
4458 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4460 // not using getRealTime is necessary for wine
4461 device->getTimer()->tick(); // Maker sure device time is up-to-date
4462 u32 time = device->getTimer()->getTime();
4463 u32 last_time = fps_timings->last_time;
4465 if (time > last_time) // Make sure time hasn't overflowed
4466 fps_timings->busy_time = time - last_time;
4468 fps_timings->busy_time = 0;
4470 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4471 ? g_settings->getFloat("pause_fps_max")
4472 : g_settings->getFloat("fps_max"));
4474 if (fps_timings->busy_time < frametime_min) {
4475 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4476 device->sleep(fps_timings->sleep_time);
4478 fps_timings->sleep_time = 0;
4481 /* Get the new value of the device timer. Note that device->sleep() may
4482 * not sleep for the entire requested time as sleep may be interrupted and
4483 * therefore it is arguably more accurate to get the new time from the
4484 * device rather than calculating it by adding sleep_time to time.
4487 device->getTimer()->tick(); // Update device timer
4488 time = device->getTimer()->getTime();
4490 if (time > last_time) // Make sure last_time hasn't overflowed
4491 *dtime = (time - last_time) / 1000.0;
4495 fps_timings->last_time = time;
4498 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
4500 const wchar_t *wmsg = wgettext(msg);
4501 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
4506 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4508 ((Game *)data)->readSettings();
4511 void Game::readSettings()
4513 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4514 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4515 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4516 m_cache_enable_particles = g_settings->getBool("enable_particles");
4517 m_cache_enable_fog = g_settings->getBool("enable_fog");
4518 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4519 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4520 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4522 m_cache_enable_noclip = g_settings->getBool("noclip");
4523 m_cache_enable_free_move = g_settings->getBool("free_move");
4525 m_cache_fog_start = g_settings->getFloat("fog_start");
4527 m_cache_cam_smoothing = 0;
4528 if (g_settings->getBool("cinematic"))
4529 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4531 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4533 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4534 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4535 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4539 /****************************************************************************/
4540 /****************************************************************************
4542 ****************************************************************************/
4543 /****************************************************************************/
4545 void Game::extendedResourceCleanup()
4547 // Extended resource accounting
4548 infostream << "Irrlicht resources after cleanup:" << std::endl;
4549 infostream << "\tRemaining meshes : "
4550 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
4551 infostream << "\tRemaining textures : "
4552 << driver->getTextureCount() << std::endl;
4554 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4555 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4556 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4560 clearTextureNameCache();
4561 infostream << "\tRemaining materials: "
4562 << driver-> getMaterialRendererCount()
4563 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4566 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4567 void Game::showPauseMenu()
4570 static const std::string control_text = strgettext("Default Controls:\n"
4571 "No menu visible:\n"
4572 "- single tap: button activate\n"
4573 "- double tap: place/use\n"
4574 "- slide finger: look around\n"
4575 "Menu/Inventory visible:\n"
4576 "- double tap (outside):\n"
4578 "- touch stack, touch slot:\n"
4580 "- touch&drag, tap 2nd finger\n"
4581 " --> place single item to slot\n"
4584 static const std::string control_text_template = strgettext("Controls:\n"
4585 "- %s: move forwards\n"
4586 "- %s: move backwards\n"
4588 "- %s: move right\n"
4589 "- %s: jump/climb\n"
4590 "- %s: sneak/go down\n"
4593 "- Mouse: turn/look\n"
4594 "- Mouse left: dig/punch\n"
4595 "- Mouse right: place/use\n"
4596 "- Mouse wheel: select item\n"
4600 char control_text_buf[600];
4602 snprintf(control_text_buf, ARRLEN(control_text_buf), control_text_template.c_str(),
4603 GET_KEY_NAME(keymap_forward),
4604 GET_KEY_NAME(keymap_backward),
4605 GET_KEY_NAME(keymap_left),
4606 GET_KEY_NAME(keymap_right),
4607 GET_KEY_NAME(keymap_jump),
4608 GET_KEY_NAME(keymap_sneak),
4609 GET_KEY_NAME(keymap_drop),
4610 GET_KEY_NAME(keymap_inventory),
4611 GET_KEY_NAME(keymap_chat)
4614 std::string control_text = std::string(control_text_buf);
4615 str_formspec_escape(control_text);
4618 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4619 std::ostringstream os;
4621 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4622 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4623 << strgettext("Continue") << "]";
4625 if (!simple_singleplayer_mode) {
4626 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4627 << strgettext("Change Password") << "]";
4629 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4633 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4634 << strgettext("Sound Volume") << "]";
4635 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4636 << strgettext("Change Keys") << "]";
4638 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4639 << strgettext("Exit to Menu") << "]";
4640 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4641 << strgettext("Exit to OS") << "]"
4642 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4643 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4645 << strgettext("Game info:") << "\n";
4646 const std::string &address = client->getAddressName();
4647 static const std::string mode = strgettext("- Mode: ");
4648 if (!simple_singleplayer_mode) {
4649 Address serverAddress = client->getServerAddress();
4650 if (address != "") {
4651 os << mode << strgettext("Remote server") << "\n"
4652 << strgettext("- Address: ") << address;
4654 os << mode << strgettext("Hosting server");
4656 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4658 os << mode << strgettext("Singleplayer") << "\n";
4660 if (simple_singleplayer_mode || address == "") {
4661 static const std::string on = strgettext("On");
4662 static const std::string off = strgettext("Off");
4663 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4664 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4665 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4666 os << strgettext("- Damage: ") << damage << "\n"
4667 << strgettext("- Creative Mode: ") << creative << "\n";
4668 if (!simple_singleplayer_mode) {
4669 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4670 os << strgettext("- PvP: ") << pvp << "\n"
4671 << strgettext("- Public: ") << announced << "\n";
4672 std::string server_name = g_settings->get("server_name");
4673 str_formspec_escape(server_name);
4674 if (announced == on && server_name != "")
4675 os << strgettext("- Server Name: ") << server_name;
4682 /* Note: FormspecFormSource and LocalFormspecHandler *
4683 * are deleted by guiFormSpecMenu */
4684 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4685 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4687 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
4688 current_formspec->setFocus("btn_continue");
4689 current_formspec->doPause = true;
4692 /****************************************************************************/
4693 /****************************************************************************
4694 extern function for launching the game
4695 ****************************************************************************/
4696 /****************************************************************************/
4698 void the_game(bool *kill,
4700 InputHandler *input,
4701 const std::string &map_dir,
4702 const std::string &playername,
4703 const std::string &password,
4704 const std::string &address, // If empty local server is created
4707 std::string &error_message,
4708 ChatBackend &chat_backend,
4709 bool *reconnect_requested,
4710 const SubgameSpec &gamespec, // Used for local game
4711 bool simple_singleplayer_mode)
4715 /* Make a copy of the server address because if a local singleplayer server
4716 * is created then this is updated and we don't want to change the value
4717 * passed to us by the calling function
4719 std::string server_address = address;
4723 if (game.startup(kill, random_input, input, map_dir,
4724 playername, password, &server_address, port, error_message,
4725 reconnect_requested, &chat_backend, gamespec,
4726 simple_singleplayer_mode)) {
4731 } catch (SerializationError &e) {
4732 error_message = std::string("A serialization error occurred:\n")
4733 + e.what() + "\n\nThe server is probably "
4734 " running a different version of " PROJECT_NAME_C ".";
4735 errorstream << error_message << std::endl;
4736 } catch (ServerError &e) {
4737 error_message = e.what();
4738 errorstream << "ServerError: " << error_message << std::endl;
4739 } catch (ModError &e) {
4740 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4741 errorstream << "ModError: " << error_message << std::endl;