3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include "client/renderingengine.h"
27 #include "client/inputhandler.h"
28 #include "client/tile.h" // For TextureSource
29 #include "client/keys.h"
30 #include "client/joystick_controller.h"
31 #include "clientmap.h"
34 #include "content_cao.h"
35 #include "event_manager.h"
36 #include "fontengine.h"
41 #include "guiChatConsole.h"
42 #include "guiFormSpecMenu.h"
43 #include "guiKeyChangeMenu.h"
44 #include "guiPasswordChange.h"
45 #include "guiVolumeChange.h"
46 #include "mainmenumanager.h"
49 #include "nodedef.h" // Needed for determining pointing to nodes
50 #include "nodemetadata.h"
51 #include "particles.h"
53 #include "quicktune_shortcutter.h"
60 #include "util/basic_macros.h"
61 #include "util/directiontables.h"
62 #include "util/pointedthing.h"
63 #include "irrlicht_changes/static_text.h"
65 #include "script/scripting_client.h"
68 #include "sound_openal.h"
71 extern Settings *g_settings;
72 extern Profiler *g_profiler;
78 struct TextDestNodeMetadata : public TextDest
80 TextDestNodeMetadata(v3s16 p, Client *client)
85 // This is deprecated I guess? -celeron55
86 void gotText(const std::wstring &text)
88 std::string ntext = wide_to_utf8(text);
89 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
90 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
92 fields["text"] = ntext;
93 m_client->sendNodemetaFields(m_p, "", fields);
95 void gotText(const StringMap &fields)
97 m_client->sendNodemetaFields(m_p, "", fields);
104 struct TextDestPlayerInventory : public TextDest
106 TextDestPlayerInventory(Client *client)
111 TextDestPlayerInventory(Client *client, const std::string &formname)
114 m_formname = formname;
116 void gotText(const StringMap &fields)
118 m_client->sendInventoryFields(m_formname, fields);
124 struct LocalFormspecHandler : public TextDest
126 LocalFormspecHandler(const std::string &formname)
128 m_formname = formname;
131 LocalFormspecHandler(const std::string &formname, Client *client):
134 m_formname = formname;
137 void gotText(const StringMap &fields)
139 if (m_formname == "MT_PAUSE_MENU") {
140 if (fields.find("btn_sound") != fields.end()) {
141 g_gamecallback->changeVolume();
145 if (fields.find("btn_key_config") != fields.end()) {
146 g_gamecallback->keyConfig();
150 if (fields.find("btn_exit_menu") != fields.end()) {
151 g_gamecallback->disconnect();
155 if (fields.find("btn_exit_os") != fields.end()) {
156 g_gamecallback->exitToOS();
158 RenderingEngine::get_raw_device()->closeDevice();
163 if (fields.find("btn_change_password") != fields.end()) {
164 g_gamecallback->changePassword();
168 if (fields.find("quit") != fields.end()) {
172 if (fields.find("btn_continue") != fields.end()) {
177 // Don't disable this part when modding is disabled, it's used in builtin
178 if (m_client && m_client->getScript())
179 m_client->getScript()->on_formspec_input(m_formname, fields);
182 Client *m_client = nullptr;
185 /* Form update callback */
187 class NodeMetadataFormSource: public IFormSource
190 NodeMetadataFormSource(ClientMap *map, v3s16 p):
195 std::string getForm()
197 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
202 return meta->getString("formspec");
205 virtual std::string resolveText(const std::string &str)
207 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
212 return meta->resolveString(str);
219 class PlayerInventoryFormSource: public IFormSource
222 PlayerInventoryFormSource(Client *client):
226 std::string getForm()
228 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
229 return player->inventory_formspec;
235 /* Profiler display */
237 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
238 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
240 if (show_profiler == 0) {
241 guitext_profiler->setVisible(false);
244 std::ostringstream os(std::ios_base::binary);
245 g_profiler->printPage(os, show_profiler, show_profiler_max);
246 std::wstring text = utf8_to_wide(os.str());
247 setStaticText(guitext_profiler, text.c_str());
248 guitext_profiler->setVisible(true);
250 s32 w = fe->getTextWidth(text.c_str());
255 unsigned text_height = fe->getTextHeight();
257 core::position2di upper_left, lower_right;
260 upper_left.Y = (text_height + 5) * 2;
261 lower_right.X = 12 + w;
262 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
264 if (lower_right.Y > screen_height * 2 / 3)
265 lower_right.Y = screen_height * 2 / 3;
267 core::rect<s32> rect(upper_left, lower_right);
269 guitext_profiler->setRelativePosition(rect);
270 guitext_profiler->setVisible(true);
278 Profiler::GraphValues values;
284 Meta(float initial = 0,
285 video::SColor color = video::SColor(255, 255, 255, 255)):
291 std::deque<Piece> m_log;
299 void put(const Profiler::GraphValues &values)
302 piece.values = values;
303 m_log.push_back(piece);
305 while (m_log.size() > m_log_max_size)
306 m_log.erase(m_log.begin());
309 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
310 gui::IGUIFont *font) const
312 // Do *not* use UNORDERED_MAP here as the order needs
313 // to be the same for each call to prevent flickering
314 std::map<std::string, Meta> m_meta;
316 for (std::deque<Piece>::const_iterator k = m_log.begin();
317 k != m_log.end(); ++k) {
318 const Piece &piece = *k;
320 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
321 i != piece.values.end(); ++i) {
322 const std::string &id = i->first;
323 const float &value = i->second;
324 std::map<std::string, Meta>::iterator j = m_meta.find(id);
326 if (j == m_meta.end()) {
327 m_meta[id] = Meta(value);
331 if (value < j->second.min)
332 j->second.min = value;
334 if (value > j->second.max)
335 j->second.max = value;
340 static const video::SColor usable_colors[] = {
341 video::SColor(255, 255, 100, 100),
342 video::SColor(255, 90, 225, 90),
343 video::SColor(255, 100, 100, 255),
344 video::SColor(255, 255, 150, 50),
345 video::SColor(255, 220, 220, 100)
347 static const u32 usable_colors_count =
348 sizeof(usable_colors) / sizeof(*usable_colors);
349 u32 next_color_i = 0;
351 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
352 i != m_meta.end(); ++i) {
353 Meta &meta = i->second;
354 video::SColor color(255, 200, 200, 200);
356 if (next_color_i < usable_colors_count)
357 color = usable_colors[next_color_i++];
363 s32 textx = x_left + m_log_max_size + 15;
364 s32 textx2 = textx + 200 - 15;
367 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
368 i != m_meta.end(); ++i) {
369 const std::string &id = i->first;
370 const Meta &meta = i->second;
372 s32 y = y_bottom - meta_i * 50;
373 float show_min = meta.min;
374 float show_max = meta.max;
376 if (show_min >= -0.0001 && show_max >= -0.0001) {
377 if (show_min <= show_max * 0.5)
383 snprintf(buf, 10, "%.3g", show_max);
384 font->draw(utf8_to_wide(buf).c_str(),
385 core::rect<s32>(textx, y - graphh,
386 textx2, y - graphh + texth),
388 snprintf(buf, 10, "%.3g", show_min);
389 font->draw(utf8_to_wide(buf).c_str(),
390 core::rect<s32>(textx, y - texth,
393 font->draw(utf8_to_wide(id).c_str(),
394 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
395 textx2, y - graphh / 2 + texth / 2),
398 s32 graph1h = graphh;
399 bool relativegraph = (show_min != 0 && show_min != show_max);
400 float lastscaledvalue = 0.0;
401 bool lastscaledvalue_exists = false;
403 for (std::deque<Piece>::const_iterator j = m_log.begin();
404 j != m_log.end(); ++j) {
405 const Piece &piece = *j;
407 bool value_exists = false;
408 Profiler::GraphValues::const_iterator k =
409 piece.values.find(id);
411 if (k != piece.values.end()) {
418 lastscaledvalue_exists = false;
422 float scaledvalue = 1.0;
424 if (show_max != show_min)
425 scaledvalue = (value - show_min) / (show_max - show_min);
427 if (scaledvalue == 1.0 && value == 0) {
429 lastscaledvalue_exists = false;
434 if (lastscaledvalue_exists) {
435 s32 ivalue1 = lastscaledvalue * graph1h;
436 s32 ivalue2 = scaledvalue * graph1h;
437 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
438 v2s32(x, graph1y - ivalue2), meta.color);
441 lastscaledvalue = scaledvalue;
442 lastscaledvalue_exists = true;
444 s32 ivalue = scaledvalue * graph1h;
445 driver->draw2DLine(v2s32(x, graph1y),
446 v2s32(x, graph1y - ivalue), meta.color);
457 class NodeDugEvent: public MtEvent
463 NodeDugEvent(v3s16 p, MapNode n):
467 const char *getType() const
475 ISoundManager *m_sound;
476 INodeDefManager *m_ndef;
478 bool makes_footstep_sound;
479 float m_player_step_timer;
481 SimpleSoundSpec m_player_step_sound;
482 SimpleSoundSpec m_player_leftpunch_sound;
483 SimpleSoundSpec m_player_rightpunch_sound;
485 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
488 makes_footstep_sound(true),
489 m_player_step_timer(0)
493 void playPlayerStep()
495 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
496 m_player_step_timer = 0.03;
497 if (makes_footstep_sound)
498 m_sound->playSound(m_player_step_sound, false);
502 static void viewBobbingStep(MtEvent *e, void *data)
504 SoundMaker *sm = (SoundMaker *)data;
505 sm->playPlayerStep();
508 static void playerRegainGround(MtEvent *e, void *data)
510 SoundMaker *sm = (SoundMaker *)data;
511 sm->playPlayerStep();
514 static void playerJump(MtEvent *e, void *data)
516 //SoundMaker *sm = (SoundMaker*)data;
519 static void cameraPunchLeft(MtEvent *e, void *data)
521 SoundMaker *sm = (SoundMaker *)data;
522 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
525 static void cameraPunchRight(MtEvent *e, void *data)
527 SoundMaker *sm = (SoundMaker *)data;
528 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
531 static void nodeDug(MtEvent *e, void *data)
533 SoundMaker *sm = (SoundMaker *)data;
534 NodeDugEvent *nde = (NodeDugEvent *)e;
535 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
538 static void playerDamage(MtEvent *e, void *data)
540 SoundMaker *sm = (SoundMaker *)data;
541 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
544 static void playerFallingDamage(MtEvent *e, void *data)
546 SoundMaker *sm = (SoundMaker *)data;
547 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
550 void registerReceiver(MtEventManager *mgr)
552 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
553 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
554 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
555 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
556 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
557 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
558 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
559 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
562 void step(float dtime)
564 m_player_step_timer -= dtime;
568 // Locally stored sounds don't need to be preloaded because of this
569 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
571 std::set<std::string> m_fetched;
573 void paths_insert(std::set<std::string> &dst_paths,
574 const std::string &base,
575 const std::string &name)
577 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
578 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
579 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
580 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
581 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
582 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
583 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
584 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
585 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
586 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
587 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
590 void fetchSounds(const std::string &name,
591 std::set<std::string> &dst_paths,
592 std::set<std::string> &dst_datas)
594 if (m_fetched.count(name))
597 m_fetched.insert(name);
599 paths_insert(dst_paths, porting::path_share, name);
600 paths_insert(dst_paths, porting::path_user, name);
605 // before 1.8 there isn't a "integer interface", only float
606 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
607 typedef f32 SamplerLayer_t;
609 typedef s32 SamplerLayer_t;
613 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
616 bool *m_force_fog_off;
619 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
620 CachedPixelShaderSetting<float> m_fog_distance;
621 CachedVertexShaderSetting<float> m_animation_timer_vertex;
622 CachedPixelShaderSetting<float> m_animation_timer_pixel;
623 CachedPixelShaderSetting<float, 3> m_day_light;
624 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
625 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
626 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
627 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
628 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
629 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
633 void onSettingsChange(const std::string &name)
635 if (name == "enable_fog")
636 m_fog_enabled = g_settings->getBool("enable_fog");
639 static void settingsCallback(const std::string &name, void *userdata)
641 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
644 void setSky(Sky *sky) { m_sky = sky; }
646 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
647 f32 *fog_range, Client *client) :
649 m_force_fog_off(force_fog_off),
650 m_fog_range(fog_range),
651 m_sky_bg_color("skyBgColor"),
652 m_fog_distance("fogDistance"),
653 m_animation_timer_vertex("animationTimer"),
654 m_animation_timer_pixel("animationTimer"),
655 m_day_light("dayLight"),
656 m_eye_position_pixel("eyePosition"),
657 m_eye_position_vertex("eyePosition"),
658 m_minimap_yaw("yawVec"),
659 m_base_texture("baseTexture"),
660 m_normal_texture("normalTexture"),
661 m_texture_flags("textureFlags"),
664 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
665 m_fog_enabled = g_settings->getBool("enable_fog");
668 ~GameGlobalShaderConstantSetter()
670 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
673 virtual void onSetConstants(video::IMaterialRendererServices *services,
680 video::SColor bgcolor = m_sky->getBgColor();
681 video::SColorf bgcolorf(bgcolor);
682 float bgcolorfa[4] = {
688 m_sky_bg_color.set(bgcolorfa, services);
691 float fog_distance = 10000 * BS;
693 if (m_fog_enabled && !*m_force_fog_off)
694 fog_distance = *m_fog_range;
696 m_fog_distance.set(&fog_distance, services);
698 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
699 video::SColorf sunlight;
700 get_sunlight_color(&sunlight, daynight_ratio);
705 m_day_light.set(dnc, services);
707 u32 animation_timer = porting::getTimeMs() % 100000;
708 float animation_timer_f = (float)animation_timer / 100000.f;
709 m_animation_timer_vertex.set(&animation_timer_f, services);
710 m_animation_timer_pixel.set(&animation_timer_f, services);
712 float eye_position_array[3];
713 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
714 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
715 eye_position_array[0] = epos.X;
716 eye_position_array[1] = epos.Y;
717 eye_position_array[2] = epos.Z;
719 epos.getAs3Values(eye_position_array);
721 m_eye_position_pixel.set(eye_position_array, services);
722 m_eye_position_vertex.set(eye_position_array, services);
724 if (m_client->getMinimap()) {
725 float minimap_yaw_array[3];
726 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
727 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
728 minimap_yaw_array[0] = minimap_yaw.X;
729 minimap_yaw_array[1] = minimap_yaw.Y;
730 minimap_yaw_array[2] = minimap_yaw.Z;
732 minimap_yaw.getAs3Values(minimap_yaw_array);
734 m_minimap_yaw.set(minimap_yaw_array, services);
737 SamplerLayer_t base_tex = 0,
740 m_base_texture.set(&base_tex, services);
741 m_normal_texture.set(&normal_tex, services);
742 m_texture_flags.set(&flags_tex, services);
747 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
750 bool *m_force_fog_off;
753 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
755 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
756 f32 *fog_range, Client *client) :
758 m_force_fog_off(force_fog_off),
759 m_fog_range(fog_range),
763 void setSky(Sky *sky) {
765 for (size_t i = 0; i < created_nosky.size(); ++i) {
766 created_nosky[i]->setSky(m_sky);
768 created_nosky.clear();
771 virtual IShaderConstantSetter* create()
773 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
774 m_sky, m_force_fog_off, m_fog_range, m_client);
776 created_nosky.push_back(scs);
782 bool nodePlacementPrediction(Client &client, const ItemDefinition &playeritem_def,
783 const ItemStack &playeritem, v3s16 nodepos, v3s16 neighbourpos)
785 std::string prediction = playeritem_def.node_placement_prediction;
786 INodeDefManager *nodedef = client.ndef();
787 ClientMap &map = client.getEnv().getClientMap();
789 bool is_valid_position;
791 node = map.getNodeNoEx(nodepos, &is_valid_position);
792 if (!is_valid_position)
795 if (prediction != "" && !nodedef->get(node).rightclickable) {
796 verbosestream << "Node placement prediction for "
797 << playeritem_def.name << " is "
798 << prediction << std::endl;
799 v3s16 p = neighbourpos;
801 // Place inside node itself if buildable_to
802 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
803 if (is_valid_position)
805 if (nodedef->get(n_under).buildable_to)
808 node = map.getNodeNoEx(p, &is_valid_position);
809 if (is_valid_position &&!nodedef->get(node).buildable_to)
814 // Find id of predicted node
816 bool found = nodedef->getId(prediction, id);
819 errorstream << "Node placement prediction failed for "
820 << playeritem_def.name << " (places "
822 << ") - Name not known" << std::endl;
826 const ContentFeatures &predicted_f = nodedef->get(id);
828 // Predict param2 for facedir and wallmounted nodes
831 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
832 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
833 v3s16 dir = nodepos - neighbourpos;
835 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
836 param2 = dir.Y < 0 ? 1 : 0;
837 } else if (abs(dir.X) > abs(dir.Z)) {
838 param2 = dir.X < 0 ? 3 : 2;
840 param2 = dir.Z < 0 ? 5 : 4;
844 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
845 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
846 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
848 if (abs(dir.X) > abs(dir.Z)) {
849 param2 = dir.X < 0 ? 3 : 1;
851 param2 = dir.Z < 0 ? 2 : 0;
857 //Check attachment if node is in group attached_node
858 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
859 static v3s16 wallmounted_dirs[8] = {
869 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
870 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
871 pp = p + wallmounted_dirs[param2];
873 pp = p + v3s16(0, -1, 0);
875 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
880 if ((predicted_f.param_type_2 == CPT2_COLOR
881 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
882 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
883 const std::string &indexstr = playeritem.metadata.getString(
885 if (!indexstr.empty()) {
886 s32 index = mystoi(indexstr);
887 if (predicted_f.param_type_2 == CPT2_COLOR) {
889 } else if (predicted_f.param_type_2
890 == CPT2_COLORED_WALLMOUNTED) {
891 // param2 = pure palette index + other
892 param2 = (index & 0xf8) | (param2 & 0x07);
893 } else if (predicted_f.param_type_2
894 == CPT2_COLORED_FACEDIR) {
895 // param2 = pure palette index + other
896 param2 = (index & 0xe0) | (param2 & 0x1f);
901 // Add node to client map
902 MapNode n(id, 0, param2);
905 LocalPlayer *player = client.getEnv().getLocalPlayer();
907 // Dont place node when player would be inside new node
908 // NOTE: This is to be eventually implemented by a mod as client-side Lua
909 if (!nodedef->get(n).walkable ||
910 g_settings->getBool("enable_build_where_you_stand") ||
911 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
912 (nodedef->get(n).walkable &&
913 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
914 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
916 // This triggers the required mesh update too
917 client.addNode(p, n);
920 } catch (InvalidPositionException &e) {
921 errorstream << "Node placement prediction failed for "
922 << playeritem_def.name << " (places "
924 << ") - Position not loaded" << std::endl;
931 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
932 Client *client, JoystickController *joystick,
933 IFormSource *fs_src, TextDest *txt_dest)
936 if (*cur_formspec == 0) {
937 *cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
938 client, client->getTextureSource(), fs_src, txt_dest);
939 (*cur_formspec)->doPause = false;
942 Caution: do not call (*cur_formspec)->drop() here --
943 the reference might outlive the menu, so we will
944 periodically check if *cur_formspec is the only
945 remaining reference (i.e. the menu was removed)
946 and delete it in that case.
950 (*cur_formspec)->setFormSource(fs_src);
951 (*cur_formspec)->setTextDest(txt_dest);
957 #define SIZE_TAG "size[11,5.5]"
959 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
962 /******************************************************************************/
963 static void updateChat(Client &client, f32 dtime, bool show_debug,
964 const v2u32 &screensize, bool show_chat, u32 show_profiler,
965 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
967 // Add chat log output for errors to be shown in chat
968 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
970 // Get new messages from error log buffer
971 while (!chat_log_error_buf.empty()) {
972 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
973 if (!g_settings->getBool("disable_escape_sequences")) {
974 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
976 chat_backend.addMessage(L"", error_message);
979 // Get new messages from client
980 std::wstring message = L"";
981 while (client.getChatMessage(message)) {
982 chat_backend.addUnparsedMessage(message);
985 // Remove old messages
986 chat_backend.step(dtime);
988 // Display all messages in a static text element
989 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
990 EnrichedString recent_chat = chat_backend.getRecentChat();
991 unsigned int line_height = g_fontengine->getLineHeight();
993 setStaticText(guitext_chat, recent_chat);
995 // Update gui element size and position
999 chat_y += 3 * line_height;
1001 // first pass to calculate height of text to be set
1002 const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
1003 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
1004 window_size.X - 20);
1005 core::rect<s32> rect(10, chat_y, width, chat_y + window_size.Y);
1006 guitext_chat->setRelativePosition(rect);
1008 //now use real height of text and adjust rect according to this size
1009 rect = core::rect<s32>(10, chat_y, width,
1010 chat_y + guitext_chat->getTextHeight());
1013 guitext_chat->setRelativePosition(rect);
1014 // Don't show chat if disabled or empty or profiler is enabled
1015 guitext_chat->setVisible(
1016 show_chat && recent_chat_count != 0 && !show_profiler);
1020 /****************************************************************************
1021 Fast key cache for main game loop
1022 ****************************************************************************/
1024 /* This is faster than using getKeySetting with the tradeoff that functions
1025 * using it must make sure that it's initialised before using it and there is
1026 * no error handling (for example bounds checking). This is really intended for
1027 * use only in the main running loop of the client (the_game()) where the faster
1028 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1029 * (e.g. formspecs) should continue using getKeySetting().
1037 populate_nonchanging();
1042 // Keys that are not settings dependent
1043 void populate_nonchanging();
1045 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1046 InputHandler *handler;
1049 void KeyCache::populate_nonchanging()
1051 key[KeyType::ESC] = EscapeKey;
1054 void KeyCache::populate()
1056 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1057 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1058 key[KeyType::LEFT] = getKeySetting("keymap_left");
1059 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1060 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1061 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1062 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1064 key[KeyType::AUTOFORWARD] = getKeySetting("keymap_autoforward");
1066 key[KeyType::DROP] = getKeySetting("keymap_drop");
1067 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1068 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1069 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1070 key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
1071 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1072 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1073 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1074 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1075 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1076 key[KeyType::HOTBAR_PREV] = getKeySetting("keymap_hotbar_previous");
1077 key[KeyType::HOTBAR_NEXT] = getKeySetting("keymap_hotbar_next");
1078 key[KeyType::MUTE] = getKeySetting("keymap_mute");
1079 key[KeyType::INC_VOLUME] = getKeySetting("keymap_increase_volume");
1080 key[KeyType::DEC_VOLUME] = getKeySetting("keymap_decrease_volume");
1081 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1082 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1083 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1084 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1085 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1086 = getKeySetting("keymap_toggle_force_fog_off");
1087 key[KeyType::TOGGLE_UPDATE_CAMERA]
1088 = getKeySetting("keymap_toggle_update_camera");
1089 key[KeyType::TOGGLE_DEBUG]
1090 = getKeySetting("keymap_toggle_debug");
1091 key[KeyType::TOGGLE_PROFILER]
1092 = getKeySetting("keymap_toggle_profiler");
1093 key[KeyType::CAMERA_MODE]
1094 = getKeySetting("keymap_camera_mode");
1095 key[KeyType::INCREASE_VIEWING_RANGE]
1096 = getKeySetting("keymap_increase_viewing_range_min");
1097 key[KeyType::DECREASE_VIEWING_RANGE]
1098 = getKeySetting("keymap_decrease_viewing_range_min");
1099 key[KeyType::RANGESELECT]
1100 = getKeySetting("keymap_rangeselect");
1101 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1103 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1104 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1105 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1106 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1108 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1110 for (int i = 0; i < 23; i++) {
1111 std::string slot_key_name = "keymap_slot" + std::to_string(i + 1);
1112 key[KeyType::SLOT_1 + i] = getKeySetting(slot_key_name.c_str());
1116 // First clear all keys, then re-add the ones we listen for
1117 handler->dontListenForKeys();
1118 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1119 handler->listenForKey(key[i]);
1121 handler->listenForKey(EscapeKey);
1122 handler->listenForKey(CancelKey);
1127 /****************************************************************************
1129 ****************************************************************************/
1131 const float object_hit_delay = 0.2;
1134 u32 last_time, busy_time, sleep_time;
1138 /* The reason the following structs are not anonymous structs within the
1139 * class is that they are not used by the majority of member functions and
1140 * many functions that do require objects of thse types do not modify them
1141 * (so they can be passed as a const qualified parameter)
1143 struct CameraOrientation {
1144 f32 camera_yaw; // "right/left"
1145 f32 camera_pitch; // "up/down"
1148 struct GameRunData {
1151 PointedThing pointed_old;
1156 bool update_wielded_item_trigger;
1157 bool reset_jump_timer;
1158 float nodig_delay_timer;
1160 float dig_time_complete;
1161 float repeat_rightclick_timer;
1162 float object_hit_delay_timer;
1163 float time_from_last_punch;
1164 ClientActiveObject *selected_object;
1168 float update_draw_list_timer;
1169 float statustext_time;
1173 v3f update_draw_list_last_cam_dir;
1175 u32 profiler_current_page;
1176 u32 profiler_max_page; // Number of pages
1179 float time_of_day_smooth;
1183 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1189 Jitter dtime_jitter, busy_time_jitter;
1192 /****************************************************************************
1194 ****************************************************************************/
1196 /* This is not intended to be a public class. If a public class becomes
1197 * desirable then it may be better to create another 'wrapper' class that
1198 * hides most of the stuff in this class (nothing in this class is required
1199 * by any other file) but exposes the public methods/data only.
1206 bool startup(bool *kill,
1208 InputHandler *input,
1209 const std::string &map_dir,
1210 const std::string &playername,
1211 const std::string &password,
1212 // If address is "", local server is used and address is updated
1213 std::string *address,
1215 std::string &error_message,
1217 ChatBackend *chat_backend,
1218 const SubgameSpec &gamespec, // Used for local game
1219 bool simple_singleplayer_mode);
1226 void extendedResourceCleanup();
1228 // Basic initialisation
1229 bool init(const std::string &map_dir, std::string *address,
1231 const SubgameSpec &gamespec);
1233 bool createSingleplayerServer(const std::string &map_dir,
1234 const SubgameSpec &gamespec, u16 port, std::string *address);
1237 bool createClient(const std::string &playername,
1238 const std::string &password, std::string *address, u16 port);
1241 // Client connection
1242 bool connectToServer(const std::string &playername,
1243 const std::string &password, std::string *address, u16 port,
1244 bool *connect_ok, bool *aborted);
1245 bool getServerContent(bool *aborted);
1249 void updateInteractTimers(f32 dtime);
1250 bool checkConnection();
1251 bool handleCallbacks();
1252 void processQueues();
1253 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1254 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1255 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1258 void processUserInput(f32 dtime);
1259 void processKeyInput();
1260 void processItemSelection(u16 *new_playeritem);
1262 void dropSelectedItem();
1263 void openInventory();
1264 void openConsole(float scale, const wchar_t *line=NULL);
1265 void toggleFreeMove();
1266 void toggleFreeMoveAlt();
1268 void toggleNoClip();
1269 void toggleCinematic();
1270 void toggleAutoforward();
1274 void toggleMinimap(bool shift_pressed);
1277 void toggleUpdateCamera();
1278 void toggleProfiler();
1280 void increaseViewRange();
1281 void decreaseViewRange();
1282 void toggleFullViewRange();
1284 void updateCameraDirection(CameraOrientation *cam, float dtime);
1285 void updateCameraOrientation(CameraOrientation *cam, float dtime);
1286 void updatePlayerControl(const CameraOrientation &cam);
1287 void step(f32 *dtime);
1288 void processClientEvents(CameraOrientation *cam);
1289 void updateCamera(u32 busy_time, f32 dtime);
1290 void updateSound(f32 dtime);
1291 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
1293 * Returns the object or node the player is pointing at.
1294 * Also updates the selected thing in the Hud.
1296 * @param[in] shootline the shootline, starting from
1297 * the camera position. This also gives the maximal distance
1299 * @param[in] liquids_pointable if false, liquids are ignored
1300 * @param[in] look_for_object if false, objects are ignored
1301 * @param[in] camera_offset offset of the camera
1302 * @param[out] selected_object the selected object or
1305 PointedThing updatePointedThing(
1306 const core::line3d<f32> &shootline, bool liquids_pointable,
1307 bool look_for_object, const v3s16 &camera_offset);
1308 void handlePointingAtNothing(const ItemStack &playerItem);
1309 void handlePointingAtNode(const PointedThing &pointed,
1310 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
1311 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1312 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
1313 const v3f &player_position, bool show_debug);
1314 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
1315 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1316 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
1317 const CameraOrientation &cam);
1318 void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
1319 void updateProfilerGraphs(ProfilerGraph *graph);
1322 void limitFps(FpsControl *fps_timings, f32 *dtime);
1324 void showOverlayMessage(const char *msg, float dtime, int percent,
1325 bool draw_clouds = true);
1327 static void settingChangedCallback(const std::string &setting_name, void *data);
1328 void readSettings();
1330 inline bool getLeftClicked()
1332 return input->getLeftClicked() ||
1333 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1335 inline bool getRightClicked()
1337 return input->getRightClicked() ||
1338 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1340 inline bool isLeftPressed()
1342 return input->getLeftState() ||
1343 input->joystick.isKeyDown(KeyType::MOUSE_L);
1345 inline bool isRightPressed()
1347 return input->getRightState() ||
1348 input->joystick.isKeyDown(KeyType::MOUSE_R);
1350 inline bool getLeftReleased()
1352 return input->getLeftReleased() ||
1353 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1356 inline bool isKeyDown(GameKeyType k)
1358 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1360 inline bool wasKeyDown(GameKeyType k)
1362 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1366 void handleAndroidChatInput();
1370 void showPauseMenu();
1372 InputHandler *input;
1377 IWritableTextureSource *texture_src;
1378 IWritableShaderSource *shader_src;
1380 // When created, these will be filled with data received from the server
1381 IWritableItemDefManager *itemdef_manager;
1382 IWritableNodeDefManager *nodedef_manager;
1384 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1385 ISoundManager *sound;
1386 bool sound_is_dummy;
1387 SoundMaker *soundmaker;
1389 ChatBackend *chat_backend;
1391 GUIFormSpecMenu *current_formspec;
1392 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1393 std::string cur_formname;
1395 EventManager *eventmgr;
1396 QuicktuneShortcutter *quicktune;
1398 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1399 MapDrawControl *draw_control;
1401 Clouds *clouds; // Free using ->Drop()
1402 Sky *sky; // Free using ->Drop()
1403 Inventory *local_inventory;
1407 GameRunData runData;
1411 This class does take ownership/responsibily for cleaning up etc of any of
1412 these items (e.g. device)
1414 IrrlichtDevice *device;
1415 video::IVideoDriver *driver;
1416 scene::ISceneManager *smgr;
1418 std::string *error_message;
1419 bool *reconnect_requested;
1420 scene::ISceneNode *skybox;
1423 bool simple_singleplayer_mode;
1426 /* Pre-calculated values
1428 int crack_animation_length;
1432 gui::IGUIStaticText *guitext; // First line of debug text
1433 gui::IGUIStaticText *guitext2; // Second line of debug text
1434 gui::IGUIStaticText *guitext3; // Third line of debug text
1435 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1436 gui::IGUIStaticText *guitext_status;
1437 gui::IGUIStaticText *guitext_chat; // Chat text
1438 gui::IGUIStaticText *guitext_profiler; // Profiler text
1440 std::wstring infotext;
1441 std::wstring m_statustext;
1445 IntervalLimiter profiler_interval;
1448 * TODO: Local caching of settings is not optimal and should at some stage
1449 * be updated to use a global settings object for getting thse values
1450 * (as opposed to the this local caching). This can be addressed in
1453 bool m_cache_doubletap_jump;
1454 bool m_cache_enable_clouds;
1455 bool m_cache_enable_joysticks;
1456 bool m_cache_enable_particles;
1457 bool m_cache_enable_fog;
1458 bool m_cache_enable_noclip;
1459 bool m_cache_enable_free_move;
1460 f32 m_cache_mouse_sensitivity;
1461 f32 m_cache_joystick_frustum_sensitivity;
1462 f32 m_repeat_right_click_time;
1463 f32 m_cache_cam_smoothing;
1464 f32 m_cache_fog_start;
1466 bool m_invert_mouse;
1467 bool m_first_loop_after_window_activation;
1468 bool m_camera_offset_changed;
1471 bool m_cache_hold_aux1;
1472 bool m_android_chat_open;
1481 itemdef_manager(NULL),
1482 nodedef_manager(NULL),
1484 sound_is_dummy(false),
1487 current_formspec(NULL),
1491 gui_chat_console(NULL),
1496 local_inventory(NULL),
1499 m_invert_mouse(false),
1500 m_first_loop_after_window_activation(false),
1501 m_camera_offset_changed(false)
1503 g_settings->registerChangedCallback("doubletap_jump",
1504 &settingChangedCallback, this);
1505 g_settings->registerChangedCallback("enable_clouds",
1506 &settingChangedCallback, this);
1507 g_settings->registerChangedCallback("doubletap_joysticks",
1508 &settingChangedCallback, this);
1509 g_settings->registerChangedCallback("enable_particles",
1510 &settingChangedCallback, this);
1511 g_settings->registerChangedCallback("enable_fog",
1512 &settingChangedCallback, this);
1513 g_settings->registerChangedCallback("mouse_sensitivity",
1514 &settingChangedCallback, this);
1515 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1516 &settingChangedCallback, this);
1517 g_settings->registerChangedCallback("repeat_rightclick_time",
1518 &settingChangedCallback, this);
1519 g_settings->registerChangedCallback("noclip",
1520 &settingChangedCallback, this);
1521 g_settings->registerChangedCallback("free_move",
1522 &settingChangedCallback, this);
1523 g_settings->registerChangedCallback("cinematic",
1524 &settingChangedCallback, this);
1525 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1526 &settingChangedCallback, this);
1527 g_settings->registerChangedCallback("camera_smoothing",
1528 &settingChangedCallback, this);
1533 m_cache_hold_aux1 = false; // This is initialised properly later
1540 /****************************************************************************
1542 ****************************************************************************/
1548 if (!sound_is_dummy)
1551 delete server; // deleted first to stop all server threads
1554 delete local_inventory;
1560 delete nodedef_manager;
1561 delete itemdef_manager;
1562 delete draw_control;
1564 extendedResourceCleanup();
1566 g_settings->deregisterChangedCallback("doubletap_jump",
1567 &settingChangedCallback, this);
1568 g_settings->deregisterChangedCallback("enable_clouds",
1569 &settingChangedCallback, this);
1570 g_settings->deregisterChangedCallback("enable_particles",
1571 &settingChangedCallback, this);
1572 g_settings->deregisterChangedCallback("enable_fog",
1573 &settingChangedCallback, this);
1574 g_settings->deregisterChangedCallback("mouse_sensitivity",
1575 &settingChangedCallback, this);
1576 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1577 &settingChangedCallback, this);
1578 g_settings->deregisterChangedCallback("noclip",
1579 &settingChangedCallback, this);
1580 g_settings->deregisterChangedCallback("free_move",
1581 &settingChangedCallback, this);
1582 g_settings->deregisterChangedCallback("cinematic",
1583 &settingChangedCallback, this);
1584 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1585 &settingChangedCallback, this);
1586 g_settings->deregisterChangedCallback("camera_smoothing",
1587 &settingChangedCallback, this);
1590 bool Game::startup(bool *kill,
1592 InputHandler *input,
1593 const std::string &map_dir,
1594 const std::string &playername,
1595 const std::string &password,
1596 std::string *address, // can change if simple_singleplayer_mode
1598 std::string &error_message,
1600 ChatBackend *chat_backend,
1601 const SubgameSpec &gamespec,
1602 bool simple_singleplayer_mode)
1605 this->device = RenderingEngine::get_raw_device();
1607 this->error_message = &error_message;
1608 this->reconnect_requested = reconnect;
1609 this->random_input = random_input;
1610 this->input = input;
1611 this->chat_backend = chat_backend;
1612 this->simple_singleplayer_mode = simple_singleplayer_mode;
1614 keycache.handler = input;
1615 keycache.populate();
1617 driver = device->getVideoDriver();
1618 smgr = RenderingEngine::get_scene_manager();
1620 RenderingEngine::get_scene_manager()->getParameters()->
1621 setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1623 memset(&runData, 0, sizeof(runData));
1624 runData.time_from_last_punch = 10.0;
1625 runData.profiler_max_page = 3;
1626 runData.update_wielded_item_trigger = true;
1628 memset(&flags, 0, sizeof(flags));
1629 flags.show_chat = true;
1630 flags.show_hud = true;
1631 flags.show_debug = g_settings->getBool("show_debug");
1632 m_invert_mouse = g_settings->getBool("invert_mouse");
1633 m_first_loop_after_window_activation = true;
1635 if (!init(map_dir, address, port, gamespec))
1638 if (!createClient(playername, password, address, port))
1647 ProfilerGraph graph;
1648 RunStats stats = { 0 };
1649 CameraOrientation cam_view_target = { 0 };
1650 CameraOrientation cam_view = { 0 };
1651 FpsControl draw_times = { 0 };
1652 f32 dtime; // in seconds
1654 /* Clear the profiler */
1655 Profiler::GraphValues dummyvalues;
1656 g_profiler->graphGet(dummyvalues);
1658 draw_times.last_time = RenderingEngine::get_timer_time();
1660 set_light_table(g_settings->getFloat("display_gamma"));
1663 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1664 && client->checkPrivilege("fast");
1667 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1668 g_settings->getU16("screen_h"));
1670 while (RenderingEngine::run()
1671 && !(*kill || g_gamecallback->shutdown_requested
1672 || (server && server->getShutdownRequested()))) {
1674 const irr::core::dimension2d<u32> ¤t_screen_size =
1675 RenderingEngine::get_video_driver()->getScreenSize();
1676 // Verify if window size has changed and save it if it's the case
1677 // Ensure evaluating settings->getBool after verifying screensize
1678 // First condition is cheaper
1679 if (previous_screen_size != current_screen_size &&
1680 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1681 g_settings->getBool("autosave_screensize")) {
1682 g_settings->setU16("screen_w", current_screen_size.Width);
1683 g_settings->setU16("screen_h", current_screen_size.Height);
1684 previous_screen_size = current_screen_size;
1687 /* Must be called immediately after a device->run() call because it
1688 * uses device->getTimer()->getTime()
1690 limitFps(&draw_times, &dtime);
1692 updateStats(&stats, draw_times, dtime);
1693 updateInteractTimers(dtime);
1695 if (!checkConnection())
1697 if (!handleCallbacks())
1703 hud->resizeHotbar();
1705 updateProfilers(stats, draw_times, dtime);
1706 processUserInput(dtime);
1707 // Update camera before player movement to avoid camera lag of one frame
1708 updateCameraDirection(&cam_view_target, dtime);
1709 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1710 cam_view.camera_yaw) * m_cache_cam_smoothing;
1711 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1712 cam_view.camera_pitch) * m_cache_cam_smoothing;
1713 updatePlayerControl(cam_view);
1715 processClientEvents(&cam_view_target);
1716 updateCamera(draw_times.busy_time, dtime);
1718 processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
1719 updateFrame(&graph, &stats, dtime, cam_view);
1720 updateProfilerGraphs(&graph);
1722 // Update if minimap has been disabled by the server
1723 flags.show_minimap &= client->shouldShowMinimap();
1728 void Game::shutdown()
1730 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1731 if (g_settings->get("3d_mode") == "pageflip") {
1732 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1735 if (current_formspec)
1736 current_formspec->quitMenu();
1738 showOverlayMessage("Shutting down...", 0, 0, false);
1743 if (gui_chat_console)
1744 gui_chat_console->drop();
1750 while (g_menumgr.menuCount() > 0) {
1751 g_menumgr.m_stack.front()->setVisible(false);
1752 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1755 if (current_formspec) {
1756 current_formspec->drop();
1757 current_formspec = NULL;
1760 chat_backend->addMessage(L"", L"# Disconnected.");
1761 chat_backend->addMessage(L"", L"");
1765 while (!client->isShutdown()) {
1766 assert(texture_src != NULL);
1767 assert(shader_src != NULL);
1768 texture_src->processQueue();
1769 shader_src->processQueue();
1776 /****************************************************************************/
1777 /****************************************************************************
1779 ****************************************************************************/
1780 /****************************************************************************/
1783 const std::string &map_dir,
1784 std::string *address,
1786 const SubgameSpec &gamespec)
1788 texture_src = createTextureSource();
1790 showOverlayMessage("Loading...", 0, 0);
1792 shader_src = createShaderSource();
1794 itemdef_manager = createItemDefManager();
1795 nodedef_manager = createNodeDefManager();
1797 eventmgr = new EventManager();
1798 quicktune = new QuicktuneShortcutter();
1800 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1801 && eventmgr && quicktune))
1807 // Create a server if not connecting to an existing one
1808 if (*address == "") {
1809 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1816 bool Game::initSound()
1819 if (g_settings->getBool("enable_sound")) {
1820 infostream << "Attempting to use OpenAL audio" << std::endl;
1821 sound = createOpenALSoundManager(&soundfetcher);
1823 infostream << "Failed to initialize OpenAL audio" << std::endl;
1825 infostream << "Sound disabled." << std::endl;
1829 infostream << "Using dummy audio." << std::endl;
1830 sound = &dummySoundManager;
1831 sound_is_dummy = true;
1834 soundmaker = new SoundMaker(sound, nodedef_manager);
1838 soundmaker->registerReceiver(eventmgr);
1843 bool Game::createSingleplayerServer(const std::string &map_dir,
1844 const SubgameSpec &gamespec, u16 port, std::string *address)
1846 showOverlayMessage("Creating server...", 0, 5);
1848 std::string bind_str = g_settings->get("bind_address");
1849 Address bind_addr(0, 0, 0, 0, port);
1851 if (g_settings->getBool("ipv6_server")) {
1852 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1856 bind_addr.Resolve(bind_str.c_str());
1857 } catch (ResolveError &e) {
1858 infostream << "Resolving bind address \"" << bind_str
1859 << "\" failed: " << e.what()
1860 << " -- Listening on all addresses." << std::endl;
1863 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1864 *error_message = "Unable to listen on " +
1865 bind_addr.serializeString() +
1866 " because IPv6 is disabled";
1867 errorstream << *error_message << std::endl;
1871 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1872 bind_addr.isIPv6(), false);
1874 server->start(bind_addr);
1879 bool Game::createClient(const std::string &playername,
1880 const std::string &password, std::string *address, u16 port)
1882 showOverlayMessage("Creating client...", 0, 10);
1884 draw_control = new MapDrawControl;
1888 bool could_connect, connect_aborted;
1890 if (!connectToServer(playername, password, address, port,
1891 &could_connect, &connect_aborted))
1894 if (!could_connect) {
1895 if (error_message->empty() && !connect_aborted) {
1896 // Should not happen if error messages are set properly
1897 *error_message = "Connection failed for unknown reason";
1898 errorstream << *error_message << std::endl;
1903 if (!getServerContent(&connect_aborted)) {
1904 if (error_message->empty() && !connect_aborted) {
1905 // Should not happen if error messages are set properly
1906 *error_message = "Connection failed for unknown reason";
1907 errorstream << *error_message << std::endl;
1912 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1913 &flags.force_fog_off, &runData.fog_range, client);
1914 shader_src->addShaderConstantSetterFactory(scsf);
1916 // Update cached textures, meshes and materials
1917 client->afterContentReceived();
1921 camera = new Camera(*draw_control, client);
1922 if (!camera || !camera->successfullyCreated(*error_message))
1924 client->setCamera(camera);
1928 if (m_cache_enable_clouds) {
1929 clouds = new Clouds(smgr, -1, time(0));
1931 *error_message = "Memory allocation error (clouds)";
1932 errorstream << *error_message << std::endl;
1939 sky = new Sky(-1, texture_src);
1941 skybox = NULL; // This is used/set later on in the main run loop
1943 local_inventory = new Inventory(itemdef_manager);
1945 if (!(sky && local_inventory)) {
1946 *error_message = "Memory allocation error (sky or local inventory)";
1947 errorstream << *error_message << std::endl;
1951 /* Pre-calculated values
1953 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1955 v2u32 size = t->getOriginalSize();
1956 crack_animation_length = size.Y / size.X;
1958 crack_animation_length = 5;
1964 /* Set window caption
1966 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1968 str += utf8_to_wide(g_version_hash);
1970 str += driver->getName();
1972 device->setWindowCaption(str.c_str());
1974 LocalPlayer *player = client->getEnv().getLocalPlayer();
1975 player->hurt_tilt_timer = 0;
1976 player->hurt_tilt_strength = 0;
1978 hud = new Hud(guienv, client, player, local_inventory);
1981 *error_message = "Memory error: could not create HUD";
1982 errorstream << *error_message << std::endl;
1986 mapper = client->getMinimap();
1988 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1993 bool Game::initGui()
1995 // First line of debug text
1996 guitext = addStaticText(guienv,
1997 utf8_to_wide(PROJECT_NAME_C).c_str(),
1998 core::rect<s32>(0, 0, 0, 0),
1999 false, false, guiroot);
2001 // Second line of debug text
2002 guitext2 = addStaticText(guienv,
2004 core::rect<s32>(0, 0, 0, 0),
2005 false, false, guiroot);
2007 // Third line of debug text
2008 guitext3 = addStaticText(guienv,
2010 core::rect<s32>(0, 0, 0, 0),
2011 false, false, guiroot);
2013 // At the middle of the screen
2014 // Object infos are shown in this
2015 guitext_info = addStaticText(guienv,
2017 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2018 false, true, guiroot);
2020 // Status text (displays info when showing and hiding GUI stuff, etc.)
2021 guitext_status = addStaticText(guienv,
2023 core::rect<s32>(0, 0, 0, 0),
2024 false, false, guiroot);
2025 guitext_status->setVisible(false);
2028 guitext_chat = addStaticText(
2031 core::rect<s32>(0, 0, 0, 0),
2032 //false, false); // Disable word wrap as of now
2033 false, true, guiroot);
2035 // Remove stale "recent" chat messages from previous connections
2036 chat_backend->clearRecentChat();
2038 // Chat backend and console
2039 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2040 -1, chat_backend, client, &g_menumgr);
2041 if (!gui_chat_console) {
2042 *error_message = "Could not allocate memory for chat console";
2043 errorstream << *error_message << std::endl;
2047 // Profiler text (size is updated when text is updated)
2048 guitext_profiler = addStaticText(guienv,
2050 core::rect<s32>(0, 0, 0, 0),
2051 false, false, guiroot);
2052 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2053 guitext_profiler->setVisible(false);
2054 guitext_profiler->setWordWrap(true);
2056 #ifdef HAVE_TOUCHSCREENGUI
2058 if (g_touchscreengui)
2059 g_touchscreengui->init(texture_src);
2066 bool Game::connectToServer(const std::string &playername,
2067 const std::string &password, std::string *address, u16 port,
2068 bool *connect_ok, bool *aborted)
2070 *connect_ok = false; // Let's not be overly optimistic
2072 bool local_server_mode = false;
2074 showOverlayMessage("Resolving address...", 0, 15);
2076 Address connect_address(0, 0, 0, 0, port);
2079 connect_address.Resolve(address->c_str());
2081 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2082 //connect_address.Resolve("localhost");
2083 if (connect_address.isIPv6()) {
2084 IPv6AddressBytes addr_bytes;
2085 addr_bytes.bytes[15] = 1;
2086 connect_address.setAddress(&addr_bytes);
2088 connect_address.setAddress(127, 0, 0, 1);
2090 local_server_mode = true;
2092 } catch (ResolveError &e) {
2093 *error_message = std::string("Couldn't resolve address: ") + e.what();
2094 errorstream << *error_message << std::endl;
2098 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2099 *error_message = "Unable to connect to " +
2100 connect_address.serializeString() +
2101 " because IPv6 is disabled";
2102 errorstream << *error_message << std::endl;
2106 client = new Client(playername.c_str(), password, *address,
2107 *draw_control, texture_src, shader_src,
2108 itemdef_manager, nodedef_manager, sound, eventmgr,
2109 connect_address.isIPv6(), &flags);
2114 infostream << "Connecting to server at ";
2115 connect_address.print(&infostream);
2116 infostream << std::endl;
2118 client->connect(connect_address,
2119 simple_singleplayer_mode || local_server_mode);
2122 Wait for server to accept connection
2128 FpsControl fps_control = { 0 };
2130 f32 wait_time = 0; // in seconds
2132 fps_control.last_time = RenderingEngine::get_timer_time();
2137 while (RenderingEngine::run()) {
2139 limitFps(&fps_control, &dtime);
2141 // Update client and server
2142 client->step(dtime);
2145 server->step(dtime);
2148 if (client->getState() == LC_Init) {
2154 if (client->accessDenied()) {
2155 *error_message = "Access denied. Reason: "
2156 + client->accessDeniedReason();
2157 *reconnect_requested = client->reconnectRequested();
2158 errorstream << *error_message << std::endl;
2162 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2164 infostream << "Connect aborted [Escape]" << std::endl;
2169 // Only time out if we aren't waiting for the server we started
2170 if ((*address != "") && (wait_time > 10)) {
2171 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2172 // If no pre v25 init was sent, and no answer was received,
2173 // but the low level connection could be established
2174 // (meaning that we have a peer id), then we probably wanted
2175 // to connect to a legacy server. In this case, tell the user
2176 // to enable the option to be able to connect.
2177 if (!sent_old_init &&
2178 (client->getProtoVersion() == 0) &&
2179 client->connectedToServer()) {
2180 *error_message = "Connection failure: init packet not "
2181 "recognized by server.\n"
2182 "Most likely the server uses an old protocol version (<v25).\n"
2183 "Please ask the server owner to update to 0.4.13 or later.\n"
2184 "To still connect to the server in the meantime,\n"
2185 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2186 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2187 "entry in the advanced settings menu.";
2189 *error_message = "Connection timed out.";
2191 errorstream << *error_message << std::endl;
2196 showOverlayMessage("Connecting to server...", dtime, 20);
2198 } catch (con::PeerNotFoundException &e) {
2199 // TODO: Should something be done here? At least an info/error
2207 bool Game::getServerContent(bool *aborted)
2211 FpsControl fps_control = { 0 };
2212 f32 dtime; // in seconds
2214 fps_control.last_time = RenderingEngine::get_timer_time();
2216 while (RenderingEngine::run()) {
2218 limitFps(&fps_control, &dtime);
2220 // Update client and server
2221 client->step(dtime);
2224 server->step(dtime);
2227 if (client->mediaReceived() && client->itemdefReceived() &&
2228 client->nodedefReceived()) {
2233 if (!checkConnection())
2236 if (client->getState() < LC_Init) {
2237 *error_message = "Client disconnected";
2238 errorstream << *error_message << std::endl;
2242 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2244 infostream << "Connect aborted [Escape]" << std::endl;
2251 if (!client->itemdefReceived()) {
2252 const wchar_t *text = wgettext("Item definitions...");
2254 RenderingEngine::draw_load_screen(text, guienv, texture_src,
2257 } else if (!client->nodedefReceived()) {
2258 const wchar_t *text = wgettext("Node definitions...");
2260 RenderingEngine::draw_load_screen(text, guienv, texture_src,
2264 std::stringstream message;
2265 std::fixed(message);
2266 message.precision(0);
2267 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2268 message.precision(2);
2270 if ((USE_CURL == 0) ||
2271 (!g_settings->getBool("enable_remote_media_server"))) {
2272 float cur = client->getCurRate();
2273 std::string cur_unit = gettext("KiB/s");
2277 cur_unit = gettext("MiB/s");
2280 message << " (" << cur << ' ' << cur_unit << ")";
2283 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2284 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
2285 texture_src, dtime, progress);
2293 /****************************************************************************/
2294 /****************************************************************************
2296 ****************************************************************************/
2297 /****************************************************************************/
2299 inline void Game::updateInteractTimers(f32 dtime)
2301 if (runData.nodig_delay_timer >= 0)
2302 runData.nodig_delay_timer -= dtime;
2304 if (runData.object_hit_delay_timer >= 0)
2305 runData.object_hit_delay_timer -= dtime;
2307 runData.time_from_last_punch += dtime;
2311 /* returns false if game should exit, otherwise true
2313 inline bool Game::checkConnection()
2315 if (client->accessDenied()) {
2316 *error_message = "Access denied. Reason: "
2317 + client->accessDeniedReason();
2318 *reconnect_requested = client->reconnectRequested();
2319 errorstream << *error_message << std::endl;
2327 /* returns false if game should exit, otherwise true
2329 inline bool Game::handleCallbacks()
2331 if (g_gamecallback->disconnect_requested) {
2332 g_gamecallback->disconnect_requested = false;
2336 if (g_gamecallback->changepassword_requested) {
2337 (new GUIPasswordChange(guienv, guiroot, -1,
2338 &g_menumgr, client))->drop();
2339 g_gamecallback->changepassword_requested = false;
2342 if (g_gamecallback->changevolume_requested) {
2343 (new GUIVolumeChange(guienv, guiroot, -1,
2344 &g_menumgr))->drop();
2345 g_gamecallback->changevolume_requested = false;
2348 if (g_gamecallback->keyconfig_requested) {
2349 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2350 &g_menumgr))->drop();
2351 g_gamecallback->keyconfig_requested = false;
2354 if (g_gamecallback->keyconfig_changed) {
2355 keycache.populate(); // update the cache with new settings
2356 g_gamecallback->keyconfig_changed = false;
2363 void Game::processQueues()
2365 texture_src->processQueue();
2366 itemdef_manager->processQueue(client);
2367 shader_src->processQueue();
2371 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2373 float profiler_print_interval =
2374 g_settings->getFloat("profiler_print_interval");
2375 bool print_to_log = true;
2377 if (profiler_print_interval == 0) {
2378 print_to_log = false;
2379 profiler_print_interval = 5;
2382 if (profiler_interval.step(dtime, profiler_print_interval)) {
2384 infostream << "Profiler:" << std::endl;
2385 g_profiler->print(infostream);
2388 update_profiler_gui(guitext_profiler, g_fontengine,
2389 runData.profiler_current_page, runData.profiler_max_page,
2390 driver->getScreenSize().Height);
2392 g_profiler->clear();
2395 addProfilerGraphs(stats, draw_times, dtime);
2399 void Game::addProfilerGraphs(const RunStats &stats,
2400 const FpsControl &draw_times, f32 dtime)
2402 g_profiler->graphAdd("mainloop_other",
2403 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2405 if (draw_times.sleep_time != 0)
2406 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2407 g_profiler->graphAdd("mainloop_dtime", dtime);
2409 g_profiler->add("Elapsed time", dtime);
2410 g_profiler->avg("FPS", 1. / dtime);
2414 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2421 /* Time average and jitter calculation
2423 jp = &stats->dtime_jitter;
2424 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2426 jitter = dtime - jp->avg;
2428 if (jitter > jp->max)
2431 jp->counter += dtime;
2433 if (jp->counter > 0.0) {
2435 jp->max_sample = jp->max;
2436 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2440 /* Busytime average and jitter calculation
2442 jp = &stats->busy_time_jitter;
2443 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2445 jitter = draw_times.busy_time - jp->avg;
2447 if (jitter > jp->max)
2449 if (jitter < jp->min)
2452 jp->counter += dtime;
2454 if (jp->counter > 0.0) {
2456 jp->max_sample = jp->max;
2457 jp->min_sample = jp->min;
2465 /****************************************************************************
2467 ****************************************************************************/
2469 void Game::processUserInput(f32 dtime)
2471 // Reset input if window not active or some menu is active
2472 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
2474 #ifdef HAVE_TOUCHSCREENGUI
2475 g_touchscreengui->hide();
2478 #ifdef HAVE_TOUCHSCREENGUI
2479 else if (g_touchscreengui) {
2480 /* on touchscreengui step may generate own input events which ain't
2481 * what we want in case we just did clear them */
2482 g_touchscreengui->step(dtime);
2486 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2487 gui_chat_console->closeConsoleAtOnce();
2490 // Input handler step() (used by the random input generator)
2494 if (current_formspec != NULL)
2495 current_formspec->getAndroidUIInput();
2497 handleAndroidChatInput();
2500 // Increase timer for double tap of "keymap_jump"
2501 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2502 runData.jump_timer += dtime;
2505 processItemSelection(&runData.new_playeritem);
2509 void Game::processKeyInput()
2511 if (wasKeyDown(KeyType::DROP)) {
2513 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
2514 toggleAutoforward();
2515 } else if (wasKeyDown(KeyType::INVENTORY)) {
2517 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2518 if (!gui_chat_console->isOpenInhibited()) {
2521 } else if (wasKeyDown(KeyType::CHAT)) {
2522 openConsole(0.2, L"");
2523 } else if (wasKeyDown(KeyType::CMD)) {
2524 openConsole(0.2, L"/");
2525 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2526 openConsole(0.2, L".");
2527 } else if (wasKeyDown(KeyType::CONSOLE)) {
2528 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2529 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2531 } else if (wasKeyDown(KeyType::JUMP)) {
2532 toggleFreeMoveAlt();
2533 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2535 } else if (wasKeyDown(KeyType::NOCLIP)) {
2537 } else if (wasKeyDown(KeyType::MUTE)) {
2538 float volume = g_settings->getFloat("sound_volume");
2539 if (volume < 0.001f) {
2540 g_settings->setFloat("sound_volume", 1.0f);
2541 m_statustext = narrow_to_wide(gettext("Volume changed to 100%"));
2543 g_settings->setFloat("sound_volume", 0.0f);
2544 m_statustext = narrow_to_wide(gettext("Volume changed to 0%"));
2546 runData.statustext_time = 0;
2547 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
2548 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
2550 g_settings->setFloat("sound_volume", new_volume);
2551 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2552 m_statustext = narrow_to_wide(buf);
2553 runData.statustext_time = 0;
2554 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
2555 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
2557 g_settings->setFloat("sound_volume", new_volume);
2558 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2559 m_statustext = narrow_to_wide(buf);
2560 runData.statustext_time = 0;
2561 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2563 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2564 client->makeScreenshot();
2565 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2567 } else if (wasKeyDown(KeyType::MINIMAP)) {
2568 toggleMinimap(isKeyDown(KeyType::SNEAK));
2569 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2571 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2573 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2574 toggleUpdateCamera();
2575 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2577 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2579 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2580 increaseViewRange();
2581 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2582 decreaseViewRange();
2583 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2584 toggleFullViewRange();
2585 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2587 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2589 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2591 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2593 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2594 // Print debug stacks
2595 dstream << "-----------------------------------------"
2597 dstream << "Printing debug stacks:" << std::endl;
2598 dstream << "-----------------------------------------"
2600 debug_stacks_print();
2603 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2604 runData.reset_jump_timer = false;
2605 runData.jump_timer = 0.0f;
2608 if (quicktune->hasMessage()) {
2609 m_statustext = utf8_to_wide(quicktune->getMessage());
2610 runData.statustext_time = 0.0f;
2614 void Game::processItemSelection(u16 *new_playeritem)
2616 LocalPlayer *player = client->getEnv().getLocalPlayer();
2618 /* Item selection using mouse wheel
2620 *new_playeritem = client->getPlayerItem();
2622 s32 wheel = input->getMouseWheel();
2623 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2624 player->hud_hotbar_itemcount - 1);
2628 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2629 wasKeyDown(KeyType::HOTBAR_NEXT)) {
2633 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2634 wasKeyDown(KeyType::HOTBAR_PREV)) {
2639 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2641 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2644 /* Item selection using hotbar slot keys
2646 for (u16 i = 0; i < 23; i++) {
2647 if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
2648 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2649 *new_playeritem = i;
2650 infostream << "Selected item: " << new_playeritem << std::endl;
2658 void Game::dropSelectedItem()
2660 IDropAction *a = new IDropAction();
2662 a->from_inv.setCurrentPlayer();
2663 a->from_list = "main";
2664 a->from_i = client->getPlayerItem();
2665 client->inventoryAction(a);
2669 void Game::openInventory()
2672 * Don't permit to open inventory is CAO or player doesn't exists.
2673 * This prevent showing an empty inventory at player load
2676 LocalPlayer *player = client->getEnv().getLocalPlayer();
2677 if (!player || !player->getCAO())
2680 infostream << "the_game: " << "Launching inventory" << std::endl;
2682 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2683 TextDest *txt_dst = new TextDestPlayerInventory(client);
2685 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
2688 InventoryLocation inventoryloc;
2689 inventoryloc.setCurrentPlayer();
2690 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2694 void Game::openConsole(float scale, const wchar_t *line)
2696 assert(scale > 0.0f && scale <= 1.0f);
2699 porting::showInputDialog(gettext("ok"), "", "", 2);
2700 m_android_chat_open = true;
2702 if (gui_chat_console->isOpenInhibited())
2704 gui_chat_console->openConsole(scale);
2706 gui_chat_console->setCloseOnEnter(true);
2707 gui_chat_console->replaceAndAddToHistory(line);
2713 void Game::handleAndroidChatInput()
2715 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2716 std::string text = porting::getInputDialogValue();
2717 client->typeChatMessage(utf8_to_wide(text));
2723 void Game::toggleFreeMove()
2725 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2727 bool free_move = !g_settings->getBool("free_move");
2728 g_settings->set("free_move", bool_to_cstr(free_move));
2730 runData.statustext_time = 0;
2731 m_statustext = msg[free_move];
2732 if (free_move && !client->checkPrivilege("fly"))
2733 m_statustext += L" (note: no 'fly' privilege)";
2737 void Game::toggleFreeMoveAlt()
2739 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2742 runData.reset_jump_timer = true;
2746 void Game::toggleFast()
2748 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2749 bool fast_move = !g_settings->getBool("fast_move");
2750 g_settings->set("fast_move", bool_to_cstr(fast_move));
2752 runData.statustext_time = 0;
2753 m_statustext = msg[fast_move];
2755 bool has_fast_privs = client->checkPrivilege("fast");
2757 if (fast_move && !has_fast_privs)
2758 m_statustext += L" (note: no 'fast' privilege)";
2761 m_cache_hold_aux1 = fast_move && has_fast_privs;
2766 void Game::toggleNoClip()
2768 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2769 bool noclip = !g_settings->getBool("noclip");
2770 g_settings->set("noclip", bool_to_cstr(noclip));
2772 runData.statustext_time = 0;
2773 m_statustext = msg[noclip];
2775 if (noclip && !client->checkPrivilege("noclip"))
2776 m_statustext += L" (note: no 'noclip' privilege)";
2779 void Game::toggleCinematic()
2781 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2782 bool cinematic = !g_settings->getBool("cinematic");
2783 g_settings->set("cinematic", bool_to_cstr(cinematic));
2785 runData.statustext_time = 0;
2786 m_statustext = msg[cinematic];
2789 // Autoforward by toggling continuous forward.
2790 void Game::toggleAutoforward()
2792 static const wchar_t *msg[] = { L"autoforward disabled", L"autoforward enabled" };
2793 bool autoforward_enabled = !g_settings->getBool("continuous_forward");
2794 g_settings->set("continuous_forward", bool_to_cstr(autoforward_enabled));
2796 runData.statustext_time = 0;
2797 m_statustext = msg[autoforward_enabled ? 1 : 0];
2800 void Game::toggleChat()
2802 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2804 flags.show_chat = !flags.show_chat;
2805 runData.statustext_time = 0;
2806 m_statustext = msg[flags.show_chat];
2810 void Game::toggleHud()
2812 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2814 flags.show_hud = !flags.show_hud;
2815 runData.statustext_time = 0;
2816 m_statustext = msg[flags.show_hud];
2819 void Game::toggleMinimap(bool shift_pressed)
2821 if (!mapper || !flags.show_hud || !g_settings->getBool("enable_minimap"))
2824 if (shift_pressed) {
2825 mapper->toggleMinimapShape();
2829 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2831 MinimapMode mode = MINIMAP_MODE_OFF;
2832 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2833 mode = mapper->getMinimapMode();
2834 mode = (MinimapMode)((int)mode + 1);
2837 flags.show_minimap = true;
2839 case MINIMAP_MODE_SURFACEx1:
2840 m_statustext = L"Minimap in surface mode, Zoom x1";
2842 case MINIMAP_MODE_SURFACEx2:
2843 m_statustext = L"Minimap in surface mode, Zoom x2";
2845 case MINIMAP_MODE_SURFACEx4:
2846 m_statustext = L"Minimap in surface mode, Zoom x4";
2848 case MINIMAP_MODE_RADARx1:
2849 m_statustext = L"Minimap in radar mode, Zoom x1";
2851 case MINIMAP_MODE_RADARx2:
2852 m_statustext = L"Minimap in radar mode, Zoom x2";
2854 case MINIMAP_MODE_RADARx4:
2855 m_statustext = L"Minimap in radar mode, Zoom x4";
2858 mode = MINIMAP_MODE_OFF;
2859 flags.show_minimap = false;
2860 m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2861 L"Minimap hidden" : L"Minimap disabled by server";
2864 runData.statustext_time = 0;
2865 mapper->setMinimapMode(mode);
2868 void Game::toggleFog()
2870 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2872 flags.force_fog_off = !flags.force_fog_off;
2873 runData.statustext_time = 0;
2874 m_statustext = msg[flags.force_fog_off];
2878 void Game::toggleDebug()
2880 // Initial / 4x toggle: Chat only
2881 // 1x toggle: Debug text with chat
2882 // 2x toggle: Debug text with profiler graph
2883 // 3x toggle: Debug text and wireframe
2884 if (!flags.show_debug) {
2885 flags.show_debug = true;
2886 flags.show_profiler_graph = false;
2887 draw_control->show_wireframe = false;
2888 m_statustext = L"Debug info shown";
2889 } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2890 flags.show_profiler_graph = true;
2891 m_statustext = L"Profiler graph shown";
2892 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2893 flags.show_profiler_graph = false;
2894 draw_control->show_wireframe = true;
2895 m_statustext = L"Wireframe shown";
2897 flags.show_debug = false;
2898 flags.show_profiler_graph = false;
2899 draw_control->show_wireframe = false;
2900 if (client->checkPrivilege("debug")) {
2901 m_statustext = L"Debug info, profiler graph, and wireframe hidden";
2903 m_statustext = L"Debug info and profiler graph hidden";
2906 runData.statustext_time = 0;
2910 void Game::toggleUpdateCamera()
2912 static const wchar_t *msg[] = {
2913 L"Camera update enabled",
2914 L"Camera update disabled"
2917 flags.disable_camera_update = !flags.disable_camera_update;
2918 runData.statustext_time = 0;
2919 m_statustext = msg[flags.disable_camera_update];
2923 void Game::toggleProfiler()
2925 runData.profiler_current_page =
2926 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2928 // FIXME: This updates the profiler with incomplete values
2929 update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2930 runData.profiler_max_page, driver->getScreenSize().Height);
2932 if (runData.profiler_current_page != 0) {
2933 std::wstringstream sstr;
2934 sstr << "Profiler shown (page " << runData.profiler_current_page
2935 << " of " << runData.profiler_max_page << ")";
2936 m_statustext = sstr.str();
2938 m_statustext = L"Profiler hidden";
2940 runData.statustext_time = 0;
2944 void Game::increaseViewRange()
2946 s16 range = g_settings->getS16("viewing_range");
2947 s16 range_new = range + 10;
2949 if (range_new > 4000) {
2951 m_statustext = utf8_to_wide("Viewing range is at maximum: "
2954 m_statustext = utf8_to_wide("Viewing range changed to "
2957 g_settings->set("viewing_range", itos(range_new));
2958 runData.statustext_time = 0;
2962 void Game::decreaseViewRange()
2964 s16 range = g_settings->getS16("viewing_range");
2965 s16 range_new = range - 10;
2967 if (range_new < 20) {
2969 m_statustext = utf8_to_wide("Viewing range is at minimum: "
2972 m_statustext = utf8_to_wide("Viewing range changed to "
2975 g_settings->set("viewing_range", itos(range_new));
2976 runData.statustext_time = 0;
2980 void Game::toggleFullViewRange()
2982 static const wchar_t *msg[] = {
2983 L"Normal view range",
2984 L"Infinite view range"
2987 draw_control->range_all = !draw_control->range_all;
2988 infostream << msg[draw_control->range_all] << std::endl;
2989 m_statustext = msg[draw_control->range_all];
2990 runData.statustext_time = 0;
2994 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2996 if ((device->isWindowActive() && device->isWindowFocused()
2997 && !isMenuActive()) || random_input) {
3000 if (!random_input) {
3001 // Mac OSX gets upset if this is set every frame
3002 if (device->getCursorControl()->isVisible())
3003 device->getCursorControl()->setVisible(false);
3007 if (m_first_loop_after_window_activation)
3008 m_first_loop_after_window_activation = false;
3010 updateCameraOrientation(cam, dtime);
3012 input->setMousePos((driver->getScreenSize().Width / 2),
3013 (driver->getScreenSize().Height / 2));
3017 // Mac OSX gets upset if this is set every frame
3018 if (!device->getCursorControl()->isVisible())
3019 device->getCursorControl()->setVisible(true);
3022 m_first_loop_after_window_activation = true;
3027 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
3029 #ifdef HAVE_TOUCHSCREENGUI
3030 if (g_touchscreengui) {
3031 cam->camera_yaw += g_touchscreengui->getYawChange();
3032 cam->camera_pitch = g_touchscreengui->getPitch();
3036 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3037 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3039 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3043 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3044 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3046 #ifdef HAVE_TOUCHSCREENGUI
3050 if (m_cache_enable_joysticks) {
3051 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3052 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
3053 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
3056 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3060 void Game::updatePlayerControl(const CameraOrientation &cam)
3062 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3064 // DO NOT use the isKeyDown method for the forward, backward, left, right
3065 // buttons, as the code that uses the controls needs to be able to
3066 // distinguish between the two in order to know when to use joysticks.
3068 PlayerControl control(
3069 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3070 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3071 input->isKeyDown(keycache.key[KeyType::LEFT]),
3072 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3073 isKeyDown(KeyType::JUMP),
3074 isKeyDown(KeyType::SPECIAL1),
3075 isKeyDown(KeyType::SNEAK),
3076 isKeyDown(KeyType::ZOOM),
3081 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3082 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3086 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3087 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3088 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3089 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3090 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3091 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3092 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3093 ( (u32)(isLeftPressed() & 0x1) << 7) |
3094 ( (u32)(isRightPressed() & 0x1) << 8
3098 /* For Android, simulate holding down AUX1 (fast move) if the user has
3099 * the fast_move setting toggled on. If there is an aux1 key defined for
3100 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3103 if (m_cache_hold_aux1) {
3104 control.aux1 = control.aux1 ^ true;
3105 keypress_bits ^= ((u32)(1U << 5));
3109 client->setPlayerControl(control);
3110 LocalPlayer *player = client->getEnv().getLocalPlayer();
3111 player->keyPressed = keypress_bits;
3117 inline void Game::step(f32 *dtime)
3119 bool can_be_and_is_paused =
3120 (simple_singleplayer_mode && g_menumgr.pausesGame());
3122 if (can_be_and_is_paused) { // This is for a singleplayer server
3123 *dtime = 0; // No time passes
3125 if (server != NULL) {
3126 //TimeTaker timer("server->step(dtime)");
3127 server->step(*dtime);
3130 //TimeTaker timer("client.step(dtime)");
3131 client->step(*dtime);
3136 void Game::processClientEvents(CameraOrientation *cam)
3138 LocalPlayer *player = client->getEnv().getLocalPlayer();
3140 while (client->hasClientEvents()) {
3141 ClientEvent event = client->getClientEvent();
3143 switch (event.type) {
3144 case CE_PLAYER_DAMAGE:
3145 if (client->getHP() == 0)
3147 if (client->moddingEnabled()) {
3148 client->getScript()->on_damage_taken(event.player_damage.amount);
3151 runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3152 runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3154 player->hurt_tilt_timer = 1.5;
3155 player->hurt_tilt_strength =
3156 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3158 client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3161 case CE_PLAYER_FORCE_MOVE:
3162 cam->camera_yaw = event.player_force_move.yaw;
3163 cam->camera_pitch = event.player_force_move.pitch;
3166 case CE_DEATHSCREEN:
3167 // This should be enabled for death formspec in builtin
3168 client->getScript()->on_death();
3170 /* Handle visualization */
3171 runData.damage_flash = 0;
3172 player->hurt_tilt_timer = 0;
3173 player->hurt_tilt_strength = 0;
3176 case CE_SHOW_FORMSPEC:
3177 if (*(event.show_formspec.formspec) == "") {
3178 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3179 current_formspec->quitMenu();
3182 FormspecFormSource *fs_src =
3183 new FormspecFormSource(*(event.show_formspec.formspec));
3184 TextDestPlayerInventory *txt_dst =
3185 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3187 create_formspec_menu(¤t_formspec, client, &input->joystick,
3189 cur_formname = *(event.show_formspec.formname);
3192 delete event.show_formspec.formspec;
3193 delete event.show_formspec.formname;
3196 case CE_SHOW_LOCAL_FORMSPEC:
3198 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3199 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3200 create_formspec_menu(¤t_formspec, client, &input->joystick,
3203 delete event.show_formspec.formspec;
3204 delete event.show_formspec.formname;
3207 case CE_SPAWN_PARTICLE:
3208 case CE_ADD_PARTICLESPAWNER:
3209 case CE_DELETE_PARTICLESPAWNER:
3210 client->getParticleManager()->handleParticleEvent(&event, client, player);
3215 u32 id = event.hudadd.id;
3217 HudElement *e = player->getHud(id);
3220 delete event.hudadd.pos;
3221 delete event.hudadd.name;
3222 delete event.hudadd.scale;
3223 delete event.hudadd.text;
3224 delete event.hudadd.align;
3225 delete event.hudadd.offset;
3226 delete event.hudadd.world_pos;
3227 delete event.hudadd.size;
3232 e->type = (HudElementType)event.hudadd.type;
3233 e->pos = *event.hudadd.pos;
3234 e->name = *event.hudadd.name;
3235 e->scale = *event.hudadd.scale;
3236 e->text = *event.hudadd.text;
3237 e->number = event.hudadd.number;
3238 e->item = event.hudadd.item;
3239 e->dir = event.hudadd.dir;
3240 e->align = *event.hudadd.align;
3241 e->offset = *event.hudadd.offset;
3242 e->world_pos = *event.hudadd.world_pos;
3243 e->size = *event.hudadd.size;
3245 u32 new_id = player->addHud(e);
3246 //if this isn't true our huds aren't consistent
3247 sanity_check(new_id == id);
3250 delete event.hudadd.pos;
3251 delete event.hudadd.name;
3252 delete event.hudadd.scale;
3253 delete event.hudadd.text;
3254 delete event.hudadd.align;
3255 delete event.hudadd.offset;
3256 delete event.hudadd.world_pos;
3257 delete event.hudadd.size;
3262 HudElement *e = player->removeHud(event.hudrm.id);
3270 u32 id = event.hudchange.id;
3271 HudElement *e = player->getHud(id);
3274 delete event.hudchange.v3fdata;
3275 delete event.hudchange.v2fdata;
3276 delete event.hudchange.sdata;
3277 delete event.hudchange.v2s32data;
3281 switch (event.hudchange.stat) {
3283 e->pos = *event.hudchange.v2fdata;
3287 e->name = *event.hudchange.sdata;
3290 case HUD_STAT_SCALE:
3291 e->scale = *event.hudchange.v2fdata;
3295 e->text = *event.hudchange.sdata;
3298 case HUD_STAT_NUMBER:
3299 e->number = event.hudchange.data;
3303 e->item = event.hudchange.data;
3307 e->dir = event.hudchange.data;
3310 case HUD_STAT_ALIGN:
3311 e->align = *event.hudchange.v2fdata;
3314 case HUD_STAT_OFFSET:
3315 e->offset = *event.hudchange.v2fdata;
3318 case HUD_STAT_WORLD_POS:
3319 e->world_pos = *event.hudchange.v3fdata;
3323 e->size = *event.hudchange.v2s32data;
3328 delete event.hudchange.v3fdata;
3329 delete event.hudchange.v2fdata;
3330 delete event.hudchange.sdata;
3331 delete event.hudchange.v2s32data;
3335 sky->setVisible(false);
3336 // Whether clouds are visible in front of a custom skybox
3337 sky->setCloudsEnabled(event.set_sky.clouds);
3344 // Handle according to type
3345 if (*event.set_sky.type == "regular") {
3346 sky->setVisible(true);
3347 sky->setCloudsEnabled(true);
3348 } else if (*event.set_sky.type == "skybox" &&
3349 event.set_sky.params->size() == 6) {
3350 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3351 skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
3352 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3353 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3354 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3355 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3356 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3357 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3359 // Handle everything else as plain color
3361 if (*event.set_sky.type != "plain")
3362 infostream << "Unknown sky type: "
3363 << (*event.set_sky.type) << std::endl;
3365 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3368 delete event.set_sky.bgcolor;
3369 delete event.set_sky.type;
3370 delete event.set_sky.params;
3373 case CE_OVERRIDE_DAY_NIGHT_RATIO:
3374 client->getEnv().setDayNightRatioOverride(
3375 event.override_day_night_ratio.do_override,
3376 event.override_day_night_ratio.ratio_f * 1000);
3379 case CE_CLOUD_PARAMS:
3381 clouds->setDensity(event.cloud_params.density);
3382 clouds->setColorBright(video::SColor(event.cloud_params.color_bright));
3383 clouds->setColorAmbient(video::SColor(event.cloud_params.color_ambient));
3384 clouds->setHeight(event.cloud_params.height);
3385 clouds->setThickness(event.cloud_params.thickness);
3386 clouds->setSpeed(v2f(
3387 event.cloud_params.speed_x,
3388 event.cloud_params.speed_y));
3393 // unknown or unhandled type
3401 void Game::updateCamera(u32 busy_time, f32 dtime)
3403 LocalPlayer *player = client->getEnv().getLocalPlayer();
3406 For interaction purposes, get info about the held item
3408 - Is it a usable item?
3409 - Can it point to liquids?
3411 ItemStack playeritem;
3413 InventoryList *mlist = local_inventory->getList("main");
3415 if (mlist && client->getPlayerItem() < mlist->getSize())
3416 playeritem = mlist->getItem(client->getPlayerItem());
3419 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3420 InventoryList *hlist = local_inventory->getList("hand");
3422 playeritem = hlist->getItem(0);
3426 ToolCapabilities playeritem_toolcap =
3427 playeritem.getToolCapabilities(itemdef_manager);
3429 v3s16 old_camera_offset = camera->getOffset();
3431 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3432 GenericCAO *playercao = player->getCAO();
3434 // If playercao not loaded, don't change camera
3438 camera->toggleCameraMode();
3440 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3441 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3444 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3445 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3447 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3448 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3450 camera->step(dtime);
3452 v3f camera_position = camera->getPosition();
3453 v3f camera_direction = camera->getDirection();
3454 f32 camera_fov = camera->getFovMax();
3455 v3s16 camera_offset = camera->getOffset();
3457 m_camera_offset_changed = (camera_offset != old_camera_offset);
3459 if (!flags.disable_camera_update) {
3460 client->getEnv().getClientMap().updateCamera(camera_position,
3461 camera_direction, camera_fov, camera_offset);
3463 if (m_camera_offset_changed) {
3464 client->updateCameraOffset(camera_offset);
3465 client->getEnv().updateCameraOffset(camera_offset);
3468 clouds->updateCameraOffset(camera_offset);
3474 void Game::updateSound(f32 dtime)
3476 // Update sound listener
3477 v3s16 camera_offset = camera->getOffset();
3478 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3479 v3f(0, 0, 0), // velocity
3480 camera->getDirection(),
3481 camera->getCameraNode()->getUpVector());
3483 // Check if volume is in the proper range, else fix it.
3484 float old_volume = g_settings->getFloat("sound_volume");
3485 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
3486 sound->setListenerGain(new_volume);
3488 if (old_volume != new_volume) {
3489 g_settings->setFloat("sound_volume", new_volume);
3492 LocalPlayer *player = client->getEnv().getLocalPlayer();
3494 // Tell the sound maker whether to make footstep sounds
3495 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3497 // Update sound maker
3498 if (player->makes_footstep_sound)
3499 soundmaker->step(dtime);
3501 ClientMap &map = client->getEnv().getClientMap();
3502 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3503 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3507 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3509 LocalPlayer *player = client->getEnv().getLocalPlayer();
3511 ItemStack playeritem;
3513 InventoryList *mlist = local_inventory->getList("main");
3515 if (mlist && client->getPlayerItem() < mlist->getSize())
3516 playeritem = mlist->getItem(client->getPlayerItem());
3519 const ItemDefinition &playeritem_def =
3520 playeritem.getDefinition(itemdef_manager);
3521 InventoryList *hlist = local_inventory->getList("hand");
3522 const ItemDefinition &hand_def =
3523 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3525 v3f player_position = player->getPosition();
3526 v3f camera_position = camera->getPosition();
3527 v3f camera_direction = camera->getDirection();
3528 v3s16 camera_offset = camera->getOffset();
3532 Calculate what block is the crosshair pointing to
3535 f32 d = playeritem_def.range; // max. distance
3536 f32 d_hand = hand_def.range;
3538 if (d < 0 && d_hand >= 0)
3543 core::line3d<f32> shootline;
3545 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3546 shootline = core::line3d<f32>(camera_position,
3547 camera_position + camera_direction * BS * d);
3549 // prevent player pointing anything in front-view
3550 shootline = core::line3d<f32>(camera_position,camera_position);
3553 #ifdef HAVE_TOUCHSCREENGUI
3555 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3556 shootline = g_touchscreengui->getShootline();
3557 shootline.start += intToFloat(camera_offset, BS);
3558 shootline.end += intToFloat(camera_offset, BS);
3563 PointedThing pointed = updatePointedThing(shootline,
3564 playeritem_def.liquids_pointable,
3565 !runData.ldown_for_dig,
3568 if (pointed != runData.pointed_old) {
3569 infostream << "Pointing at " << pointed.dump() << std::endl;
3570 hud->updateSelectionMesh(camera_offset);
3575 - releasing left mouse button
3576 - pointing away from node
3578 if (runData.digging) {
3579 if (getLeftReleased()) {
3580 infostream << "Left button released"
3581 << " (stopped digging)" << std::endl;
3582 runData.digging = false;
3583 } else if (pointed != runData.pointed_old) {
3584 if (pointed.type == POINTEDTHING_NODE
3585 && runData.pointed_old.type == POINTEDTHING_NODE
3586 && pointed.node_undersurface
3587 == runData.pointed_old.node_undersurface) {
3588 // Still pointing to the same node, but a different face.
3591 infostream << "Pointing away from node"
3592 << " (stopped digging)" << std::endl;
3593 runData.digging = false;
3594 hud->updateSelectionMesh(camera_offset);
3598 if (!runData.digging) {
3599 client->interact(1, runData.pointed_old);
3600 client->setCrack(-1, v3s16(0, 0, 0));
3601 runData.dig_time = 0.0;
3603 } else if (runData.dig_instantly && getLeftReleased()) {
3604 // Remove e.g. torches faster when clicking instead of holding LMB
3605 runData.nodig_delay_timer = 0;
3606 runData.dig_instantly = false;
3609 if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3610 runData.ldown_for_dig = false;
3613 runData.left_punch = false;
3615 soundmaker->m_player_leftpunch_sound.name = "";
3617 if (isRightPressed())
3618 runData.repeat_rightclick_timer += dtime;
3620 runData.repeat_rightclick_timer = 0;
3622 if (playeritem_def.usable && isLeftPressed()) {
3623 if (getLeftClicked() && (!client->moddingEnabled()
3624 || !client->getScript()->on_item_use(playeritem, pointed)))
3625 client->interact(4, pointed);
3626 } else if (pointed.type == POINTEDTHING_NODE) {
3627 ToolCapabilities playeritem_toolcap =
3628 playeritem.getToolCapabilities(itemdef_manager);
3629 if (playeritem.name.empty() && hand_def.tool_capabilities != NULL) {
3630 playeritem_toolcap = *hand_def.tool_capabilities;
3632 handlePointingAtNode(pointed, playeritem_def, playeritem,
3633 playeritem_toolcap, dtime);
3634 } else if (pointed.type == POINTEDTHING_OBJECT) {
3635 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3636 } else if (isLeftPressed()) {
3637 // When button is held down in air, show continuous animation
3638 runData.left_punch = true;
3639 } else if (getRightClicked()) {
3640 handlePointingAtNothing(playeritem);
3643 runData.pointed_old = pointed;
3645 if (runData.left_punch || getLeftClicked())
3646 camera->setDigging(0); // left click animation
3648 input->resetLeftClicked();
3649 input->resetRightClicked();
3651 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3652 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3654 input->resetLeftReleased();
3655 input->resetRightReleased();
3657 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3658 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3662 PointedThing Game::updatePointedThing(
3663 const core::line3d<f32> &shootline,
3664 bool liquids_pointable,
3665 bool look_for_object,
3666 const v3s16 &camera_offset)
3668 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3669 selectionboxes->clear();
3670 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3671 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3672 "show_entity_selectionbox");
3674 ClientEnvironment &env = client->getEnv();
3675 ClientMap &map = env.getClientMap();
3676 INodeDefManager *nodedef = map.getNodeDefManager();
3678 runData.selected_object = NULL;
3680 RaycastState s(shootline, look_for_object, liquids_pointable);
3681 PointedThing result;
3682 env.continueRaycast(&s, &result);
3683 if (result.type == POINTEDTHING_OBJECT) {
3684 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3685 aabb3f selection_box;
3686 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3687 runData.selected_object->getSelectionBox(&selection_box)) {
3688 v3f pos = runData.selected_object->getPosition();
3689 selectionboxes->push_back(aabb3f(selection_box));
3690 hud->setSelectionPos(pos, camera_offset);
3692 } else if (result.type == POINTEDTHING_NODE) {
3693 // Update selection boxes
3694 MapNode n = map.getNodeNoEx(result.node_undersurface);
3695 std::vector<aabb3f> boxes;
3696 n.getSelectionBoxes(nodedef, &boxes,
3697 n.getNeighbors(result.node_undersurface, &map));
3700 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3701 i != boxes.end(); ++i) {
3703 box.MinEdge -= v3f(d, d, d);
3704 box.MaxEdge += v3f(d, d, d);
3705 selectionboxes->push_back(box);
3707 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3709 hud->setSelectedFaceNormal(v3f(
3710 result.intersection_normal.X,
3711 result.intersection_normal.Y,
3712 result.intersection_normal.Z));
3715 // Update selection mesh light level and vertex colors
3716 if (selectionboxes->size() > 0) {
3717 v3f pf = hud->getSelectionPos();
3718 v3s16 p = floatToInt(pf, BS);
3720 // Get selection mesh light level
3721 MapNode n = map.getNodeNoEx(p);
3722 u16 node_light = getInteriorLight(n, -1, nodedef);
3723 u16 light_level = node_light;
3725 for (u8 i = 0; i < 6; i++) {
3726 n = map.getNodeNoEx(p + g_6dirs[i]);
3727 node_light = getInteriorLight(n, -1, nodedef);
3728 if (node_light > light_level)
3729 light_level = node_light;
3732 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3734 final_color_blend(&c, light_level, daynight_ratio);
3736 // Modify final color a bit with time
3737 u32 timer = porting::getTimeMs() % 5000;
3738 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3739 float sin_r = 0.08 * sin(timerf);
3740 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3741 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3742 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3743 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3744 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3746 // Set mesh final color
3747 hud->setSelectionMeshColor(c);
3753 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3755 infostream << "Right Clicked in Air" << std::endl;
3756 PointedThing fauxPointed;
3757 fauxPointed.type = POINTEDTHING_NOTHING;
3758 client->interact(5, fauxPointed);
3762 void Game::handlePointingAtNode(const PointedThing &pointed,
3763 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
3764 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3766 v3s16 nodepos = pointed.node_undersurface;
3767 v3s16 neighbourpos = pointed.node_abovesurface;
3770 Check information text of node
3773 ClientMap &map = client->getEnv().getClientMap();
3775 if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3776 && client->checkPrivilege("interact")) {
3777 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3780 // This should be done after digging handling
3781 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3784 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3786 MapNode n = map.getNodeNoEx(nodepos);
3788 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3789 infotext = L"Unknown node: ";
3790 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3794 if ((getRightClicked() ||
3795 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3796 client->checkPrivilege("interact")) {
3797 runData.repeat_rightclick_timer = 0;
3798 infostream << "Ground right-clicked" << std::endl;
3800 if (meta && meta->getString("formspec") != "" && !random_input
3801 && !isKeyDown(KeyType::SNEAK)) {
3802 infostream << "Launching custom inventory view" << std::endl;
3804 InventoryLocation inventoryloc;
3805 inventoryloc.setNodeMeta(nodepos);
3807 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3808 &client->getEnv().getClientMap(), nodepos);
3809 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3811 create_formspec_menu(¤t_formspec, client,
3812 &input->joystick, fs_src, txt_dst);
3815 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3817 // Report right click to server
3819 camera->setDigging(1); // right click animation (always shown for feedback)
3821 // If the wielded item has node placement prediction,
3823 bool placed = nodePlacementPrediction(*client,
3824 playeritem_def, playeritem,
3825 nodepos, neighbourpos);
3829 client->interact(3, pointed);
3831 soundmaker->m_player_rightpunch_sound =
3832 playeritem_def.sound_place;
3834 if (client->moddingEnabled())
3835 client->getScript()->on_placenode(pointed, playeritem_def);
3837 soundmaker->m_player_rightpunch_sound =
3840 if (playeritem_def.node_placement_prediction == "" ||
3841 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3842 client->interact(3, pointed); // Report to server
3844 soundmaker->m_player_rightpunch_sound =
3845 playeritem_def.sound_place_failed;
3853 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3854 const v3f &player_position, bool show_debug)
3856 infotext = unescape_enriched(
3857 utf8_to_wide(runData.selected_object->infoText()));
3860 if (infotext != L"") {
3863 infotext += unescape_enriched(utf8_to_wide(
3864 runData.selected_object->debugInfoText()));
3867 if (isLeftPressed()) {
3868 bool do_punch = false;
3869 bool do_punch_damage = false;
3871 if (runData.object_hit_delay_timer <= 0.0) {
3873 do_punch_damage = true;
3874 runData.object_hit_delay_timer = object_hit_delay;
3877 if (getLeftClicked())
3881 infostream << "Left-clicked object" << std::endl;
3882 runData.left_punch = true;
3885 if (do_punch_damage) {
3886 // Report direct punch
3887 v3f objpos = runData.selected_object->getPosition();
3888 v3f dir = (objpos - player_position).normalize();
3889 ItemStack item = playeritem;
3890 if (playeritem.name.empty()) {
3891 InventoryList *hlist = local_inventory->getList("hand");
3893 item = hlist->getItem(0);
3897 bool disable_send = runData.selected_object->directReportPunch(
3898 dir, &item, runData.time_from_last_punch);
3899 runData.time_from_last_punch = 0;
3902 client->interact(0, pointed);
3904 } else if (getRightClicked()) {
3905 infostream << "Right-clicked object" << std::endl;
3906 client->interact(3, pointed); // place
3911 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3912 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3914 LocalPlayer *player = client->getEnv().getLocalPlayer();
3915 ClientMap &map = client->getEnv().getClientMap();
3916 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3918 // NOTE: Similar piece of code exists on the server side for
3920 // Get digging parameters
3921 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3922 &playeritem_toolcap);
3924 // If can't dig, try hand
3925 if (!params.diggable) {
3926 InventoryList *hlist = local_inventory->getList("hand");
3927 const ItemDefinition &hand =
3928 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3929 const ToolCapabilities *tp = hand.tool_capabilities;
3932 params = getDigParams(nodedef_manager->get(n).groups, tp);
3935 if (!params.diggable) {
3936 // I guess nobody will wait for this long
3937 runData.dig_time_complete = 10000000.0;
3939 runData.dig_time_complete = params.time;
3941 if (m_cache_enable_particles) {
3942 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3943 client->getParticleManager()->addPunchingParticles(client,
3944 player, nodepos, n, features);
3948 if (!runData.digging) {
3949 infostream << "Started digging" << std::endl;
3950 runData.dig_instantly = runData.dig_time_complete == 0;
3951 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3953 client->interact(0, pointed);
3954 runData.digging = true;
3955 runData.ldown_for_dig = true;
3958 if (!runData.dig_instantly) {
3959 runData.dig_index = (float)crack_animation_length
3961 / runData.dig_time_complete;
3963 // This is for e.g. torches
3964 runData.dig_index = crack_animation_length;
3967 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3969 if (sound_dig.exists() && params.diggable) {
3970 if (sound_dig.name == "__group") {
3971 if (params.main_group != "") {
3972 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3973 soundmaker->m_player_leftpunch_sound.name =
3974 std::string("default_dig_") +
3978 soundmaker->m_player_leftpunch_sound = sound_dig;
3982 // Don't show cracks if not diggable
3983 if (runData.dig_time_complete >= 100000.0) {
3984 } else if (runData.dig_index < crack_animation_length) {
3985 //TimeTaker timer("client.setTempMod");
3986 //infostream<<"dig_index="<<dig_index<<std::endl;
3987 client->setCrack(runData.dig_index, nodepos);
3989 infostream << "Digging completed" << std::endl;
3990 client->setCrack(-1, v3s16(0, 0, 0));
3992 runData.dig_time = 0;
3993 runData.digging = false;
3995 runData.nodig_delay_timer =
3996 runData.dig_time_complete / (float)crack_animation_length;
3998 // We don't want a corresponding delay to very time consuming nodes
3999 // and nodes without digging time (e.g. torches) get a fixed delay.
4000 if (runData.nodig_delay_timer > 0.3)
4001 runData.nodig_delay_timer = 0.3;
4002 else if (runData.dig_instantly)
4003 runData.nodig_delay_timer = 0.15;
4005 bool is_valid_position;
4006 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
4007 if (is_valid_position) {
4008 if (client->moddingEnabled() &&
4009 client->getScript()->on_dignode(nodepos, wasnode)) {
4012 client->removeNode(nodepos);
4015 client->interact(2, pointed);
4017 if (m_cache_enable_particles) {
4018 const ContentFeatures &features =
4019 client->getNodeDefManager()->get(wasnode);
4020 client->getParticleManager()->addDiggingParticles(client,
4021 player, nodepos, wasnode, features);
4025 // Send event to trigger sound
4026 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4027 client->event()->put(e);
4030 if (runData.dig_time_complete < 100000.0) {
4031 runData.dig_time += dtime;
4033 runData.dig_time = 0;
4034 client->setCrack(-1, nodepos);
4037 camera->setDigging(0); // left click animation
4041 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
4042 const CameraOrientation &cam)
4044 LocalPlayer *player = client->getEnv().getLocalPlayer();
4050 if (draw_control->range_all) {
4051 runData.fog_range = 100000 * BS;
4053 runData.fog_range = draw_control->wanted_range * BS;
4057 Calculate general brightness
4059 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4060 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4061 float direct_brightness;
4064 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4065 direct_brightness = time_brightness;
4066 sunlight_seen = true;
4068 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4069 float old_brightness = sky->getBrightness();
4070 direct_brightness = client->getEnv().getClientMap()
4071 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
4072 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4076 float time_of_day_smooth = runData.time_of_day_smooth;
4077 float time_of_day = client->getEnv().getTimeOfDayF();
4079 static const float maxsm = 0.05;
4080 static const float todsm = 0.05;
4082 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4083 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4084 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4085 time_of_day_smooth = time_of_day;
4087 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4088 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4089 + (time_of_day + 1.0) * todsm;
4091 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4092 + time_of_day * todsm;
4094 runData.time_of_day = time_of_day;
4095 runData.time_of_day_smooth = time_of_day_smooth;
4097 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4098 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4099 player->getPitch());
4105 if (sky->getCloudsVisible()) {
4106 clouds->setVisible(true);
4107 clouds->step(dtime);
4108 // camera->getPosition is not enough for 3rd person views
4109 v3f camera_node_position = camera->getCameraNode()->getPosition();
4110 v3s16 camera_offset = camera->getOffset();
4111 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
4112 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
4113 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
4114 clouds->update(camera_node_position,
4115 sky->getCloudColor());
4116 if (clouds->isCameraInsideCloud() && m_cache_enable_fog &&
4117 !flags.force_fog_off) {
4118 // if inside clouds, and fog enabled, use that as sky
4120 video::SColor clouds_dark = clouds->getColor()
4121 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
4122 sky->overrideColors(clouds_dark, clouds->getColor());
4123 sky->setBodiesVisible(false);
4124 runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
4125 // do not draw clouds after all
4126 clouds->setVisible(false);
4129 clouds->setVisible(false);
4136 client->getParticleManager()->step(dtime);
4142 if (m_cache_enable_fog && !flags.force_fog_off) {
4145 video::EFT_FOG_LINEAR,
4146 runData.fog_range * m_cache_fog_start,
4147 runData.fog_range * 1.0,
4155 video::EFT_FOG_LINEAR,
4165 Get chat messages from client
4168 v2u32 screensize = driver->getScreenSize();
4170 updateChat(*client, dtime, flags.show_debug, screensize,
4171 flags.show_chat, runData.profiler_current_page,
4172 *chat_backend, guitext_chat);
4178 if (client->getPlayerItem() != runData.new_playeritem)
4179 client->selectPlayerItem(runData.new_playeritem);
4181 // Update local inventory if it has changed
4182 if (client->getLocalInventoryUpdated()) {
4183 //infostream<<"Updating local inventory"<<std::endl;
4184 client->getLocalInventory(*local_inventory);
4185 runData.update_wielded_item_trigger = true;
4188 if (runData.update_wielded_item_trigger) {
4189 // Update wielded tool
4190 InventoryList *mlist = local_inventory->getList("main");
4192 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4193 ItemStack item = mlist->getItem(client->getPlayerItem());
4194 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4195 InventoryList *hlist = local_inventory->getList("hand");
4197 item = hlist->getItem(0);
4199 camera->wield(item);
4202 runData.update_wielded_item_trigger = false;
4206 Update block draw list every 200ms or when camera direction has
4209 runData.update_draw_list_timer += dtime;
4211 v3f camera_direction = camera->getDirection();
4212 if (runData.update_draw_list_timer >= 0.2
4213 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4214 || m_camera_offset_changed) {
4215 runData.update_draw_list_timer = 0;
4216 client->getEnv().getClientMap().updateDrawList(driver);
4217 runData.update_draw_list_last_cam_dir = camera_direction;
4220 updateGui(*stats, dtime, cam);
4223 make sure menu is on top
4224 1. Delete formspec menu reference if menu was removed
4225 2. Else, make sure formspec menu is on top
4227 if (current_formspec) {
4228 if (current_formspec->getReferenceCount() == 1) {
4229 current_formspec->drop();
4230 current_formspec = NULL;
4231 } else if (isMenuActive()) {
4232 guiroot->bringToFront(current_formspec);
4239 const video::SColor &skycolor = sky->getSkyColor();
4241 TimeTaker tt_draw("mainloop: draw");
4242 driver->beginScene(true, true, skycolor);
4244 RenderingEngine::draw_scene(camera, client, player, hud, mapper,
4245 guienv, screensize, skycolor, flags.show_hud,
4246 flags.show_minimap);
4251 if (flags.show_profiler_graph)
4252 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4257 if (runData.damage_flash > 0.0) {
4258 video::SColor color(runData.damage_flash, 180, 0, 0);
4259 driver->draw2DRectangle(color,
4260 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4263 runData.damage_flash -= 100.0 * dtime;
4269 if (player->hurt_tilt_timer > 0.0) {
4270 player->hurt_tilt_timer -= dtime * 5;
4272 if (player->hurt_tilt_timer < 0)
4273 player->hurt_tilt_strength = 0;
4277 Update minimap pos and rotation
4279 if (mapper && flags.show_minimap && flags.show_hud) {
4280 mapper->setPos(floatToInt(player->getPosition(), BS));
4281 mapper->setAngle(player->getYaw());
4289 stats->drawtime = tt_draw.stop(true);
4290 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4294 inline static const char *yawToDirectionString(int yaw)
4296 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4298 yaw = wrapDegrees_0_360(yaw);
4299 yaw = (yaw + 45) % 360 / 90;
4301 return direction[yaw];
4305 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4307 v2u32 screensize = driver->getScreenSize();
4308 LocalPlayer *player = client->getEnv().getLocalPlayer();
4309 v3f player_position = player->getPosition();
4311 if (flags.show_debug) {
4312 static float drawtime_avg = 0;
4313 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4314 u16 fps = 1.0 / stats.dtime_jitter.avg;
4316 std::ostringstream os(std::ios_base::binary);
4318 << PROJECT_NAME_C " " << g_version_hash
4319 << ", FPS = " << fps
4320 << ", range_all = " << draw_control->range_all
4321 << std::setprecision(0)
4322 << ", drawtime = " << drawtime_avg << " ms"
4323 << std::setprecision(1)
4324 << ", dtime_jitter = "
4325 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4326 << std::setprecision(1)
4327 << ", view_range = " << draw_control->wanted_range
4328 << std::setprecision(3)
4329 << ", RTT = " << client->getRTT() << " s";
4330 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4331 guitext->setVisible(true);
4333 guitext->setVisible(false);
4336 if (guitext->isVisible()) {
4337 core::rect<s32> rect(
4339 screensize.X, 5 + g_fontengine->getTextHeight()
4341 guitext->setRelativePosition(rect);
4344 if (flags.show_debug) {
4345 std::ostringstream os(std::ios_base::binary);
4346 os << std::setprecision(1) << std::fixed
4347 << "pos = (" << (player_position.X / BS)
4348 << ", " << (player_position.Y / BS)
4349 << ", " << (player_position.Z / BS)
4350 << "), yaw = " << (wrapDegrees_0_360(cam.camera_yaw)) << "°"
4351 << " " << yawToDirectionString(cam.camera_yaw)
4352 << ", seed = " << ((u64)client->getMapSeed());
4353 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4354 guitext2->setVisible(true);
4356 guitext2->setVisible(false);
4359 if (guitext2->isVisible()) {
4360 core::rect<s32> rect(
4361 5, 5 + g_fontengine->getTextHeight(),
4362 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4364 guitext2->setRelativePosition(rect);
4367 if (flags.show_debug && runData.pointed_old.type == POINTEDTHING_NODE) {
4368 ClientMap &map = client->getEnv().getClientMap();
4369 const INodeDefManager *nodedef = client->getNodeDefManager();
4370 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4372 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4373 std::ostringstream os(std::ios_base::binary);
4374 os << "pointing_at = (" << nodedef->get(n).name
4375 << ", param2 = " << (u64) n.getParam2()
4377 setStaticText(guitext3, utf8_to_wide(os.str()).c_str());
4378 guitext3->setVisible(true);
4380 guitext3->setVisible(false);
4383 guitext3->setVisible(false);
4386 if (guitext3->isVisible()) {
4387 core::rect<s32> rect(
4388 5, 5 + g_fontengine->getTextHeight() * 2,
4389 screensize.X, 5 + g_fontengine->getTextHeight() * 3
4391 guitext3->setRelativePosition(rect);
4394 setStaticText(guitext_info, infotext.c_str());
4395 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4397 float statustext_time_max = 1.5;
4399 if (!m_statustext.empty()) {
4400 runData.statustext_time += dtime;
4402 if (runData.statustext_time >= statustext_time_max) {
4404 runData.statustext_time = 0;
4408 setStaticText(guitext_status, m_statustext.c_str());
4409 guitext_status->setVisible(!m_statustext.empty());
4411 if (!m_statustext.empty()) {
4412 s32 status_width = guitext_status->getTextWidth();
4413 s32 status_height = guitext_status->getTextHeight();
4414 s32 status_y = screensize.Y - 150;
4415 s32 status_x = (screensize.X - status_width) / 2;
4416 core::rect<s32> rect(
4417 status_x , status_y - status_height,
4418 status_x + status_width, status_y
4420 guitext_status->setRelativePosition(rect);
4423 video::SColor initial_color(255, 0, 0, 0);
4425 if (guienv->getSkin())
4426 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4428 video::SColor final_color = initial_color;
4429 final_color.setAlpha(0);
4430 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4431 initial_color, final_color,
4432 pow(runData.statustext_time / statustext_time_max, 2.0f));
4433 guitext_status->setOverrideColor(fade_color);
4434 guitext_status->enableOverrideColor(true);
4439 /* Log times and stuff for visualization */
4440 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4442 Profiler::GraphValues values;
4443 g_profiler->graphGet(values);
4449 /****************************************************************************
4451 ****************************************************************************/
4453 /* On some computers framerate doesn't seem to be automatically limited
4455 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4457 // not using getRealTime is necessary for wine
4458 device->getTimer()->tick(); // Maker sure device time is up-to-date
4459 u32 time = device->getTimer()->getTime();
4460 u32 last_time = fps_timings->last_time;
4462 if (time > last_time) // Make sure time hasn't overflowed
4463 fps_timings->busy_time = time - last_time;
4465 fps_timings->busy_time = 0;
4467 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4468 ? g_settings->getFloat("pause_fps_max")
4469 : g_settings->getFloat("fps_max"));
4471 if (fps_timings->busy_time < frametime_min) {
4472 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4473 device->sleep(fps_timings->sleep_time);
4475 fps_timings->sleep_time = 0;
4478 /* Get the new value of the device timer. Note that device->sleep() may
4479 * not sleep for the entire requested time as sleep may be interrupted and
4480 * therefore it is arguably more accurate to get the new time from the
4481 * device rather than calculating it by adding sleep_time to time.
4484 device->getTimer()->tick(); // Update device timer
4485 time = device->getTimer()->getTime();
4487 if (time > last_time) // Make sure last_time hasn't overflowed
4488 *dtime = (time - last_time) / 1000.0;
4492 fps_timings->last_time = time;
4495 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
4497 const wchar_t *wmsg = wgettext(msg);
4498 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
4503 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4505 ((Game *)data)->readSettings();
4508 void Game::readSettings()
4510 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4511 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4512 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4513 m_cache_enable_particles = g_settings->getBool("enable_particles");
4514 m_cache_enable_fog = g_settings->getBool("enable_fog");
4515 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4516 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4517 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4519 m_cache_enable_noclip = g_settings->getBool("noclip");
4520 m_cache_enable_free_move = g_settings->getBool("free_move");
4522 m_cache_fog_start = g_settings->getFloat("fog_start");
4524 m_cache_cam_smoothing = 0;
4525 if (g_settings->getBool("cinematic"))
4526 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4528 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4530 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4531 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4532 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4536 /****************************************************************************/
4537 /****************************************************************************
4539 ****************************************************************************/
4540 /****************************************************************************/
4542 void Game::extendedResourceCleanup()
4544 // Extended resource accounting
4545 infostream << "Irrlicht resources after cleanup:" << std::endl;
4546 infostream << "\tRemaining meshes : "
4547 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
4548 infostream << "\tRemaining textures : "
4549 << driver->getTextureCount() << std::endl;
4551 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4552 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4553 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4557 clearTextureNameCache();
4558 infostream << "\tRemaining materials: "
4559 << driver-> getMaterialRendererCount()
4560 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4563 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4564 void Game::showPauseMenu()
4567 static const std::string control_text = strgettext("Default Controls:\n"
4568 "No menu visible:\n"
4569 "- single tap: button activate\n"
4570 "- double tap: place/use\n"
4571 "- slide finger: look around\n"
4572 "Menu/Inventory visible:\n"
4573 "- double tap (outside):\n"
4575 "- touch stack, touch slot:\n"
4577 "- touch&drag, tap 2nd finger\n"
4578 " --> place single item to slot\n"
4581 static const std::string control_text_template = strgettext("Controls:\n"
4582 "- %s: move forwards\n"
4583 "- %s: move backwards\n"
4585 "- %s: move right\n"
4586 "- %s: jump/climb\n"
4587 "- %s: sneak/go down\n"
4590 "- Mouse: turn/look\n"
4591 "- Mouse left: dig/punch\n"
4592 "- Mouse right: place/use\n"
4593 "- Mouse wheel: select item\n"
4597 char control_text_buf[600];
4599 snprintf(control_text_buf, ARRLEN(control_text_buf), control_text_template.c_str(),
4600 GET_KEY_NAME(keymap_forward),
4601 GET_KEY_NAME(keymap_backward),
4602 GET_KEY_NAME(keymap_left),
4603 GET_KEY_NAME(keymap_right),
4604 GET_KEY_NAME(keymap_jump),
4605 GET_KEY_NAME(keymap_sneak),
4606 GET_KEY_NAME(keymap_drop),
4607 GET_KEY_NAME(keymap_inventory),
4608 GET_KEY_NAME(keymap_chat)
4611 std::string control_text = std::string(control_text_buf);
4612 str_formspec_escape(control_text);
4615 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4616 std::ostringstream os;
4618 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4619 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4620 << strgettext("Continue") << "]";
4622 if (!simple_singleplayer_mode) {
4623 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4624 << strgettext("Change Password") << "]";
4626 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4630 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4631 << strgettext("Sound Volume") << "]";
4632 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4633 << strgettext("Change Keys") << "]";
4635 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4636 << strgettext("Exit to Menu") << "]";
4637 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4638 << strgettext("Exit to OS") << "]"
4639 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4640 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4642 << strgettext("Game info:") << "\n";
4643 const std::string &address = client->getAddressName();
4644 static const std::string mode = strgettext("- Mode: ");
4645 if (!simple_singleplayer_mode) {
4646 Address serverAddress = client->getServerAddress();
4647 if (address != "") {
4648 os << mode << strgettext("Remote server") << "\n"
4649 << strgettext("- Address: ") << address;
4651 os << mode << strgettext("Hosting server");
4653 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4655 os << mode << strgettext("Singleplayer") << "\n";
4657 if (simple_singleplayer_mode || address == "") {
4658 static const std::string on = strgettext("On");
4659 static const std::string off = strgettext("Off");
4660 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4661 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4662 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4663 os << strgettext("- Damage: ") << damage << "\n"
4664 << strgettext("- Creative Mode: ") << creative << "\n";
4665 if (!simple_singleplayer_mode) {
4666 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4667 os << strgettext("- PvP: ") << pvp << "\n"
4668 << strgettext("- Public: ") << announced << "\n";
4669 std::string server_name = g_settings->get("server_name");
4670 str_formspec_escape(server_name);
4671 if (announced == on && server_name != "")
4672 os << strgettext("- Server Name: ") << server_name;
4679 /* Note: FormspecFormSource and LocalFormspecHandler *
4680 * are deleted by guiFormSpecMenu */
4681 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4682 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4684 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
4685 current_formspec->setFocus("btn_continue");
4686 current_formspec->doPause = true;
4689 /****************************************************************************/
4690 /****************************************************************************
4691 extern function for launching the game
4692 ****************************************************************************/
4693 /****************************************************************************/
4695 void the_game(bool *kill,
4697 InputHandler *input,
4698 const std::string &map_dir,
4699 const std::string &playername,
4700 const std::string &password,
4701 const std::string &address, // If empty local server is created
4704 std::string &error_message,
4705 ChatBackend &chat_backend,
4706 bool *reconnect_requested,
4707 const SubgameSpec &gamespec, // Used for local game
4708 bool simple_singleplayer_mode)
4712 /* Make a copy of the server address because if a local singleplayer server
4713 * is created then this is updated and we don't want to change the value
4714 * passed to us by the calling function
4716 std::string server_address = address;
4720 if (game.startup(kill, random_input, input, map_dir,
4721 playername, password, &server_address, port, error_message,
4722 reconnect_requested, &chat_backend, gamespec,
4723 simple_singleplayer_mode)) {
4728 } catch (SerializationError &e) {
4729 error_message = std::string("A serialization error occurred:\n")
4730 + e.what() + "\n\nThe server is probably "
4731 " running a different version of " PROJECT_NAME_C ".";
4732 errorstream << error_message << std::endl;
4733 } catch (ServerError &e) {
4734 error_message = e.what();
4735 errorstream << "ServerError: " << error_message << std::endl;
4736 } catch (ModError &e) {
4737 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4738 errorstream << "ModError: " << error_message << std::endl;