3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include "client/inputhandler.h"
26 #include "client/tile.h" // For TextureSource
27 #include "client/keys.h"
28 #include "client/joystick_controller.h"
29 #include "clientmap.h"
32 #include "content_cao.h"
33 #include "drawscene.h"
34 #include "event_manager.h"
35 #include "fontengine.h"
40 #include "guiChatConsole.h"
41 #include "guiFormSpecMenu.h"
42 #include "guiKeyChangeMenu.h"
43 #include "guiPasswordChange.h"
44 #include "guiVolumeChange.h"
45 #include "mainmenumanager.h"
47 #include "nodedef.h" // Needed for determining pointing to nodes
48 #include "nodemetadata.h"
49 #include "particles.h"
51 #include "quicktune_shortcutter.h"
57 #include "util/basic_macros.h"
58 #include "util/directiontables.h"
59 #include "util/pointedthing.h"
60 #include "irrlicht_changes/static_text.h"
62 #include "script/scripting_client.h"
65 #include "sound_openal.h"
68 extern Settings *g_settings;
69 extern Profiler *g_profiler;
75 struct TextDestNodeMetadata : public TextDest
77 TextDestNodeMetadata(v3s16 p, Client *client)
82 // This is deprecated I guess? -celeron55
83 void gotText(const std::wstring &text)
85 std::string ntext = wide_to_utf8(text);
86 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
87 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
89 fields["text"] = ntext;
90 m_client->sendNodemetaFields(m_p, "", fields);
92 void gotText(const StringMap &fields)
94 m_client->sendNodemetaFields(m_p, "", fields);
101 struct TextDestPlayerInventory : public TextDest
103 TextDestPlayerInventory(Client *client)
108 TextDestPlayerInventory(Client *client, const std::string &formname)
111 m_formname = formname;
113 void gotText(const StringMap &fields)
115 m_client->sendInventoryFields(m_formname, fields);
121 struct LocalFormspecHandler : public TextDest
123 LocalFormspecHandler(const std::string &formname):
126 m_formname = formname;
129 LocalFormspecHandler(const std::string &formname, Client *client):
132 m_formname = formname;
135 void gotText(const StringMap &fields)
137 if (m_formname == "MT_PAUSE_MENU") {
138 if (fields.find("btn_sound") != fields.end()) {
139 g_gamecallback->changeVolume();
143 if (fields.find("btn_key_config") != fields.end()) {
144 g_gamecallback->keyConfig();
148 if (fields.find("btn_exit_menu") != fields.end()) {
149 g_gamecallback->disconnect();
153 if (fields.find("btn_exit_os") != fields.end()) {
154 g_gamecallback->exitToOS();
158 if (fields.find("btn_change_password") != fields.end()) {
159 g_gamecallback->changePassword();
163 if (fields.find("quit") != fields.end()) {
167 if (fields.find("btn_continue") != fields.end()) {
172 // Don't disable this part when modding is disabled, it's used in builtin
173 m_client->getScript()->on_formspec_input(m_formname, fields);
179 /* Form update callback */
181 class NodeMetadataFormSource: public IFormSource
184 NodeMetadataFormSource(ClientMap *map, v3s16 p):
189 std::string getForm()
191 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
196 return meta->getString("formspec");
199 virtual std::string resolveText(const std::string &str)
201 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
206 return meta->resolveString(str);
213 class PlayerInventoryFormSource: public IFormSource
216 PlayerInventoryFormSource(Client *client):
220 std::string getForm()
222 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
223 return player->inventory_formspec;
229 /* Profiler display */
231 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
232 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
234 if (show_profiler == 0) {
235 guitext_profiler->setVisible(false);
238 std::ostringstream os(std::ios_base::binary);
239 g_profiler->printPage(os, show_profiler, show_profiler_max);
240 std::wstring text = utf8_to_wide(os.str());
241 setStaticText(guitext_profiler, text.c_str());
242 guitext_profiler->setVisible(true);
244 s32 w = fe->getTextWidth(text.c_str());
249 unsigned text_height = fe->getTextHeight();
251 core::position2di upper_left, lower_right;
254 upper_left.Y = (text_height + 5) * 2;
255 lower_right.X = 12 + w;
256 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
258 if (lower_right.Y > screen_height * 2 / 3)
259 lower_right.Y = screen_height * 2 / 3;
261 core::rect<s32> rect(upper_left, lower_right);
263 guitext_profiler->setRelativePosition(rect);
264 guitext_profiler->setVisible(true);
272 Profiler::GraphValues values;
278 Meta(float initial = 0,
279 video::SColor color = video::SColor(255, 255, 255, 255)):
285 std::deque<Piece> m_log;
293 void put(const Profiler::GraphValues &values)
296 piece.values = values;
297 m_log.push_back(piece);
299 while (m_log.size() > m_log_max_size)
300 m_log.erase(m_log.begin());
303 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
304 gui::IGUIFont *font) const
306 // Do *not* use UNORDERED_MAP here as the order needs
307 // to be the same for each call to prevent flickering
308 std::map<std::string, Meta> m_meta;
310 for (std::deque<Piece>::const_iterator k = m_log.begin();
311 k != m_log.end(); ++k) {
312 const Piece &piece = *k;
314 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
315 i != piece.values.end(); ++i) {
316 const std::string &id = i->first;
317 const float &value = i->second;
318 std::map<std::string, Meta>::iterator j = m_meta.find(id);
320 if (j == m_meta.end()) {
321 m_meta[id] = Meta(value);
325 if (value < j->second.min)
326 j->second.min = value;
328 if (value > j->second.max)
329 j->second.max = value;
334 static const video::SColor usable_colors[] = {
335 video::SColor(255, 255, 100, 100),
336 video::SColor(255, 90, 225, 90),
337 video::SColor(255, 100, 100, 255),
338 video::SColor(255, 255, 150, 50),
339 video::SColor(255, 220, 220, 100)
341 static const u32 usable_colors_count =
342 sizeof(usable_colors) / sizeof(*usable_colors);
343 u32 next_color_i = 0;
345 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
346 i != m_meta.end(); ++i) {
347 Meta &meta = i->second;
348 video::SColor color(255, 200, 200, 200);
350 if (next_color_i < usable_colors_count)
351 color = usable_colors[next_color_i++];
357 s32 textx = x_left + m_log_max_size + 15;
358 s32 textx2 = textx + 200 - 15;
361 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
362 i != m_meta.end(); ++i) {
363 const std::string &id = i->first;
364 const Meta &meta = i->second;
366 s32 y = y_bottom - meta_i * 50;
367 float show_min = meta.min;
368 float show_max = meta.max;
370 if (show_min >= -0.0001 && show_max >= -0.0001) {
371 if (show_min <= show_max * 0.5)
377 snprintf(buf, 10, "%.3g", show_max);
378 font->draw(utf8_to_wide(buf).c_str(),
379 core::rect<s32>(textx, y - graphh,
380 textx2, y - graphh + texth),
382 snprintf(buf, 10, "%.3g", show_min);
383 font->draw(utf8_to_wide(buf).c_str(),
384 core::rect<s32>(textx, y - texth,
387 font->draw(utf8_to_wide(id).c_str(),
388 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
389 textx2, y - graphh / 2 + texth / 2),
392 s32 graph1h = graphh;
393 bool relativegraph = (show_min != 0 && show_min != show_max);
394 float lastscaledvalue = 0.0;
395 bool lastscaledvalue_exists = false;
397 for (std::deque<Piece>::const_iterator j = m_log.begin();
398 j != m_log.end(); ++j) {
399 const Piece &piece = *j;
401 bool value_exists = false;
402 Profiler::GraphValues::const_iterator k =
403 piece.values.find(id);
405 if (k != piece.values.end()) {
412 lastscaledvalue_exists = false;
416 float scaledvalue = 1.0;
418 if (show_max != show_min)
419 scaledvalue = (value - show_min) / (show_max - show_min);
421 if (scaledvalue == 1.0 && value == 0) {
423 lastscaledvalue_exists = false;
428 if (lastscaledvalue_exists) {
429 s32 ivalue1 = lastscaledvalue * graph1h;
430 s32 ivalue2 = scaledvalue * graph1h;
431 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
432 v2s32(x, graph1y - ivalue2), meta.color);
435 lastscaledvalue = scaledvalue;
436 lastscaledvalue_exists = true;
438 s32 ivalue = scaledvalue * graph1h;
439 driver->draw2DLine(v2s32(x, graph1y),
440 v2s32(x, graph1y - ivalue), meta.color);
451 class NodeDugEvent: public MtEvent
457 NodeDugEvent(v3s16 p, MapNode n):
461 const char *getType() const
469 ISoundManager *m_sound;
470 INodeDefManager *m_ndef;
472 bool makes_footstep_sound;
473 float m_player_step_timer;
475 SimpleSoundSpec m_player_step_sound;
476 SimpleSoundSpec m_player_leftpunch_sound;
477 SimpleSoundSpec m_player_rightpunch_sound;
479 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
482 makes_footstep_sound(true),
483 m_player_step_timer(0)
487 void playPlayerStep()
489 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
490 m_player_step_timer = 0.03;
491 if (makes_footstep_sound)
492 m_sound->playSound(m_player_step_sound, false);
496 static void viewBobbingStep(MtEvent *e, void *data)
498 SoundMaker *sm = (SoundMaker *)data;
499 sm->playPlayerStep();
502 static void playerRegainGround(MtEvent *e, void *data)
504 SoundMaker *sm = (SoundMaker *)data;
505 sm->playPlayerStep();
508 static void playerJump(MtEvent *e, void *data)
510 //SoundMaker *sm = (SoundMaker*)data;
513 static void cameraPunchLeft(MtEvent *e, void *data)
515 SoundMaker *sm = (SoundMaker *)data;
516 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
519 static void cameraPunchRight(MtEvent *e, void *data)
521 SoundMaker *sm = (SoundMaker *)data;
522 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
525 static void nodeDug(MtEvent *e, void *data)
527 SoundMaker *sm = (SoundMaker *)data;
528 NodeDugEvent *nde = (NodeDugEvent *)e;
529 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
532 static void playerDamage(MtEvent *e, void *data)
534 SoundMaker *sm = (SoundMaker *)data;
535 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
538 static void playerFallingDamage(MtEvent *e, void *data)
540 SoundMaker *sm = (SoundMaker *)data;
541 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
544 void registerReceiver(MtEventManager *mgr)
546 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
547 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
548 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
549 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
550 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
551 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
552 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
553 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
556 void step(float dtime)
558 m_player_step_timer -= dtime;
562 // Locally stored sounds don't need to be preloaded because of this
563 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
565 std::set<std::string> m_fetched;
567 void paths_insert(std::set<std::string> &dst_paths,
568 const std::string &base,
569 const std::string &name)
571 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
572 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
573 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
574 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
575 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
576 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
577 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
578 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
579 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
580 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
581 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
584 void fetchSounds(const std::string &name,
585 std::set<std::string> &dst_paths,
586 std::set<std::string> &dst_datas)
588 if (m_fetched.count(name))
591 m_fetched.insert(name);
593 paths_insert(dst_paths, porting::path_share, name);
594 paths_insert(dst_paths, porting::path_user, name);
599 // before 1.8 there isn't a "integer interface", only float
600 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
601 typedef f32 SamplerLayer_t;
603 typedef s32 SamplerLayer_t;
607 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
610 bool *m_force_fog_off;
613 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
614 CachedPixelShaderSetting<float> m_fog_distance;
615 CachedVertexShaderSetting<float> m_animation_timer_vertex;
616 CachedPixelShaderSetting<float> m_animation_timer_pixel;
617 CachedPixelShaderSetting<float, 3> m_day_light;
618 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
619 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
620 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
621 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
622 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
623 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
627 void onSettingsChange(const std::string &name)
629 if (name == "enable_fog")
630 m_fog_enabled = g_settings->getBool("enable_fog");
633 static void settingsCallback(const std::string &name, void *userdata)
635 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
638 void setSky(Sky *sky) { m_sky = sky; }
640 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
641 f32 *fog_range, Client *client) :
643 m_force_fog_off(force_fog_off),
644 m_fog_range(fog_range),
645 m_sky_bg_color("skyBgColor"),
646 m_fog_distance("fogDistance"),
647 m_animation_timer_vertex("animationTimer"),
648 m_animation_timer_pixel("animationTimer"),
649 m_day_light("dayLight"),
650 m_eye_position_pixel("eyePosition"),
651 m_eye_position_vertex("eyePosition"),
652 m_minimap_yaw("yawVec"),
653 m_base_texture("baseTexture"),
654 m_normal_texture("normalTexture"),
655 m_texture_flags("textureFlags"),
658 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
659 m_fog_enabled = g_settings->getBool("enable_fog");
662 ~GameGlobalShaderConstantSetter()
664 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
667 virtual void onSetConstants(video::IMaterialRendererServices *services,
674 video::SColor bgcolor = m_sky->getBgColor();
675 video::SColorf bgcolorf(bgcolor);
676 float bgcolorfa[4] = {
682 m_sky_bg_color.set(bgcolorfa, services);
685 float fog_distance = 10000 * BS;
687 if (m_fog_enabled && !*m_force_fog_off)
688 fog_distance = *m_fog_range;
690 m_fog_distance.set(&fog_distance, services);
692 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
693 video::SColorf sunlight;
694 get_sunlight_color(&sunlight, daynight_ratio);
699 m_day_light.set(dnc, services);
701 u32 animation_timer = porting::getTimeMs() % 100000;
702 float animation_timer_f = (float)animation_timer / 100000.f;
703 m_animation_timer_vertex.set(&animation_timer_f, services);
704 m_animation_timer_pixel.set(&animation_timer_f, services);
706 float eye_position_array[3];
707 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
708 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
709 eye_position_array[0] = epos.X;
710 eye_position_array[1] = epos.Y;
711 eye_position_array[2] = epos.Z;
713 epos.getAs3Values(eye_position_array);
715 m_eye_position_pixel.set(eye_position_array, services);
716 m_eye_position_vertex.set(eye_position_array, services);
718 float minimap_yaw_array[3];
719 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
720 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
721 minimap_yaw_array[0] = minimap_yaw.X;
722 minimap_yaw_array[1] = minimap_yaw.Y;
723 minimap_yaw_array[2] = minimap_yaw.Z;
725 minimap_yaw.getAs3Values(minimap_yaw_array);
727 m_minimap_yaw.set(minimap_yaw_array, services);
729 SamplerLayer_t base_tex = 0,
732 m_base_texture.set(&base_tex, services);
733 m_normal_texture.set(&normal_tex, services);
734 m_texture_flags.set(&flags_tex, services);
739 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
742 bool *m_force_fog_off;
745 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
747 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
748 f32 *fog_range, Client *client) :
750 m_force_fog_off(force_fog_off),
751 m_fog_range(fog_range),
755 void setSky(Sky *sky) {
757 for (size_t i = 0; i < created_nosky.size(); ++i) {
758 created_nosky[i]->setSky(m_sky);
760 created_nosky.clear();
763 virtual IShaderConstantSetter* create()
765 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
766 m_sky, m_force_fog_off, m_fog_range, m_client);
768 created_nosky.push_back(scs);
774 bool nodePlacementPrediction(Client &client,
775 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
777 std::string prediction = playeritem_def.node_placement_prediction;
778 INodeDefManager *nodedef = client.ndef();
779 ClientMap &map = client.getEnv().getClientMap();
781 bool is_valid_position;
783 node = map.getNodeNoEx(nodepos, &is_valid_position);
784 if (!is_valid_position)
787 if (prediction != "" && !nodedef->get(node).rightclickable) {
788 verbosestream << "Node placement prediction for "
789 << playeritem_def.name << " is "
790 << prediction << std::endl;
791 v3s16 p = neighbourpos;
793 // Place inside node itself if buildable_to
794 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
795 if (is_valid_position)
797 if (nodedef->get(n_under).buildable_to)
800 node = map.getNodeNoEx(p, &is_valid_position);
801 if (is_valid_position &&!nodedef->get(node).buildable_to)
806 // Find id of predicted node
808 bool found = nodedef->getId(prediction, id);
811 errorstream << "Node placement prediction failed for "
812 << playeritem_def.name << " (places "
814 << ") - Name not known" << std::endl;
818 // Predict param2 for facedir and wallmounted nodes
821 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
822 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED) {
823 v3s16 dir = nodepos - neighbourpos;
825 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
826 param2 = dir.Y < 0 ? 1 : 0;
827 } else if (abs(dir.X) > abs(dir.Z)) {
828 param2 = dir.X < 0 ? 3 : 2;
830 param2 = dir.Z < 0 ? 5 : 4;
834 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR ||
835 nodedef->get(id).param_type_2 == CPT2_COLORED_FACEDIR) {
836 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
838 if (abs(dir.X) > abs(dir.Z)) {
839 param2 = dir.X < 0 ? 3 : 1;
841 param2 = dir.Z < 0 ? 2 : 0;
847 //Check attachment if node is in group attached_node
848 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
849 static v3s16 wallmounted_dirs[8] = {
859 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
860 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED)
861 pp = p + wallmounted_dirs[param2];
863 pp = p + v3s16(0, -1, 0);
865 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
869 // Add node to client map
870 MapNode n(id, 0, param2);
873 LocalPlayer *player = client.getEnv().getLocalPlayer();
875 // Dont place node when player would be inside new node
876 // NOTE: This is to be eventually implemented by a mod as client-side Lua
877 if (!nodedef->get(n).walkable ||
878 g_settings->getBool("enable_build_where_you_stand") ||
879 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
880 (nodedef->get(n).walkable &&
881 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
882 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
884 // This triggers the required mesh update too
885 client.addNode(p, n);
888 } catch (InvalidPositionException &e) {
889 errorstream << "Node placement prediction failed for "
890 << playeritem_def.name << " (places "
892 << ") - Position not loaded" << std::endl;
899 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
900 Client *client, IrrlichtDevice *device, JoystickController *joystick,
901 IFormSource *fs_src, TextDest *txt_dest)
904 if (*cur_formspec == 0) {
905 *cur_formspec = new GUIFormSpecMenu(device, joystick,
906 guiroot, -1, &g_menumgr, client, client->getTextureSource(),
908 (*cur_formspec)->doPause = false;
911 Caution: do not call (*cur_formspec)->drop() here --
912 the reference might outlive the menu, so we will
913 periodically check if *cur_formspec is the only
914 remaining reference (i.e. the menu was removed)
915 and delete it in that case.
919 (*cur_formspec)->setFormSource(fs_src);
920 (*cur_formspec)->setTextDest(txt_dest);
926 #define SIZE_TAG "size[11,5.5]"
928 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
931 /******************************************************************************/
932 static void updateChat(Client &client, f32 dtime, bool show_debug,
933 const v2u32 &screensize, bool show_chat, u32 show_profiler,
934 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
936 // Add chat log output for errors to be shown in chat
937 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
939 // Get new messages from error log buffer
940 while (!chat_log_error_buf.empty()) {
941 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
942 if (!g_settings->getBool("disable_escape_sequences")) {
943 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
945 chat_backend.addMessage(L"", error_message);
948 // Get new messages from client
949 std::wstring message;
951 while (client.getChatMessage(message)) {
952 chat_backend.addUnparsedMessage(message);
955 // Remove old messages
956 chat_backend.step(dtime);
958 // Display all messages in a static text element
959 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
960 EnrichedString recent_chat = chat_backend.getRecentChat();
961 unsigned int line_height = g_fontengine->getLineHeight();
963 setStaticText(guitext_chat, recent_chat);
965 // Update gui element size and position
969 chat_y += 2 * line_height;
971 // first pass to calculate height of text to be set
972 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
973 porting::getWindowSize().X - 20);
974 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
975 guitext_chat->setRelativePosition(rect);
977 //now use real height of text and adjust rect according to this size
978 rect = core::rect<s32>(10, chat_y, width,
979 chat_y + guitext_chat->getTextHeight());
982 guitext_chat->setRelativePosition(rect);
983 // Don't show chat if disabled or empty or profiler is enabled
984 guitext_chat->setVisible(
985 show_chat && recent_chat_count != 0 && !show_profiler);
989 /****************************************************************************
990 Fast key cache for main game loop
991 ****************************************************************************/
993 /* This is faster than using getKeySetting with the tradeoff that functions
994 * using it must make sure that it's initialised before using it and there is
995 * no error handling (for example bounds checking). This is really intended for
996 * use only in the main running loop of the client (the_game()) where the faster
997 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
998 * (e.g. formspecs) should continue using getKeySetting().
1006 populate_nonchanging();
1011 // Keys that are not settings dependent
1012 void populate_nonchanging();
1014 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1015 InputHandler *handler;
1018 void KeyCache::populate_nonchanging()
1020 key[KeyType::ESC] = EscapeKey;
1023 void KeyCache::populate()
1025 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1026 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1027 key[KeyType::LEFT] = getKeySetting("keymap_left");
1028 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1029 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1030 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1031 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1033 key[KeyType::AUTORUN] = getKeySetting("keymap_autorun");
1035 key[KeyType::DROP] = getKeySetting("keymap_drop");
1036 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1037 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1038 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1039 key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
1040 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1041 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1042 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1043 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1044 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1045 key[KeyType::HOTBAR_PREV] = getKeySetting("keymap_hotbar_previous");
1046 key[KeyType::HOTBAR_NEXT] = getKeySetting("keymap_hotbar_next");
1047 key[KeyType::MUTE] = getKeySetting("keymap_mute");
1048 key[KeyType::INC_VOLUME] = getKeySetting("keymap_increase_volume");
1049 key[KeyType::DEC_VOLUME] = getKeySetting("keymap_decrease_volume");
1050 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1051 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1052 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1053 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1054 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1055 = getKeySetting("keymap_toggle_force_fog_off");
1056 key[KeyType::TOGGLE_UPDATE_CAMERA]
1057 = getKeySetting("keymap_toggle_update_camera");
1058 key[KeyType::TOGGLE_DEBUG]
1059 = getKeySetting("keymap_toggle_debug");
1060 key[KeyType::TOGGLE_PROFILER]
1061 = getKeySetting("keymap_toggle_profiler");
1062 key[KeyType::CAMERA_MODE]
1063 = getKeySetting("keymap_camera_mode");
1064 key[KeyType::INCREASE_VIEWING_RANGE]
1065 = getKeySetting("keymap_increase_viewing_range_min");
1066 key[KeyType::DECREASE_VIEWING_RANGE]
1067 = getKeySetting("keymap_decrease_viewing_range_min");
1068 key[KeyType::RANGESELECT]
1069 = getKeySetting("keymap_rangeselect");
1070 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1072 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1073 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1074 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1075 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1077 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1080 // First clear all keys, then re-add the ones we listen for
1081 handler->dontListenForKeys();
1082 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1083 handler->listenForKey(key[i]);
1085 handler->listenForKey(EscapeKey);
1086 handler->listenForKey(CancelKey);
1087 for (size_t i = 0; i < 10; i++) {
1088 handler->listenForKey(NumberKey[i]);
1094 /****************************************************************************
1096 ****************************************************************************/
1098 const float object_hit_delay = 0.2;
1101 u32 last_time, busy_time, sleep_time;
1105 /* The reason the following structs are not anonymous structs within the
1106 * class is that they are not used by the majority of member functions and
1107 * many functions that do require objects of thse types do not modify them
1108 * (so they can be passed as a const qualified parameter)
1110 struct CameraOrientation {
1111 f32 camera_yaw; // "right/left"
1112 f32 camera_pitch; // "up/down"
1115 struct GameRunData {
1118 PointedThing pointed_old;
1123 bool update_wielded_item_trigger;
1124 bool reset_jump_timer;
1125 float nodig_delay_timer;
1127 float dig_time_complete;
1128 float repeat_rightclick_timer;
1129 float object_hit_delay_timer;
1130 float time_from_last_punch;
1131 ClientActiveObject *selected_object;
1135 float update_draw_list_timer;
1136 float statustext_time;
1140 v3f update_draw_list_last_cam_dir;
1142 u32 profiler_current_page;
1143 u32 profiler_max_page; // Number of pages
1146 float time_of_day_smooth;
1150 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1156 Jitter dtime_jitter, busy_time_jitter;
1159 /****************************************************************************
1161 ****************************************************************************/
1163 /* This is not intended to be a public class. If a public class becomes
1164 * desirable then it may be better to create another 'wrapper' class that
1165 * hides most of the stuff in this class (nothing in this class is required
1166 * by any other file) but exposes the public methods/data only.
1173 bool startup(bool *kill,
1175 InputHandler *input,
1176 IrrlichtDevice *device,
1177 const std::string &map_dir,
1178 const std::string &playername,
1179 const std::string &password,
1180 // If address is "", local server is used and address is updated
1181 std::string *address,
1183 std::string &error_message,
1185 ChatBackend *chat_backend,
1186 const SubgameSpec &gamespec, // Used for local game
1187 bool simple_singleplayer_mode);
1194 void extendedResourceCleanup();
1196 // Basic initialisation
1197 bool init(const std::string &map_dir, std::string *address,
1199 const SubgameSpec &gamespec);
1201 bool createSingleplayerServer(const std::string &map_dir,
1202 const SubgameSpec &gamespec, u16 port, std::string *address);
1205 bool createClient(const std::string &playername,
1206 const std::string &password, std::string *address, u16 port);
1209 // Client connection
1210 bool connectToServer(const std::string &playername,
1211 const std::string &password, std::string *address, u16 port,
1212 bool *connect_ok, bool *aborted);
1213 bool getServerContent(bool *aborted);
1217 void updateInteractTimers(f32 dtime);
1218 bool checkConnection();
1219 bool handleCallbacks();
1220 void processQueues();
1221 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1222 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1223 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1226 void processUserInput(f32 dtime);
1227 void processKeyInput();
1228 void processItemSelection(u16 *new_playeritem);
1230 void dropSelectedItem();
1231 void openInventory();
1232 void openConsole(float scale, const wchar_t *line=NULL);
1233 void toggleFreeMove();
1234 void toggleFreeMoveAlt();
1236 void toggleNoClip();
1237 void toggleCinematic();
1238 void toggleAutorun();
1242 void toggleMinimap(bool shift_pressed);
1245 void toggleUpdateCamera();
1246 void toggleProfiler();
1248 void increaseViewRange();
1249 void decreaseViewRange();
1250 void toggleFullViewRange();
1252 void updateCameraDirection(CameraOrientation *cam, float dtime);
1253 void updateCameraOrientation(CameraOrientation *cam, float dtime);
1254 void updatePlayerControl(const CameraOrientation &cam);
1255 void step(f32 *dtime);
1256 void processClientEvents(CameraOrientation *cam);
1257 void updateCamera(u32 busy_time, f32 dtime);
1258 void updateSound(f32 dtime);
1259 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
1261 * Returns the object or node the player is pointing at.
1262 * Also updates the selected thing in the Hud.
1264 * @param[in] shootline the shootline, starting from
1265 * the camera position. This also gives the maximal distance
1267 * @param[in] liquids_pointable if false, liquids are ignored
1268 * @param[in] look_for_object if false, objects are ignored
1269 * @param[in] camera_offset offset of the camera
1270 * @param[out] selected_object the selected object or
1273 PointedThing updatePointedThing(
1274 const core::line3d<f32> &shootline, bool liquids_pointable,
1275 bool look_for_object, const v3s16 &camera_offset);
1276 void handlePointingAtNothing(const ItemStack &playerItem);
1277 void handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
1278 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1279 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
1280 const v3f &player_position, bool show_debug);
1281 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
1282 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1283 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
1284 const CameraOrientation &cam);
1285 void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
1286 void updateProfilerGraphs(ProfilerGraph *graph);
1289 void limitFps(FpsControl *fps_timings, f32 *dtime);
1291 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1292 bool draw_clouds = true);
1294 static void settingChangedCallback(const std::string &setting_name, void *data);
1295 void readSettings();
1297 inline bool getLeftClicked()
1299 return input->getLeftClicked() ||
1300 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1302 inline bool getRightClicked()
1304 return input->getRightClicked() ||
1305 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1307 inline bool isLeftPressed()
1309 return input->getLeftState() ||
1310 input->joystick.isKeyDown(KeyType::MOUSE_L);
1312 inline bool isRightPressed()
1314 return input->getRightState() ||
1315 input->joystick.isKeyDown(KeyType::MOUSE_R);
1317 inline bool getLeftReleased()
1319 return input->getLeftReleased() ||
1320 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1323 inline bool isKeyDown(GameKeyType k)
1325 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1327 inline bool wasKeyDown(GameKeyType k)
1329 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1333 void handleAndroidChatInput();
1337 void showPauseMenu();
1339 InputHandler *input;
1344 IWritableTextureSource *texture_src;
1345 IWritableShaderSource *shader_src;
1347 // When created, these will be filled with data received from the server
1348 IWritableItemDefManager *itemdef_manager;
1349 IWritableNodeDefManager *nodedef_manager;
1351 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1352 ISoundManager *sound;
1353 bool sound_is_dummy;
1354 SoundMaker *soundmaker;
1356 ChatBackend *chat_backend;
1358 GUIFormSpecMenu *current_formspec;
1359 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1360 std::string cur_formname;
1362 EventManager *eventmgr;
1363 QuicktuneShortcutter *quicktune;
1365 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1366 MapDrawControl *draw_control;
1368 Clouds *clouds; // Free using ->Drop()
1369 Sky *sky; // Free using ->Drop()
1370 Inventory *local_inventory;
1374 GameRunData runData;
1378 This class does take ownership/responsibily for cleaning up etc of any of
1379 these items (e.g. device)
1381 IrrlichtDevice *device;
1382 video::IVideoDriver *driver;
1383 scene::ISceneManager *smgr;
1385 std::string *error_message;
1386 bool *reconnect_requested;
1387 scene::ISceneNode *skybox;
1390 bool simple_singleplayer_mode;
1393 /* Pre-calculated values
1395 int crack_animation_length;
1399 gui::IGUIStaticText *guitext; // First line of debug text
1400 gui::IGUIStaticText *guitext2; // Second line of debug text
1401 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1402 gui::IGUIStaticText *guitext_status;
1403 gui::IGUIStaticText *guitext_chat; // Chat text
1404 gui::IGUIStaticText *guitext_profiler; // Profiler text
1406 std::wstring infotext;
1407 std::wstring m_statustext;
1411 IntervalLimiter profiler_interval;
1414 * TODO: Local caching of settings is not optimal and should at some stage
1415 * be updated to use a global settings object for getting thse values
1416 * (as opposed to the this local caching). This can be addressed in
1419 bool m_cache_doubletap_jump;
1420 bool m_cache_enable_clouds;
1421 bool m_cache_enable_joysticks;
1422 bool m_cache_enable_particles;
1423 bool m_cache_enable_fog;
1424 bool m_cache_enable_noclip;
1425 bool m_cache_enable_free_move;
1426 f32 m_cache_mouse_sensitivity;
1427 f32 m_cache_joystick_frustum_sensitivity;
1428 f32 m_repeat_right_click_time;
1429 f32 m_cache_cam_smoothing;
1430 f32 m_cache_fog_start;
1432 bool m_invert_mouse;
1433 bool m_first_loop_after_window_activation;
1434 bool m_camera_offset_changed;
1437 bool m_cache_hold_aux1;
1438 bool m_android_chat_open;
1447 itemdef_manager(NULL),
1448 nodedef_manager(NULL),
1450 sound_is_dummy(false),
1453 current_formspec(NULL),
1457 gui_chat_console(NULL),
1462 local_inventory(NULL),
1465 m_invert_mouse(false),
1466 m_first_loop_after_window_activation(false),
1467 m_camera_offset_changed(false)
1469 g_settings->registerChangedCallback("doubletap_jump",
1470 &settingChangedCallback, this);
1471 g_settings->registerChangedCallback("enable_clouds",
1472 &settingChangedCallback, this);
1473 g_settings->registerChangedCallback("doubletap_joysticks",
1474 &settingChangedCallback, this);
1475 g_settings->registerChangedCallback("enable_particles",
1476 &settingChangedCallback, this);
1477 g_settings->registerChangedCallback("enable_fog",
1478 &settingChangedCallback, this);
1479 g_settings->registerChangedCallback("mouse_sensitivity",
1480 &settingChangedCallback, this);
1481 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1482 &settingChangedCallback, this);
1483 g_settings->registerChangedCallback("repeat_rightclick_time",
1484 &settingChangedCallback, this);
1485 g_settings->registerChangedCallback("noclip",
1486 &settingChangedCallback, this);
1487 g_settings->registerChangedCallback("free_move",
1488 &settingChangedCallback, this);
1489 g_settings->registerChangedCallback("cinematic",
1490 &settingChangedCallback, this);
1491 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1492 &settingChangedCallback, this);
1493 g_settings->registerChangedCallback("camera_smoothing",
1494 &settingChangedCallback, this);
1499 m_cache_hold_aux1 = false; // This is initialised properly later
1506 /****************************************************************************
1508 ****************************************************************************/
1514 if (!sound_is_dummy)
1517 delete server; // deleted first to stop all server threads
1520 delete local_inventory;
1526 delete nodedef_manager;
1527 delete itemdef_manager;
1528 delete draw_control;
1530 extendedResourceCleanup();
1532 g_settings->deregisterChangedCallback("doubletap_jump",
1533 &settingChangedCallback, this);
1534 g_settings->deregisterChangedCallback("enable_clouds",
1535 &settingChangedCallback, this);
1536 g_settings->deregisterChangedCallback("enable_particles",
1537 &settingChangedCallback, this);
1538 g_settings->deregisterChangedCallback("enable_fog",
1539 &settingChangedCallback, this);
1540 g_settings->deregisterChangedCallback("mouse_sensitivity",
1541 &settingChangedCallback, this);
1542 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1543 &settingChangedCallback, this);
1544 g_settings->deregisterChangedCallback("noclip",
1545 &settingChangedCallback, this);
1546 g_settings->deregisterChangedCallback("free_move",
1547 &settingChangedCallback, this);
1548 g_settings->deregisterChangedCallback("cinematic",
1549 &settingChangedCallback, this);
1550 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1551 &settingChangedCallback, this);
1552 g_settings->deregisterChangedCallback("camera_smoothing",
1553 &settingChangedCallback, this);
1556 bool Game::startup(bool *kill,
1558 InputHandler *input,
1559 IrrlichtDevice *device,
1560 const std::string &map_dir,
1561 const std::string &playername,
1562 const std::string &password,
1563 std::string *address, // can change if simple_singleplayer_mode
1565 std::string &error_message,
1567 ChatBackend *chat_backend,
1568 const SubgameSpec &gamespec,
1569 bool simple_singleplayer_mode)
1572 this->device = device;
1574 this->error_message = &error_message;
1575 this->reconnect_requested = reconnect;
1576 this->random_input = random_input;
1577 this->input = input;
1578 this->chat_backend = chat_backend;
1579 this->simple_singleplayer_mode = simple_singleplayer_mode;
1581 keycache.handler = input;
1582 keycache.populate();
1584 driver = device->getVideoDriver();
1585 smgr = device->getSceneManager();
1587 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1589 memset(&runData, 0, sizeof(runData));
1590 runData.time_from_last_punch = 10.0;
1591 runData.profiler_max_page = 3;
1592 runData.update_wielded_item_trigger = true;
1594 memset(&flags, 0, sizeof(flags));
1595 flags.show_chat = true;
1596 flags.show_hud = true;
1597 flags.show_debug = g_settings->getBool("show_debug");
1598 m_invert_mouse = g_settings->getBool("invert_mouse");
1599 m_first_loop_after_window_activation = true;
1601 if (!init(map_dir, address, port, gamespec))
1604 if (!createClient(playername, password, address, port))
1613 ProfilerGraph graph;
1614 RunStats stats = { 0 };
1615 CameraOrientation cam_view_target = { 0 };
1616 CameraOrientation cam_view = { 0 };
1617 FpsControl draw_times = { 0 };
1618 f32 dtime; // in seconds
1620 /* Clear the profiler */
1621 Profiler::GraphValues dummyvalues;
1622 g_profiler->graphGet(dummyvalues);
1624 draw_times.last_time = device->getTimer()->getTime();
1626 set_light_table(g_settings->getFloat("display_gamma"));
1629 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1630 && client->checkPrivilege("fast");
1633 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screenW"),
1634 g_settings->getU16("screenH"));
1636 while (device->run()
1637 && !(*kill || g_gamecallback->shutdown_requested
1638 || (server && server->getShutdownRequested()))) {
1640 const irr::core::dimension2d<u32> ¤t_screen_size =
1641 device->getVideoDriver()->getScreenSize();
1642 // Verify if window size has changed and save it if it's the case
1643 // Ensure evaluating settings->getBool after verifying screensize
1644 // First condition is cheaper
1645 if (previous_screen_size != current_screen_size &&
1646 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1647 g_settings->getBool("autosave_screensize")) {
1648 g_settings->setU16("screenW", current_screen_size.Width);
1649 g_settings->setU16("screenH", current_screen_size.Height);
1650 previous_screen_size = current_screen_size;
1653 /* Must be called immediately after a device->run() call because it
1654 * uses device->getTimer()->getTime()
1656 limitFps(&draw_times, &dtime);
1658 updateStats(&stats, draw_times, dtime);
1659 updateInteractTimers(dtime);
1661 if (!checkConnection())
1663 if (!handleCallbacks())
1669 hud->resizeHotbar();
1671 updateProfilers(stats, draw_times, dtime);
1672 processUserInput(dtime);
1673 // Update camera before player movement to avoid camera lag of one frame
1674 updateCameraDirection(&cam_view_target, dtime);
1675 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1676 cam_view.camera_yaw) * m_cache_cam_smoothing;
1677 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1678 cam_view.camera_pitch) * m_cache_cam_smoothing;
1679 updatePlayerControl(cam_view);
1681 processClientEvents(&cam_view_target);
1682 updateCamera(draw_times.busy_time, dtime);
1684 processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
1685 updateFrame(&graph, &stats, dtime, cam_view);
1686 updateProfilerGraphs(&graph);
1688 // Update if minimap has been disabled by the server
1689 flags.show_minimap &= client->shouldShowMinimap();
1694 void Game::shutdown()
1696 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1697 if (g_settings->get("3d_mode") == "pageflip") {
1698 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1702 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1707 if (gui_chat_console)
1708 gui_chat_console->drop();
1714 while (g_menumgr.menuCount() > 0) {
1715 g_menumgr.m_stack.front()->setVisible(false);
1716 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1719 if (current_formspec) {
1720 current_formspec->drop();
1721 current_formspec = NULL;
1724 chat_backend->addMessage(L"", L"# Disconnected.");
1725 chat_backend->addMessage(L"", L"");
1729 while (!client->isShutdown()) {
1730 assert(texture_src != NULL);
1731 assert(shader_src != NULL);
1732 texture_src->processQueue();
1733 shader_src->processQueue();
1740 /****************************************************************************/
1741 /****************************************************************************
1743 ****************************************************************************/
1744 /****************************************************************************/
1747 const std::string &map_dir,
1748 std::string *address,
1750 const SubgameSpec &gamespec)
1752 texture_src = createTextureSource(device);
1754 showOverlayMessage(wgettext("Loading..."), 0, 0);
1756 shader_src = createShaderSource(device);
1758 itemdef_manager = createItemDefManager();
1759 nodedef_manager = createNodeDefManager();
1761 eventmgr = new EventManager();
1762 quicktune = new QuicktuneShortcutter();
1764 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1765 && eventmgr && quicktune))
1771 // Create a server if not connecting to an existing one
1772 if (*address == "") {
1773 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1780 bool Game::initSound()
1783 if (g_settings->getBool("enable_sound")) {
1784 infostream << "Attempting to use OpenAL audio" << std::endl;
1785 sound = createOpenALSoundManager(&soundfetcher);
1787 infostream << "Failed to initialize OpenAL audio" << std::endl;
1789 infostream << "Sound disabled." << std::endl;
1793 infostream << "Using dummy audio." << std::endl;
1794 sound = &dummySoundManager;
1795 sound_is_dummy = true;
1798 soundmaker = new SoundMaker(sound, nodedef_manager);
1802 soundmaker->registerReceiver(eventmgr);
1807 bool Game::createSingleplayerServer(const std::string &map_dir,
1808 const SubgameSpec &gamespec, u16 port, std::string *address)
1810 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1812 std::string bind_str = g_settings->get("bind_address");
1813 Address bind_addr(0, 0, 0, 0, port);
1815 if (g_settings->getBool("ipv6_server")) {
1816 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1820 bind_addr.Resolve(bind_str.c_str());
1821 } catch (ResolveError &e) {
1822 infostream << "Resolving bind address \"" << bind_str
1823 << "\" failed: " << e.what()
1824 << " -- Listening on all addresses." << std::endl;
1827 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1828 *error_message = "Unable to listen on " +
1829 bind_addr.serializeString() +
1830 " because IPv6 is disabled";
1831 errorstream << *error_message << std::endl;
1835 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1836 bind_addr.isIPv6(), false);
1838 server->start(bind_addr);
1843 bool Game::createClient(const std::string &playername,
1844 const std::string &password, std::string *address, u16 port)
1846 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1848 draw_control = new MapDrawControl;
1852 bool could_connect, connect_aborted;
1854 if (!connectToServer(playername, password, address, port,
1855 &could_connect, &connect_aborted))
1858 if (!could_connect) {
1859 if (error_message->empty() && !connect_aborted) {
1860 // Should not happen if error messages are set properly
1861 *error_message = "Connection failed for unknown reason";
1862 errorstream << *error_message << std::endl;
1867 if (!getServerContent(&connect_aborted)) {
1868 if (error_message->empty() && !connect_aborted) {
1869 // Should not happen if error messages are set properly
1870 *error_message = "Connection failed for unknown reason";
1871 errorstream << *error_message << std::endl;
1876 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1877 &flags.force_fog_off, &runData.fog_range, client);
1878 shader_src->addShaderConstantSetterFactory(scsf);
1880 // Update cached textures, meshes and materials
1881 client->afterContentReceived(device);
1885 camera = new Camera(smgr, *draw_control, client);
1886 if (!camera || !camera->successfullyCreated(*error_message))
1888 client->setCamera(camera);
1892 if (m_cache_enable_clouds) {
1893 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1895 *error_message = "Memory allocation error (clouds)";
1896 errorstream << *error_message << std::endl;
1903 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
1905 skybox = NULL; // This is used/set later on in the main run loop
1907 local_inventory = new Inventory(itemdef_manager);
1909 if (!(sky && local_inventory)) {
1910 *error_message = "Memory allocation error (sky or local inventory)";
1911 errorstream << *error_message << std::endl;
1915 /* Pre-calculated values
1917 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1919 v2u32 size = t->getOriginalSize();
1920 crack_animation_length = size.Y / size.X;
1922 crack_animation_length = 5;
1928 /* Set window caption
1930 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1932 str += utf8_to_wide(g_version_hash);
1934 str += driver->getName();
1936 device->setWindowCaption(str.c_str());
1938 LocalPlayer *player = client->getEnv().getLocalPlayer();
1939 player->hurt_tilt_timer = 0;
1940 player->hurt_tilt_strength = 0;
1942 hud = new Hud(driver, smgr, guienv, client, player, local_inventory);
1945 *error_message = "Memory error: could not create HUD";
1946 errorstream << *error_message << std::endl;
1950 mapper = client->getMinimap();
1951 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1956 bool Game::initGui()
1958 // First line of debug text
1959 guitext = addStaticText(guienv,
1960 utf8_to_wide(PROJECT_NAME_C).c_str(),
1961 core::rect<s32>(0, 0, 0, 0),
1962 false, false, guiroot);
1964 // Second line of debug text
1965 guitext2 = addStaticText(guienv,
1967 core::rect<s32>(0, 0, 0, 0),
1968 false, false, guiroot);
1970 // At the middle of the screen
1971 // Object infos are shown in this
1972 guitext_info = addStaticText(guienv,
1974 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
1975 false, true, guiroot);
1977 // Status text (displays info when showing and hiding GUI stuff, etc.)
1978 guitext_status = addStaticText(guienv,
1980 core::rect<s32>(0, 0, 0, 0),
1981 false, false, guiroot);
1982 guitext_status->setVisible(false);
1985 guitext_chat = addStaticText(
1988 core::rect<s32>(0, 0, 0, 0),
1989 //false, false); // Disable word wrap as of now
1990 false, true, guiroot);
1992 // Remove stale "recent" chat messages from previous connections
1993 chat_backend->clearRecentChat();
1995 // Chat backend and console
1996 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
1997 -1, chat_backend, client, &g_menumgr);
1998 if (!gui_chat_console) {
1999 *error_message = "Could not allocate memory for chat console";
2000 errorstream << *error_message << std::endl;
2004 // Profiler text (size is updated when text is updated)
2005 guitext_profiler = addStaticText(guienv,
2007 core::rect<s32>(0, 0, 0, 0),
2008 false, false, guiroot);
2009 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2010 guitext_profiler->setVisible(false);
2011 guitext_profiler->setWordWrap(true);
2013 #ifdef HAVE_TOUCHSCREENGUI
2015 if (g_touchscreengui)
2016 g_touchscreengui->init(texture_src);
2023 bool Game::connectToServer(const std::string &playername,
2024 const std::string &password, std::string *address, u16 port,
2025 bool *connect_ok, bool *aborted)
2027 *connect_ok = false; // Let's not be overly optimistic
2029 bool local_server_mode = false;
2031 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2033 Address connect_address(0, 0, 0, 0, port);
2036 connect_address.Resolve(address->c_str());
2038 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2039 //connect_address.Resolve("localhost");
2040 if (connect_address.isIPv6()) {
2041 IPv6AddressBytes addr_bytes;
2042 addr_bytes.bytes[15] = 1;
2043 connect_address.setAddress(&addr_bytes);
2045 connect_address.setAddress(127, 0, 0, 1);
2047 local_server_mode = true;
2049 } catch (ResolveError &e) {
2050 *error_message = std::string("Couldn't resolve address: ") + e.what();
2051 errorstream << *error_message << std::endl;
2055 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2056 *error_message = "Unable to connect to " +
2057 connect_address.serializeString() +
2058 " because IPv6 is disabled";
2059 errorstream << *error_message << std::endl;
2063 client = new Client(device,
2064 playername.c_str(), password, *address,
2065 *draw_control, texture_src, shader_src,
2066 itemdef_manager, nodedef_manager, sound, eventmgr,
2067 connect_address.isIPv6(), &flags);
2072 infostream << "Connecting to server at ";
2073 connect_address.print(&infostream);
2074 infostream << std::endl;
2076 client->connect(connect_address,
2077 simple_singleplayer_mode || local_server_mode);
2080 Wait for server to accept connection
2086 FpsControl fps_control = { 0 };
2088 f32 wait_time = 0; // in seconds
2090 fps_control.last_time = device->getTimer()->getTime();
2094 while (device->run()) {
2096 limitFps(&fps_control, &dtime);
2098 // Update client and server
2099 client->step(dtime);
2102 server->step(dtime);
2105 if (client->getState() == LC_Init) {
2111 if (client->accessDenied()) {
2112 *error_message = "Access denied. Reason: "
2113 + client->accessDeniedReason();
2114 *reconnect_requested = client->reconnectRequested();
2115 errorstream << *error_message << std::endl;
2119 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2121 infostream << "Connect aborted [Escape]" << std::endl;
2126 // Only time out if we aren't waiting for the server we started
2127 if ((*address != "") && (wait_time > 10)) {
2128 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2129 // If no pre v25 init was sent, and no answer was received,
2130 // but the low level connection could be established
2131 // (meaning that we have a peer id), then we probably wanted
2132 // to connect to a legacy server. In this case, tell the user
2133 // to enable the option to be able to connect.
2134 if (!sent_old_init &&
2135 (client->getProtoVersion() == 0) &&
2136 client->connectedToServer()) {
2137 *error_message = "Connection failure: init packet not "
2138 "recognized by server.\n"
2139 "Most likely the server uses an old protocol version (<v25).\n"
2140 "Please ask the server owner to update to 0.4.13 or later.\n"
2141 "To still connect to the server in the meantime,\n"
2142 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2143 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2144 "entry in the advanced settings menu.";
2146 *error_message = "Connection timed out.";
2148 errorstream << *error_message << std::endl;
2153 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2155 } catch (con::PeerNotFoundException &e) {
2156 // TODO: Should something be done here? At least an info/error
2164 bool Game::getServerContent(bool *aborted)
2168 FpsControl fps_control = { 0 };
2169 f32 dtime; // in seconds
2171 fps_control.last_time = device->getTimer()->getTime();
2173 while (device->run()) {
2175 limitFps(&fps_control, &dtime);
2177 // Update client and server
2178 client->step(dtime);
2181 server->step(dtime);
2184 if (client->mediaReceived() && client->itemdefReceived() &&
2185 client->nodedefReceived()) {
2190 if (!checkConnection())
2193 if (client->getState() < LC_Init) {
2194 *error_message = "Client disconnected";
2195 errorstream << *error_message << std::endl;
2199 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2201 infostream << "Connect aborted [Escape]" << std::endl;
2208 if (!client->itemdefReceived()) {
2209 const wchar_t *text = wgettext("Item definitions...");
2211 draw_load_screen(text, device, guienv, texture_src,
2214 } else if (!client->nodedefReceived()) {
2215 const wchar_t *text = wgettext("Node definitions...");
2217 draw_load_screen(text, device, guienv, texture_src,
2221 std::stringstream message;
2222 std::fixed(message);
2223 message.precision(0);
2224 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2225 message.precision(2);
2227 if ((USE_CURL == 0) ||
2228 (!g_settings->getBool("enable_remote_media_server"))) {
2229 float cur = client->getCurRate();
2230 std::string cur_unit = gettext("KiB/s");
2234 cur_unit = gettext("MiB/s");
2237 message << " (" << cur << ' ' << cur_unit << ")";
2240 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2241 draw_load_screen(utf8_to_wide(message.str()), device,
2242 guienv, texture_src, dtime, progress);
2250 /****************************************************************************/
2251 /****************************************************************************
2253 ****************************************************************************/
2254 /****************************************************************************/
2256 inline void Game::updateInteractTimers(f32 dtime)
2258 if (runData.nodig_delay_timer >= 0)
2259 runData.nodig_delay_timer -= dtime;
2261 if (runData.object_hit_delay_timer >= 0)
2262 runData.object_hit_delay_timer -= dtime;
2264 runData.time_from_last_punch += dtime;
2268 /* returns false if game should exit, otherwise true
2270 inline bool Game::checkConnection()
2272 if (client->accessDenied()) {
2273 *error_message = "Access denied. Reason: "
2274 + client->accessDeniedReason();
2275 *reconnect_requested = client->reconnectRequested();
2276 errorstream << *error_message << std::endl;
2284 /* returns false if game should exit, otherwise true
2286 inline bool Game::handleCallbacks()
2288 if (g_gamecallback->disconnect_requested) {
2289 g_gamecallback->disconnect_requested = false;
2293 if (g_gamecallback->changepassword_requested) {
2294 (new GUIPasswordChange(guienv, guiroot, -1,
2295 &g_menumgr, client))->drop();
2296 g_gamecallback->changepassword_requested = false;
2299 if (g_gamecallback->changevolume_requested) {
2300 (new GUIVolumeChange(guienv, guiroot, -1,
2301 &g_menumgr))->drop();
2302 g_gamecallback->changevolume_requested = false;
2305 if (g_gamecallback->keyconfig_requested) {
2306 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2307 &g_menumgr))->drop();
2308 g_gamecallback->keyconfig_requested = false;
2311 if (g_gamecallback->keyconfig_changed) {
2312 keycache.populate(); // update the cache with new settings
2313 g_gamecallback->keyconfig_changed = false;
2320 void Game::processQueues()
2322 texture_src->processQueue();
2323 itemdef_manager->processQueue(client);
2324 shader_src->processQueue();
2328 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2330 float profiler_print_interval =
2331 g_settings->getFloat("profiler_print_interval");
2332 bool print_to_log = true;
2334 if (profiler_print_interval == 0) {
2335 print_to_log = false;
2336 profiler_print_interval = 5;
2339 if (profiler_interval.step(dtime, profiler_print_interval)) {
2341 infostream << "Profiler:" << std::endl;
2342 g_profiler->print(infostream);
2345 update_profiler_gui(guitext_profiler, g_fontengine,
2346 runData.profiler_current_page, runData.profiler_max_page,
2347 driver->getScreenSize().Height);
2349 g_profiler->clear();
2352 addProfilerGraphs(stats, draw_times, dtime);
2356 void Game::addProfilerGraphs(const RunStats &stats,
2357 const FpsControl &draw_times, f32 dtime)
2359 g_profiler->graphAdd("mainloop_other",
2360 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2362 if (draw_times.sleep_time != 0)
2363 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2364 g_profiler->graphAdd("mainloop_dtime", dtime);
2366 g_profiler->add("Elapsed time", dtime);
2367 g_profiler->avg("FPS", 1. / dtime);
2371 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2378 /* Time average and jitter calculation
2380 jp = &stats->dtime_jitter;
2381 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2383 jitter = dtime - jp->avg;
2385 if (jitter > jp->max)
2388 jp->counter += dtime;
2390 if (jp->counter > 0.0) {
2392 jp->max_sample = jp->max;
2393 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2397 /* Busytime average and jitter calculation
2399 jp = &stats->busy_time_jitter;
2400 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2402 jitter = draw_times.busy_time - jp->avg;
2404 if (jitter > jp->max)
2406 if (jitter < jp->min)
2409 jp->counter += dtime;
2411 if (jp->counter > 0.0) {
2413 jp->max_sample = jp->max;
2414 jp->min_sample = jp->min;
2422 /****************************************************************************
2424 ****************************************************************************/
2426 void Game::processUserInput(f32 dtime)
2428 // Reset input if window not active or some menu is active
2429 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
2431 #ifdef HAVE_TOUCHSCREENGUI
2432 g_touchscreengui->hide();
2435 #ifdef HAVE_TOUCHSCREENGUI
2436 else if (g_touchscreengui) {
2437 /* on touchscreengui step may generate own input events which ain't
2438 * what we want in case we just did clear them */
2439 g_touchscreengui->step(dtime);
2443 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2444 gui_chat_console->closeConsoleAtOnce();
2447 // Input handler step() (used by the random input generator)
2451 if (current_formspec != NULL)
2452 current_formspec->getAndroidUIInput();
2454 handleAndroidChatInput();
2457 // Increase timer for double tap of "keymap_jump"
2458 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2459 runData.jump_timer += dtime;
2462 processItemSelection(&runData.new_playeritem);
2466 void Game::processKeyInput()
2468 if (wasKeyDown(KeyType::DROP)) {
2470 } else if (wasKeyDown(KeyType::AUTORUN)) {
2472 } else if (wasKeyDown(KeyType::INVENTORY)) {
2474 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2475 if (!gui_chat_console->isOpenInhibited()) {
2478 } else if (wasKeyDown(KeyType::CHAT)) {
2479 openConsole(0.2, L"");
2480 } else if (wasKeyDown(KeyType::CMD)) {
2481 openConsole(0.2, L"/");
2482 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2483 openConsole(0.2, L".");
2484 } else if (wasKeyDown(KeyType::CONSOLE)) {
2485 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2486 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2488 } else if (wasKeyDown(KeyType::JUMP)) {
2489 toggleFreeMoveAlt();
2490 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2492 } else if (wasKeyDown(KeyType::NOCLIP)) {
2494 } else if (wasKeyDown(KeyType::MUTE)) {
2495 float volume = g_settings->getFloat("sound_volume");
2496 if (volume < 0.001f) {
2497 g_settings->setFloat("sound_volume", 1.0f);
2498 m_statustext = narrow_to_wide(gettext("Volume changed to 100%"));
2500 g_settings->setFloat("sound_volume", 0.0f);
2501 m_statustext = narrow_to_wide(gettext("Volume changed to 0%"));
2503 runData.statustext_time = 0;
2504 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
2505 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
2507 g_settings->setFloat("sound_volume", new_volume);
2508 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2509 m_statustext = narrow_to_wide(buf);
2510 runData.statustext_time = 0;
2511 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
2512 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
2514 g_settings->setFloat("sound_volume", new_volume);
2515 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2516 m_statustext = narrow_to_wide(buf);
2517 runData.statustext_time = 0;
2518 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2520 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2521 client->makeScreenshot(device);
2522 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2524 } else if (wasKeyDown(KeyType::MINIMAP)) {
2525 toggleMinimap(isKeyDown(KeyType::SNEAK));
2526 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2528 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2530 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2531 toggleUpdateCamera();
2532 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2534 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2536 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2537 increaseViewRange();
2538 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2539 decreaseViewRange();
2540 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2541 toggleFullViewRange();
2542 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2544 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2546 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2548 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2550 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2551 // Print debug stacks
2552 dstream << "-----------------------------------------"
2554 dstream << "Printing debug stacks:" << std::endl;
2555 dstream << "-----------------------------------------"
2557 debug_stacks_print();
2560 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2561 runData.reset_jump_timer = false;
2562 runData.jump_timer = 0.0f;
2565 if (quicktune->hasMessage()) {
2566 m_statustext = utf8_to_wide(quicktune->getMessage());
2567 runData.statustext_time = 0.0f;
2571 void Game::processItemSelection(u16 *new_playeritem)
2573 LocalPlayer *player = client->getEnv().getLocalPlayer();
2575 /* Item selection using mouse wheel
2577 *new_playeritem = client->getPlayerItem();
2579 s32 wheel = input->getMouseWheel();
2580 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2581 player->hud_hotbar_itemcount - 1);
2585 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2586 wasKeyDown(KeyType::HOTBAR_NEXT)) {
2590 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2591 wasKeyDown(KeyType::HOTBAR_PREV)) {
2596 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2598 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2601 /* Item selection using keyboard
2603 for (u16 i = 0; i < 10; i++) {
2604 static const KeyPress *item_keys[10] = {
2605 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2606 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2607 NumberKey + 9, NumberKey + 0,
2610 if (input->wasKeyDown(*item_keys[i])) {
2611 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2612 *new_playeritem = i;
2613 infostream << "Selected item: " << new_playeritem << std::endl;
2621 void Game::dropSelectedItem()
2623 IDropAction *a = new IDropAction();
2625 a->from_inv.setCurrentPlayer();
2626 a->from_list = "main";
2627 a->from_i = client->getPlayerItem();
2628 client->inventoryAction(a);
2632 void Game::openInventory()
2635 * Don't permit to open inventory is CAO or player doesn't exists.
2636 * This prevent showing an empty inventory at player load
2639 LocalPlayer *player = client->getEnv().getLocalPlayer();
2640 if (player == NULL || player->getCAO() == NULL)
2643 infostream << "the_game: " << "Launching inventory" << std::endl;
2645 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2646 TextDest *txt_dst = new TextDestPlayerInventory(client);
2648 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
2651 InventoryLocation inventoryloc;
2652 inventoryloc.setCurrentPlayer();
2653 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2657 void Game::openConsole(float scale, const wchar_t *line)
2659 assert(scale > 0.0f && scale <= 1.0f);
2662 porting::showInputDialog(gettext("ok"), "", "", 2);
2663 m_android_chat_open = true;
2665 if (gui_chat_console->isOpenInhibited())
2667 gui_chat_console->openConsole(scale);
2669 gui_chat_console->setCloseOnEnter(true);
2670 gui_chat_console->replaceAndAddToHistory(line);
2676 void Game::handleAndroidChatInput()
2678 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2679 std::string text = porting::getInputDialogValue();
2680 client->typeChatMessage(utf8_to_wide(text));
2686 void Game::toggleFreeMove()
2688 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2690 bool free_move = !g_settings->getBool("free_move");
2691 g_settings->set("free_move", bool_to_cstr(free_move));
2693 runData.statustext_time = 0;
2694 m_statustext = msg[free_move];
2695 if (free_move && !client->checkPrivilege("fly"))
2696 m_statustext += L" (note: no 'fly' privilege)";
2700 void Game::toggleFreeMoveAlt()
2702 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2705 runData.reset_jump_timer = true;
2709 void Game::toggleFast()
2711 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2712 bool fast_move = !g_settings->getBool("fast_move");
2713 g_settings->set("fast_move", bool_to_cstr(fast_move));
2715 runData.statustext_time = 0;
2716 m_statustext = msg[fast_move];
2718 bool has_fast_privs = client->checkPrivilege("fast");
2720 if (fast_move && !has_fast_privs)
2721 m_statustext += L" (note: no 'fast' privilege)";
2724 m_cache_hold_aux1 = fast_move && has_fast_privs;
2729 void Game::toggleNoClip()
2731 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2732 bool noclip = !g_settings->getBool("noclip");
2733 g_settings->set("noclip", bool_to_cstr(noclip));
2735 runData.statustext_time = 0;
2736 m_statustext = msg[noclip];
2738 if (noclip && !client->checkPrivilege("noclip"))
2739 m_statustext += L" (note: no 'noclip' privilege)";
2742 void Game::toggleCinematic()
2744 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2745 bool cinematic = !g_settings->getBool("cinematic");
2746 g_settings->set("cinematic", bool_to_cstr(cinematic));
2748 runData.statustext_time = 0;
2749 m_statustext = msg[cinematic];
2752 // Add WoW-style autorun by toggling continuous forward.
2753 void Game::toggleAutorun()
2755 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2756 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2757 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2759 runData.statustext_time = 0;
2760 m_statustext = msg[autorun_enabled ? 1 : 0];
2763 void Game::toggleChat()
2765 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2767 flags.show_chat = !flags.show_chat;
2768 runData.statustext_time = 0;
2769 m_statustext = msg[flags.show_chat];
2773 void Game::toggleHud()
2775 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2777 flags.show_hud = !flags.show_hud;
2778 runData.statustext_time = 0;
2779 m_statustext = msg[flags.show_hud];
2782 void Game::toggleMinimap(bool shift_pressed)
2784 if (!flags.show_hud || !g_settings->getBool("enable_minimap"))
2787 if (shift_pressed) {
2788 mapper->toggleMinimapShape();
2792 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2794 MinimapMode mode = MINIMAP_MODE_OFF;
2795 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2796 mode = mapper->getMinimapMode();
2797 mode = (MinimapMode)((int)mode + 1);
2800 flags.show_minimap = true;
2802 case MINIMAP_MODE_SURFACEx1:
2803 m_statustext = L"Minimap in surface mode, Zoom x1";
2805 case MINIMAP_MODE_SURFACEx2:
2806 m_statustext = L"Minimap in surface mode, Zoom x2";
2808 case MINIMAP_MODE_SURFACEx4:
2809 m_statustext = L"Minimap in surface mode, Zoom x4";
2811 case MINIMAP_MODE_RADARx1:
2812 m_statustext = L"Minimap in radar mode, Zoom x1";
2814 case MINIMAP_MODE_RADARx2:
2815 m_statustext = L"Minimap in radar mode, Zoom x2";
2817 case MINIMAP_MODE_RADARx4:
2818 m_statustext = L"Minimap in radar mode, Zoom x4";
2821 mode = MINIMAP_MODE_OFF;
2822 flags.show_minimap = false;
2823 m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2824 L"Minimap hidden" : L"Minimap disabled by server";
2827 runData.statustext_time = 0;
2828 mapper->setMinimapMode(mode);
2831 void Game::toggleFog()
2833 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2835 flags.force_fog_off = !flags.force_fog_off;
2836 runData.statustext_time = 0;
2837 m_statustext = msg[flags.force_fog_off];
2841 void Game::toggleDebug()
2843 // Initial / 4x toggle: Chat only
2844 // 1x toggle: Debug text with chat
2845 // 2x toggle: Debug text with profiler graph
2846 // 3x toggle: Debug text and wireframe
2847 if (!flags.show_debug) {
2848 flags.show_debug = true;
2849 flags.show_profiler_graph = false;
2850 draw_control->show_wireframe = false;
2851 m_statustext = L"Debug info shown";
2852 } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2853 flags.show_profiler_graph = true;
2854 m_statustext = L"Profiler graph shown";
2855 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2856 flags.show_profiler_graph = false;
2857 draw_control->show_wireframe = true;
2858 m_statustext = L"Wireframe shown";
2860 flags.show_debug = false;
2861 flags.show_profiler_graph = false;
2862 draw_control->show_wireframe = false;
2863 if (client->checkPrivilege("debug")) {
2864 m_statustext = L"Debug info, profiler graph, and wireframe hidden";
2866 m_statustext = L"Debug info and profiler graph hidden";
2869 runData.statustext_time = 0;
2873 void Game::toggleUpdateCamera()
2875 static const wchar_t *msg[] = {
2876 L"Camera update enabled",
2877 L"Camera update disabled"
2880 flags.disable_camera_update = !flags.disable_camera_update;
2881 runData.statustext_time = 0;
2882 m_statustext = msg[flags.disable_camera_update];
2886 void Game::toggleProfiler()
2888 runData.profiler_current_page =
2889 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2891 // FIXME: This updates the profiler with incomplete values
2892 update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2893 runData.profiler_max_page, driver->getScreenSize().Height);
2895 if (runData.profiler_current_page != 0) {
2896 std::wstringstream sstr;
2897 sstr << "Profiler shown (page " << runData.profiler_current_page
2898 << " of " << runData.profiler_max_page << ")";
2899 m_statustext = sstr.str();
2901 m_statustext = L"Profiler hidden";
2903 runData.statustext_time = 0;
2907 void Game::increaseViewRange()
2909 s16 range = g_settings->getS16("viewing_range");
2910 s16 range_new = range + 10;
2912 if (range_new > 4000) {
2914 m_statustext = utf8_to_wide("Viewing range is at maximum: "
2917 m_statustext = utf8_to_wide("Viewing range changed to "
2920 g_settings->set("viewing_range", itos(range_new));
2921 runData.statustext_time = 0;
2925 void Game::decreaseViewRange()
2927 s16 range = g_settings->getS16("viewing_range");
2928 s16 range_new = range - 10;
2930 if (range_new < 20) {
2932 m_statustext = utf8_to_wide("Viewing range is at minimum: "
2935 m_statustext = utf8_to_wide("Viewing range changed to "
2938 g_settings->set("viewing_range", itos(range_new));
2939 runData.statustext_time = 0;
2943 void Game::toggleFullViewRange()
2945 static const wchar_t *msg[] = {
2946 L"Disabled full viewing range",
2947 L"Enabled full viewing range"
2950 draw_control->range_all = !draw_control->range_all;
2951 infostream << msg[draw_control->range_all] << std::endl;
2952 m_statustext = msg[draw_control->range_all];
2953 runData.statustext_time = 0;
2957 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2959 if ((device->isWindowActive() && !isMenuActive()) || random_input) {
2962 if (!random_input) {
2963 // Mac OSX gets upset if this is set every frame
2964 if (device->getCursorControl()->isVisible())
2965 device->getCursorControl()->setVisible(false);
2969 if (m_first_loop_after_window_activation)
2970 m_first_loop_after_window_activation = false;
2972 updateCameraOrientation(cam, dtime);
2974 input->setMousePos((driver->getScreenSize().Width / 2),
2975 (driver->getScreenSize().Height / 2));
2979 // Mac OSX gets upset if this is set every frame
2980 if (!device->getCursorControl()->isVisible())
2981 device->getCursorControl()->setVisible(true);
2984 if (!m_first_loop_after_window_activation)
2985 m_first_loop_after_window_activation = true;
2990 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2992 #ifdef HAVE_TOUCHSCREENGUI
2993 if (g_touchscreengui) {
2994 cam->camera_yaw += g_touchscreengui->getYawChange();
2995 cam->camera_pitch = g_touchscreengui->getPitch();
2999 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3000 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3002 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3006 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3007 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3009 #ifdef HAVE_TOUCHSCREENGUI
3013 if (m_cache_enable_joysticks) {
3014 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3015 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
3016 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
3019 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3023 void Game::updatePlayerControl(const CameraOrientation &cam)
3025 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3027 // DO NOT use the isKeyDown method for the forward, backward, left, right
3028 // buttons, as the code that uses the controls needs to be able to
3029 // distinguish between the two in order to know when to use joysticks.
3031 PlayerControl control(
3032 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3033 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3034 input->isKeyDown(keycache.key[KeyType::LEFT]),
3035 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3036 isKeyDown(KeyType::JUMP),
3037 isKeyDown(KeyType::SPECIAL1),
3038 isKeyDown(KeyType::SNEAK),
3039 isKeyDown(KeyType::ZOOM),
3044 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3045 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3049 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3050 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3051 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3052 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3053 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3054 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3055 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3056 ( (u32)(isLeftPressed() & 0x1) << 7) |
3057 ( (u32)(isRightPressed() & 0x1) << 8
3061 /* For Android, simulate holding down AUX1 (fast move) if the user has
3062 * the fast_move setting toggled on. If there is an aux1 key defined for
3063 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3066 if (m_cache_hold_aux1) {
3067 control.aux1 = control.aux1 ^ true;
3068 keypress_bits ^= ((u32)(1U << 5));
3072 client->setPlayerControl(control);
3073 LocalPlayer *player = client->getEnv().getLocalPlayer();
3074 player->keyPressed = keypress_bits;
3080 inline void Game::step(f32 *dtime)
3082 bool can_be_and_is_paused =
3083 (simple_singleplayer_mode && g_menumgr.pausesGame());
3085 if (can_be_and_is_paused) { // This is for a singleplayer server
3086 *dtime = 0; // No time passes
3088 if (server != NULL) {
3089 //TimeTaker timer("server->step(dtime)");
3090 server->step(*dtime);
3093 //TimeTaker timer("client.step(dtime)");
3094 client->step(*dtime);
3099 void Game::processClientEvents(CameraOrientation *cam)
3101 LocalPlayer *player = client->getEnv().getLocalPlayer();
3103 while (client->hasClientEvents()) {
3104 ClientEvent event = client->getClientEvent();
3106 switch (event.type) {
3107 case CE_PLAYER_DAMAGE:
3108 if (client->getHP() == 0)
3110 if (client->moddingEnabled()) {
3111 client->getScript()->on_damage_taken(event.player_damage.amount);
3114 runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3115 runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3117 player->hurt_tilt_timer = 1.5;
3118 player->hurt_tilt_strength =
3119 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3121 client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3124 case CE_PLAYER_FORCE_MOVE:
3125 cam->camera_yaw = event.player_force_move.yaw;
3126 cam->camera_pitch = event.player_force_move.pitch;
3129 case CE_DEATHSCREEN:
3130 // This should be enabled for death formspec in builtin
3131 client->getScript()->on_death();
3133 /* Handle visualization */
3134 runData.damage_flash = 0;
3135 player->hurt_tilt_timer = 0;
3136 player->hurt_tilt_strength = 0;
3139 case CE_SHOW_FORMSPEC:
3140 if (*(event.show_formspec.formspec) == "") {
3141 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3142 current_formspec->quitMenu();
3145 FormspecFormSource *fs_src =
3146 new FormspecFormSource(*(event.show_formspec.formspec));
3147 TextDestPlayerInventory *txt_dst =
3148 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3150 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3152 cur_formname = *(event.show_formspec.formname);
3155 delete event.show_formspec.formspec;
3156 delete event.show_formspec.formname;
3159 case CE_SHOW_LOCAL_FORMSPEC:
3161 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3162 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3163 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3166 delete event.show_formspec.formspec;
3167 delete event.show_formspec.formname;
3170 case CE_SPAWN_PARTICLE:
3171 case CE_ADD_PARTICLESPAWNER:
3172 case CE_DELETE_PARTICLESPAWNER:
3173 client->getParticleManager()->handleParticleEvent(&event, client,
3179 u32 id = event.hudadd.id;
3181 HudElement *e = player->getHud(id);
3184 delete event.hudadd.pos;
3185 delete event.hudadd.name;
3186 delete event.hudadd.scale;
3187 delete event.hudadd.text;
3188 delete event.hudadd.align;
3189 delete event.hudadd.offset;
3190 delete event.hudadd.world_pos;
3191 delete event.hudadd.size;
3196 e->type = (HudElementType)event.hudadd.type;
3197 e->pos = *event.hudadd.pos;
3198 e->name = *event.hudadd.name;
3199 e->scale = *event.hudadd.scale;
3200 e->text = *event.hudadd.text;
3201 e->number = event.hudadd.number;
3202 e->item = event.hudadd.item;
3203 e->dir = event.hudadd.dir;
3204 e->align = *event.hudadd.align;
3205 e->offset = *event.hudadd.offset;
3206 e->world_pos = *event.hudadd.world_pos;
3207 e->size = *event.hudadd.size;
3209 u32 new_id = player->addHud(e);
3210 //if this isn't true our huds aren't consistent
3211 sanity_check(new_id == id);
3214 delete event.hudadd.pos;
3215 delete event.hudadd.name;
3216 delete event.hudadd.scale;
3217 delete event.hudadd.text;
3218 delete event.hudadd.align;
3219 delete event.hudadd.offset;
3220 delete event.hudadd.world_pos;
3221 delete event.hudadd.size;
3226 HudElement *e = player->removeHud(event.hudrm.id);
3235 u32 id = event.hudchange.id;
3236 HudElement *e = player->getHud(id);
3239 delete event.hudchange.v3fdata;
3240 delete event.hudchange.v2fdata;
3241 delete event.hudchange.sdata;
3242 delete event.hudchange.v2s32data;
3246 switch (event.hudchange.stat) {
3248 e->pos = *event.hudchange.v2fdata;
3252 e->name = *event.hudchange.sdata;
3255 case HUD_STAT_SCALE:
3256 e->scale = *event.hudchange.v2fdata;
3260 e->text = *event.hudchange.sdata;
3263 case HUD_STAT_NUMBER:
3264 e->number = event.hudchange.data;
3268 e->item = event.hudchange.data;
3272 e->dir = event.hudchange.data;
3275 case HUD_STAT_ALIGN:
3276 e->align = *event.hudchange.v2fdata;
3279 case HUD_STAT_OFFSET:
3280 e->offset = *event.hudchange.v2fdata;
3283 case HUD_STAT_WORLD_POS:
3284 e->world_pos = *event.hudchange.v3fdata;
3288 e->size = *event.hudchange.v2s32data;
3293 delete event.hudchange.v3fdata;
3294 delete event.hudchange.v2fdata;
3295 delete event.hudchange.sdata;
3296 delete event.hudchange.v2s32data;
3300 sky->setVisible(false);
3301 // Whether clouds are visible in front of a custom skybox
3302 sky->setCloudsEnabled(event.set_sky.clouds);
3309 // Handle according to type
3310 if (*event.set_sky.type == "regular") {
3311 sky->setVisible(true);
3312 sky->setCloudsEnabled(true);
3313 } else if (*event.set_sky.type == "skybox" &&
3314 event.set_sky.params->size() == 6) {
3315 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3316 skybox = smgr->addSkyBoxSceneNode(
3317 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3318 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3319 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3320 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3321 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3322 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3324 // Handle everything else as plain color
3326 if (*event.set_sky.type != "plain")
3327 infostream << "Unknown sky type: "
3328 << (*event.set_sky.type) << std::endl;
3330 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3333 delete event.set_sky.bgcolor;
3334 delete event.set_sky.type;
3335 delete event.set_sky.params;
3338 case CE_OVERRIDE_DAY_NIGHT_RATIO:
3339 client->getEnv().setDayNightRatioOverride(
3340 event.override_day_night_ratio.do_override,
3341 event.override_day_night_ratio.ratio_f * 1000);
3344 case CE_CLOUD_PARAMS:
3346 clouds->setDensity(event.cloud_params.density);
3347 clouds->setColorBright(video::SColor(event.cloud_params.color_bright));
3348 clouds->setColorAmbient(video::SColor(event.cloud_params.color_ambient));
3349 clouds->setHeight(event.cloud_params.height);
3350 clouds->setThickness(event.cloud_params.thickness);
3351 clouds->setSpeed(v2f(
3352 event.cloud_params.speed_x,
3353 event.cloud_params.speed_y));
3358 // unknown or unhandled type
3366 void Game::updateCamera(u32 busy_time, f32 dtime)
3368 LocalPlayer *player = client->getEnv().getLocalPlayer();
3371 For interaction purposes, get info about the held item
3373 - Is it a usable item?
3374 - Can it point to liquids?
3376 ItemStack playeritem;
3378 InventoryList *mlist = local_inventory->getList("main");
3380 if (mlist && client->getPlayerItem() < mlist->getSize())
3381 playeritem = mlist->getItem(client->getPlayerItem());
3384 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3385 InventoryList *hlist = local_inventory->getList("hand");
3387 playeritem = hlist->getItem(0);
3391 ToolCapabilities playeritem_toolcap =
3392 playeritem.getToolCapabilities(itemdef_manager);
3394 v3s16 old_camera_offset = camera->getOffset();
3396 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3397 GenericCAO *playercao = player->getCAO();
3399 // If playercao not loaded, don't change camera
3400 if (playercao == NULL)
3403 camera->toggleCameraMode();
3405 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3406 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3409 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3410 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3412 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3413 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3415 camera->step(dtime);
3417 v3f camera_position = camera->getPosition();
3418 v3f camera_direction = camera->getDirection();
3419 f32 camera_fov = camera->getFovMax();
3420 v3s16 camera_offset = camera->getOffset();
3422 m_camera_offset_changed = (camera_offset != old_camera_offset);
3424 if (!flags.disable_camera_update) {
3425 client->getEnv().getClientMap().updateCamera(camera_position,
3426 camera_direction, camera_fov, camera_offset);
3428 if (m_camera_offset_changed) {
3429 client->updateCameraOffset(camera_offset);
3430 client->getEnv().updateCameraOffset(camera_offset);
3433 clouds->updateCameraOffset(camera_offset);
3439 void Game::updateSound(f32 dtime)
3441 // Update sound listener
3442 v3s16 camera_offset = camera->getOffset();
3443 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3444 v3f(0, 0, 0), // velocity
3445 camera->getDirection(),
3446 camera->getCameraNode()->getUpVector());
3448 // Check if volume is in the proper range, else fix it.
3449 float old_volume = g_settings->getFloat("sound_volume");
3450 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
3451 sound->setListenerGain(new_volume);
3453 if (old_volume != new_volume) {
3454 g_settings->setFloat("sound_volume", new_volume);
3457 LocalPlayer *player = client->getEnv().getLocalPlayer();
3459 // Tell the sound maker whether to make footstep sounds
3460 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3462 // Update sound maker
3463 if (player->makes_footstep_sound)
3464 soundmaker->step(dtime);
3466 ClientMap &map = client->getEnv().getClientMap();
3467 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3468 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3472 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3474 LocalPlayer *player = client->getEnv().getLocalPlayer();
3476 ItemStack playeritem;
3478 InventoryList *mlist = local_inventory->getList("main");
3480 if (mlist && client->getPlayerItem() < mlist->getSize())
3481 playeritem = mlist->getItem(client->getPlayerItem());
3484 const ItemDefinition &playeritem_def =
3485 playeritem.getDefinition(itemdef_manager);
3486 InventoryList *hlist = local_inventory->getList("hand");
3487 const ItemDefinition &hand_def =
3488 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3490 v3f player_position = player->getPosition();
3491 v3f camera_position = camera->getPosition();
3492 v3f camera_direction = camera->getDirection();
3493 v3s16 camera_offset = camera->getOffset();
3497 Calculate what block is the crosshair pointing to
3500 f32 d = playeritem_def.range; // max. distance
3501 f32 d_hand = hand_def.range;
3503 if (d < 0 && d_hand >= 0)
3508 core::line3d<f32> shootline;
3510 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3511 shootline = core::line3d<f32>(camera_position,
3512 camera_position + camera_direction * BS * d);
3514 // prevent player pointing anything in front-view
3515 shootline = core::line3d<f32>(camera_position,camera_position);
3518 #ifdef HAVE_TOUCHSCREENGUI
3520 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3521 shootline = g_touchscreengui->getShootline();
3522 shootline.start += intToFloat(camera_offset, BS);
3523 shootline.end += intToFloat(camera_offset, BS);
3528 PointedThing pointed = updatePointedThing(shootline,
3529 playeritem_def.liquids_pointable,
3530 !runData.ldown_for_dig,
3533 if (pointed != runData.pointed_old) {
3534 infostream << "Pointing at " << pointed.dump() << std::endl;
3535 hud->updateSelectionMesh(camera_offset);
3540 - releasing left mouse button
3541 - pointing away from node
3543 if (runData.digging) {
3544 if (getLeftReleased()) {
3545 infostream << "Left button released"
3546 << " (stopped digging)" << std::endl;
3547 runData.digging = false;
3548 } else if (pointed != runData.pointed_old) {
3549 if (pointed.type == POINTEDTHING_NODE
3550 && runData.pointed_old.type == POINTEDTHING_NODE
3551 && pointed.node_undersurface
3552 == runData.pointed_old.node_undersurface) {
3553 // Still pointing to the same node, but a different face.
3556 infostream << "Pointing away from node"
3557 << " (stopped digging)" << std::endl;
3558 runData.digging = false;
3559 hud->updateSelectionMesh(camera_offset);
3563 if (!runData.digging) {
3564 client->interact(1, runData.pointed_old);
3565 client->setCrack(-1, v3s16(0, 0, 0));
3566 runData.dig_time = 0.0;
3568 } else if (runData.dig_instantly && getLeftReleased()) {
3569 // Remove e.g. torches faster when clicking instead of holding LMB
3570 runData.nodig_delay_timer = 0;
3571 runData.dig_instantly = false;
3574 if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3575 runData.ldown_for_dig = false;
3578 runData.left_punch = false;
3580 soundmaker->m_player_leftpunch_sound.name = "";
3582 if (isRightPressed())
3583 runData.repeat_rightclick_timer += dtime;
3585 runData.repeat_rightclick_timer = 0;
3587 if (playeritem_def.usable && isLeftPressed()) {
3588 if (getLeftClicked() && (!client->moddingEnabled()
3589 || !client->getScript()->on_item_use(playeritem, pointed)))
3590 client->interact(4, pointed);
3591 } else if (pointed.type == POINTEDTHING_NODE) {
3592 ToolCapabilities playeritem_toolcap =
3593 playeritem.getToolCapabilities(itemdef_manager);
3594 if (playeritem.name.empty()) {
3595 playeritem_toolcap = *hand_def.tool_capabilities;
3597 handlePointingAtNode(pointed, playeritem_def, playeritem_toolcap, dtime);
3598 } else if (pointed.type == POINTEDTHING_OBJECT) {
3599 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3600 } else if (isLeftPressed()) {
3601 // When button is held down in air, show continuous animation
3602 runData.left_punch = true;
3603 } else if (getRightClicked()) {
3604 handlePointingAtNothing(playeritem);
3607 runData.pointed_old = pointed;
3609 if (runData.left_punch || getLeftClicked())
3610 camera->setDigging(0); // left click animation
3612 input->resetLeftClicked();
3613 input->resetRightClicked();
3615 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3616 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3618 input->resetLeftReleased();
3619 input->resetRightReleased();
3621 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3622 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3626 PointedThing Game::updatePointedThing(
3627 const core::line3d<f32> &shootline,
3628 bool liquids_pointable,
3629 bool look_for_object,
3630 const v3s16 &camera_offset)
3632 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3633 selectionboxes->clear();
3634 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3635 static const bool show_entity_selectionbox = g_settings->getBool(
3636 "show_entity_selectionbox");
3638 ClientMap &map = client->getEnv().getClientMap();
3639 INodeDefManager *nodedef=client->getNodeDefManager();
3641 runData.selected_object = NULL;
3643 PointedThing result=client->getEnv().getPointedThing(
3644 shootline, liquids_pointable, look_for_object);
3645 if (result.type == POINTEDTHING_OBJECT) {
3646 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3647 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox()) {
3648 aabb3f *selection_box = runData.selected_object->getSelectionBox();
3650 // Box should exist because object was
3651 // returned in the first place
3653 assert(selection_box);
3655 v3f pos = runData.selected_object->getPosition();
3656 selectionboxes->push_back(aabb3f(
3657 selection_box->MinEdge, selection_box->MaxEdge));
3658 selectionboxes->push_back(
3659 aabb3f(selection_box->MinEdge, selection_box->MaxEdge));
3660 hud->setSelectionPos(pos, camera_offset);
3662 } else if (result.type == POINTEDTHING_NODE) {
3663 // Update selection boxes
3664 MapNode n = map.getNodeNoEx(result.node_undersurface);
3665 std::vector<aabb3f> boxes;
3666 n.getSelectionBoxes(nodedef, &boxes,
3667 n.getNeighbors(result.node_undersurface, &map));
3670 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3671 i != boxes.end(); ++i) {
3673 box.MinEdge -= v3f(d, d, d);
3674 box.MaxEdge += v3f(d, d, d);
3675 selectionboxes->push_back(box);
3677 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3679 hud->setSelectedFaceNormal(v3f(
3680 result.intersection_normal.X,
3681 result.intersection_normal.Y,
3682 result.intersection_normal.Z));
3685 // Update selection mesh light level and vertex colors
3686 if (selectionboxes->size() > 0) {
3687 v3f pf = hud->getSelectionPos();
3688 v3s16 p = floatToInt(pf, BS);
3690 // Get selection mesh light level
3691 MapNode n = map.getNodeNoEx(p);
3692 u16 node_light = getInteriorLight(n, -1, nodedef);
3693 u16 light_level = node_light;
3695 for (u8 i = 0; i < 6; i++) {
3696 n = map.getNodeNoEx(p + g_6dirs[i]);
3697 node_light = getInteriorLight(n, -1, nodedef);
3698 if (node_light > light_level)
3699 light_level = node_light;
3702 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3704 final_color_blend(&c, light_level, daynight_ratio);
3706 // Modify final color a bit with time
3707 u32 timer = porting::getTimeMs() % 5000;
3708 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3709 float sin_r = 0.08 * sin(timerf);
3710 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3711 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3712 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3713 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3714 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3716 // Set mesh final color
3717 hud->setSelectionMeshColor(c);
3723 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3725 infostream << "Right Clicked in Air" << std::endl;
3726 PointedThing fauxPointed;
3727 fauxPointed.type = POINTEDTHING_NOTHING;
3728 client->interact(5, fauxPointed);
3732 void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
3733 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3735 v3s16 nodepos = pointed.node_undersurface;
3736 v3s16 neighbourpos = pointed.node_abovesurface;
3739 Check information text of node
3742 ClientMap &map = client->getEnv().getClientMap();
3743 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3746 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3748 MapNode n = map.getNodeNoEx(nodepos);
3750 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3751 infotext = L"Unknown node: ";
3752 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3756 if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3757 && client->checkPrivilege("interact")) {
3758 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3761 if ((getRightClicked() ||
3762 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3763 client->checkPrivilege("interact")) {
3764 runData.repeat_rightclick_timer = 0;
3765 infostream << "Ground right-clicked" << std::endl;
3767 if (meta && meta->getString("formspec") != "" && !random_input
3768 && !isKeyDown(KeyType::SNEAK)) {
3769 infostream << "Launching custom inventory view" << std::endl;
3771 InventoryLocation inventoryloc;
3772 inventoryloc.setNodeMeta(nodepos);
3774 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3775 &client->getEnv().getClientMap(), nodepos);
3776 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3778 create_formspec_menu(¤t_formspec, client,
3779 device, &input->joystick, fs_src, txt_dst);
3782 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3784 // Report right click to server
3786 camera->setDigging(1); // right click animation (always shown for feedback)
3788 // If the wielded item has node placement prediction,
3790 bool placed = nodePlacementPrediction(*client,
3792 nodepos, neighbourpos);
3796 client->interact(3, pointed);
3798 soundmaker->m_player_rightpunch_sound =
3799 playeritem_def.sound_place;
3801 if (client->moddingEnabled())
3802 client->getScript()->on_placenode(pointed, playeritem_def);
3804 soundmaker->m_player_rightpunch_sound =
3807 if (playeritem_def.node_placement_prediction == "" ||
3808 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3809 client->interact(3, pointed); // Report to server
3811 soundmaker->m_player_rightpunch_sound =
3812 playeritem_def.sound_place_failed;
3820 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3821 const v3f &player_position, bool show_debug)
3823 infotext = unescape_enriched(
3824 utf8_to_wide(runData.selected_object->infoText()));
3827 if (infotext != L"") {
3830 infotext += unescape_enriched(utf8_to_wide(
3831 runData.selected_object->debugInfoText()));
3834 if (isLeftPressed()) {
3835 bool do_punch = false;
3836 bool do_punch_damage = false;
3838 if (runData.object_hit_delay_timer <= 0.0) {
3840 do_punch_damage = true;
3841 runData.object_hit_delay_timer = object_hit_delay;
3844 if (getLeftClicked())
3848 infostream << "Left-clicked object" << std::endl;
3849 runData.left_punch = true;
3852 if (do_punch_damage) {
3853 // Report direct punch
3854 v3f objpos = runData.selected_object->getPosition();
3855 v3f dir = (objpos - player_position).normalize();
3856 ItemStack item = playeritem;
3857 if (playeritem.name.empty()) {
3858 InventoryList *hlist = local_inventory->getList("hand");
3860 item = hlist->getItem(0);
3864 bool disable_send = runData.selected_object->directReportPunch(
3865 dir, &item, runData.time_from_last_punch);
3866 runData.time_from_last_punch = 0;
3869 client->interact(0, pointed);
3871 } else if (getRightClicked()) {
3872 infostream << "Right-clicked object" << std::endl;
3873 client->interact(3, pointed); // place
3878 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3879 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3881 LocalPlayer *player = client->getEnv().getLocalPlayer();
3882 ClientMap &map = client->getEnv().getClientMap();
3883 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3885 // NOTE: Similar piece of code exists on the server side for
3887 // Get digging parameters
3888 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3889 &playeritem_toolcap);
3891 // If can't dig, try hand
3892 if (!params.diggable) {
3893 InventoryList *hlist = local_inventory->getList("hand");
3894 const ItemDefinition &hand =
3895 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3896 const ToolCapabilities *tp = hand.tool_capabilities;
3899 params = getDigParams(nodedef_manager->get(n).groups, tp);
3902 if (!runData.digging) {
3903 infostream << "Started digging" << std::endl;
3904 runData.dig_instantly = params.time == 0;
3905 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3907 client->interact(0, pointed);
3908 runData.digging = true;
3909 runData.ldown_for_dig = true;
3912 if (!params.diggable) {
3913 // I guess nobody will wait for this long
3914 runData.dig_time_complete = 10000000.0;
3916 runData.dig_time_complete = params.time;
3918 if (m_cache_enable_particles) {
3919 const ContentFeatures &features =
3920 client->getNodeDefManager()->get(n);
3921 client->getParticleManager()->addPunchingParticles(client, smgr,
3922 player, nodepos, n, features);
3926 if (!runData.dig_instantly) {
3927 runData.dig_index = (float)crack_animation_length
3929 / runData.dig_time_complete;
3931 // This is for e.g. torches
3932 runData.dig_index = crack_animation_length;
3935 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3937 if (sound_dig.exists() && params.diggable) {
3938 if (sound_dig.name == "__group") {
3939 if (params.main_group != "") {
3940 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3941 soundmaker->m_player_leftpunch_sound.name =
3942 std::string("default_dig_") +
3946 soundmaker->m_player_leftpunch_sound = sound_dig;
3950 // Don't show cracks if not diggable
3951 if (runData.dig_time_complete >= 100000.0) {
3952 } else if (runData.dig_index < crack_animation_length) {
3953 //TimeTaker timer("client.setTempMod");
3954 //infostream<<"dig_index="<<dig_index<<std::endl;
3955 client->setCrack(runData.dig_index, nodepos);
3957 infostream << "Digging completed" << std::endl;
3958 client->setCrack(-1, v3s16(0, 0, 0));
3960 runData.dig_time = 0;
3961 runData.digging = false;
3963 runData.nodig_delay_timer =
3964 runData.dig_time_complete / (float)crack_animation_length;
3966 // We don't want a corresponding delay to very time consuming nodes
3967 // and nodes without digging time (e.g. torches) get a fixed delay.
3968 if (runData.nodig_delay_timer > 0.3)
3969 runData.nodig_delay_timer = 0.3;
3970 else if (runData.dig_instantly)
3971 runData.nodig_delay_timer = 0.15;
3973 bool is_valid_position;
3974 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3975 if (is_valid_position) {
3976 if (client->moddingEnabled()) {
3977 if (client->getScript()->on_dignode(nodepos, wasnode)) {
3981 client->removeNode(nodepos);
3984 client->interact(2, pointed);
3986 if (m_cache_enable_particles) {
3987 const ContentFeatures &features =
3988 client->getNodeDefManager()->get(wasnode);
3989 client->getParticleManager()->addDiggingParticles(client, smgr,
3990 player, nodepos, wasnode, features);
3994 // Send event to trigger sound
3995 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3996 client->event()->put(e);
3999 if (runData.dig_time_complete < 100000.0) {
4000 runData.dig_time += dtime;
4002 runData.dig_time = 0;
4003 client->setCrack(-1, nodepos);
4006 camera->setDigging(0); // left click animation
4010 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
4011 const CameraOrientation &cam)
4013 LocalPlayer *player = client->getEnv().getLocalPlayer();
4019 if (draw_control->range_all) {
4020 runData.fog_range = 100000 * BS;
4022 runData.fog_range = draw_control->wanted_range * BS;
4026 Calculate general brightness
4028 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4029 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4030 float direct_brightness;
4033 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4034 direct_brightness = time_brightness;
4035 sunlight_seen = true;
4037 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4038 float old_brightness = sky->getBrightness();
4039 direct_brightness = client->getEnv().getClientMap()
4040 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
4041 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4045 float time_of_day_smooth = runData.time_of_day_smooth;
4046 float time_of_day = client->getEnv().getTimeOfDayF();
4048 static const float maxsm = 0.05;
4049 static const float todsm = 0.05;
4051 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4052 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4053 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4054 time_of_day_smooth = time_of_day;
4056 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4057 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4058 + (time_of_day + 1.0) * todsm;
4060 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4061 + time_of_day * todsm;
4063 runData.time_of_day = time_of_day;
4064 runData.time_of_day_smooth = time_of_day_smooth;
4066 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4067 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4068 player->getPitch());
4074 v3f player_position = player->getPosition();
4075 if (sky->getCloudsVisible()) {
4076 clouds->setVisible(true);
4077 clouds->step(dtime);
4078 clouds->update(v2f(player_position.X, player_position.Z),
4079 sky->getCloudColor());
4081 clouds->setVisible(false);
4088 client->getParticleManager()->step(dtime);
4094 if (m_cache_enable_fog && !flags.force_fog_off) {
4097 video::EFT_FOG_LINEAR,
4098 runData.fog_range * m_cache_fog_start,
4099 runData.fog_range * 1.0,
4107 video::EFT_FOG_LINEAR,
4117 Get chat messages from client
4120 v2u32 screensize = driver->getScreenSize();
4122 updateChat(*client, dtime, flags.show_debug, screensize,
4123 flags.show_chat, runData.profiler_current_page,
4124 *chat_backend, guitext_chat);
4130 if (client->getPlayerItem() != runData.new_playeritem)
4131 client->selectPlayerItem(runData.new_playeritem);
4133 // Update local inventory if it has changed
4134 if (client->getLocalInventoryUpdated()) {
4135 //infostream<<"Updating local inventory"<<std::endl;
4136 client->getLocalInventory(*local_inventory);
4137 runData.update_wielded_item_trigger = true;
4140 if (runData.update_wielded_item_trigger) {
4141 // Update wielded tool
4142 InventoryList *mlist = local_inventory->getList("main");
4144 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4145 ItemStack item = mlist->getItem(client->getPlayerItem());
4146 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4147 InventoryList *hlist = local_inventory->getList("hand");
4149 item = hlist->getItem(0);
4151 camera->wield(item);
4154 runData.update_wielded_item_trigger = false;
4158 Update block draw list every 200ms or when camera direction has
4161 runData.update_draw_list_timer += dtime;
4163 v3f camera_direction = camera->getDirection();
4164 if (runData.update_draw_list_timer >= 0.2
4165 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4166 || m_camera_offset_changed) {
4167 runData.update_draw_list_timer = 0;
4168 client->getEnv().getClientMap().updateDrawList(driver);
4169 runData.update_draw_list_last_cam_dir = camera_direction;
4172 updateGui(*stats, dtime, cam);
4175 make sure menu is on top
4176 1. Delete formspec menu reference if menu was removed
4177 2. Else, make sure formspec menu is on top
4179 if (current_formspec) {
4180 if (current_formspec->getReferenceCount() == 1) {
4181 current_formspec->drop();
4182 current_formspec = NULL;
4183 } else if (isMenuActive()) {
4184 guiroot->bringToFront(current_formspec);
4192 const video::SColor &skycolor = sky->getSkyColor();
4194 TimeTaker tt_draw("mainloop: draw");
4195 driver->beginScene(true, true, skycolor);
4197 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4198 guienv, screensize, skycolor, flags.show_hud,
4199 flags.show_minimap);
4204 if (flags.show_profiler_graph)
4205 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4210 if (runData.damage_flash > 0.0) {
4211 video::SColor color(runData.damage_flash, 180, 0, 0);
4212 driver->draw2DRectangle(color,
4213 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4216 runData.damage_flash -= 100.0 * dtime;
4222 if (player->hurt_tilt_timer > 0.0) {
4223 player->hurt_tilt_timer -= dtime * 5;
4225 if (player->hurt_tilt_timer < 0)
4226 player->hurt_tilt_strength = 0;
4230 Update minimap pos and rotation
4232 if (flags.show_minimap && flags.show_hud) {
4233 mapper->setPos(floatToInt(player->getPosition(), BS));
4234 mapper->setAngle(player->getYaw());
4242 stats->drawtime = tt_draw.stop(true);
4243 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4247 inline static const char *yawToDirectionString(int yaw)
4249 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4251 yaw = wrapDegrees_0_360(yaw);
4252 yaw = (yaw + 45) % 360 / 90;
4254 return direction[yaw];
4258 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4260 v2u32 screensize = driver->getScreenSize();
4261 LocalPlayer *player = client->getEnv().getLocalPlayer();
4262 v3f player_position = player->getPosition();
4264 if (flags.show_debug) {
4265 static float drawtime_avg = 0;
4266 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4268 u16 fps = 1.0 / stats.dtime_jitter.avg;
4270 std::ostringstream os(std::ios_base::binary);
4272 << PROJECT_NAME_C " " << g_version_hash
4274 << " (R: range_all=" << draw_control->range_all << ")"
4275 << std::setprecision(0)
4276 << " drawtime = " << drawtime_avg
4277 << std::setprecision(1)
4278 << ", dtime_jitter = "
4279 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4280 << std::setprecision(1)
4281 << ", v_range = " << draw_control->wanted_range
4282 << std::setprecision(3)
4283 << ", RTT = " << client->getRTT();
4284 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4285 guitext->setVisible(true);
4287 guitext->setVisible(false);
4290 if (guitext->isVisible()) {
4291 core::rect<s32> rect(
4293 screensize.X, 5 + g_fontengine->getTextHeight()
4295 guitext->setRelativePosition(rect);
4298 if (flags.show_debug) {
4299 std::ostringstream os(std::ios_base::binary);
4300 os << std::setprecision(1) << std::fixed
4301 << "(" << (player_position.X / BS)
4302 << ", " << (player_position.Y / BS)
4303 << ", " << (player_position.Z / BS)
4304 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4305 << " " << yawToDirectionString(cam.camera_yaw)
4306 << ") (seed = " << ((u64)client->getMapSeed())
4309 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4310 ClientMap &map = client->getEnv().getClientMap();
4311 const INodeDefManager *nodedef = client->getNodeDefManager();
4312 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4313 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4314 const ContentFeatures &features = nodedef->get(n);
4315 os << " (pointing_at = " << nodedef->get(n).name
4316 << " - " << features.tiledef[0].name.c_str()
4321 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4322 guitext2->setVisible(true);
4324 core::rect<s32> rect(
4325 5, 5 + g_fontengine->getTextHeight(),
4326 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4328 guitext2->setRelativePosition(rect);
4330 guitext2->setVisible(false);
4333 setStaticText(guitext_info, infotext.c_str());
4334 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4336 float statustext_time_max = 1.5;
4338 if (!m_statustext.empty()) {
4339 runData.statustext_time += dtime;
4341 if (runData.statustext_time >= statustext_time_max) {
4343 runData.statustext_time = 0;
4347 setStaticText(guitext_status, m_statustext.c_str());
4348 guitext_status->setVisible(!m_statustext.empty());
4350 if (!m_statustext.empty()) {
4351 s32 status_width = guitext_status->getTextWidth();
4352 s32 status_height = guitext_status->getTextHeight();
4353 s32 status_y = screensize.Y - 150;
4354 s32 status_x = (screensize.X - status_width) / 2;
4355 core::rect<s32> rect(
4356 status_x , status_y - status_height,
4357 status_x + status_width, status_y
4359 guitext_status->setRelativePosition(rect);
4362 video::SColor initial_color(255, 0, 0, 0);
4364 if (guienv->getSkin())
4365 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4367 video::SColor final_color = initial_color;
4368 final_color.setAlpha(0);
4369 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4370 initial_color, final_color,
4371 pow(runData.statustext_time / statustext_time_max, 2.0f));
4372 guitext_status->setOverrideColor(fade_color);
4373 guitext_status->enableOverrideColor(true);
4378 /* Log times and stuff for visualization */
4379 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4381 Profiler::GraphValues values;
4382 g_profiler->graphGet(values);
4388 /****************************************************************************
4390 ****************************************************************************/
4392 /* On some computers framerate doesn't seem to be automatically limited
4394 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4396 // not using getRealTime is necessary for wine
4397 device->getTimer()->tick(); // Maker sure device time is up-to-date
4398 u32 time = device->getTimer()->getTime();
4399 u32 last_time = fps_timings->last_time;
4401 if (time > last_time) // Make sure time hasn't overflowed
4402 fps_timings->busy_time = time - last_time;
4404 fps_timings->busy_time = 0;
4406 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4407 ? g_settings->getFloat("pause_fps_max")
4408 : g_settings->getFloat("fps_max"));
4410 if (fps_timings->busy_time < frametime_min) {
4411 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4412 device->sleep(fps_timings->sleep_time);
4414 fps_timings->sleep_time = 0;
4417 /* Get the new value of the device timer. Note that device->sleep() may
4418 * not sleep for the entire requested time as sleep may be interrupted and
4419 * therefore it is arguably more accurate to get the new time from the
4420 * device rather than calculating it by adding sleep_time to time.
4423 device->getTimer()->tick(); // Update device timer
4424 time = device->getTimer()->getTime();
4426 if (time > last_time) // Make sure last_time hasn't overflowed
4427 *dtime = (time - last_time) / 1000.0;
4431 fps_timings->last_time = time;
4434 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4435 // pass a copy of it to this function
4436 // Note: \p msg must be allocated using new (not malloc())
4437 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4438 int percent, bool draw_clouds)
4440 draw_load_screen(msg, device, guienv, texture_src, dtime, percent,
4445 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4447 ((Game *)data)->readSettings();
4450 void Game::readSettings()
4452 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4453 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4454 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4455 m_cache_enable_particles = g_settings->getBool("enable_particles");
4456 m_cache_enable_fog = g_settings->getBool("enable_fog");
4457 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4458 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4459 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4461 m_cache_enable_noclip = g_settings->getBool("noclip");
4462 m_cache_enable_free_move = g_settings->getBool("free_move");
4464 m_cache_fog_start = g_settings->getFloat("fog_start");
4466 m_cache_cam_smoothing = 0;
4467 if (g_settings->getBool("cinematic"))
4468 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4470 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4472 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4473 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4474 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4478 /****************************************************************************/
4479 /****************************************************************************
4481 ****************************************************************************/
4482 /****************************************************************************/
4484 void Game::extendedResourceCleanup()
4486 // Extended resource accounting
4487 infostream << "Irrlicht resources after cleanup:" << std::endl;
4488 infostream << "\tRemaining meshes : "
4489 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4490 infostream << "\tRemaining textures : "
4491 << driver->getTextureCount() << std::endl;
4493 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4494 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4495 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4499 clearTextureNameCache();
4500 infostream << "\tRemaining materials: "
4501 << driver-> getMaterialRendererCount()
4502 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4505 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4506 void Game::showPauseMenu()
4509 static const std::string control_text = strgettext("Default Controls:\n"
4510 "No menu visible:\n"
4511 "- single tap: button activate\n"
4512 "- double tap: place/use\n"
4513 "- slide finger: look around\n"
4514 "Menu/Inventory visible:\n"
4515 "- double tap (outside):\n"
4517 "- touch stack, touch slot:\n"
4519 "- touch&drag, tap 2nd finger\n"
4520 " --> place single item to slot\n"
4523 static const std::string control_text_template = strgettext("Controls:\n"
4524 "- %s: move forwards\n"
4525 "- %s: move backwards\n"
4527 "- %s: move right\n"
4528 "- %s: jump/climb\n"
4529 "- %s: sneak/go down\n"
4532 "- Mouse: turn/look\n"
4533 "- Mouse left: dig/punch\n"
4534 "- Mouse right: place/use\n"
4535 "- Mouse wheel: select item\n"
4539 char control_text_buf[600];
4541 snprintf(control_text_buf, ARRLEN(control_text_buf), control_text_template.c_str(),
4542 GET_KEY_NAME(keymap_forward),
4543 GET_KEY_NAME(keymap_backward),
4544 GET_KEY_NAME(keymap_left),
4545 GET_KEY_NAME(keymap_right),
4546 GET_KEY_NAME(keymap_jump),
4547 GET_KEY_NAME(keymap_sneak),
4548 GET_KEY_NAME(keymap_drop),
4549 GET_KEY_NAME(keymap_inventory),
4550 GET_KEY_NAME(keymap_chat)
4553 std::string control_text = std::string(control_text_buf);
4554 str_formspec_escape(control_text);
4557 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4558 std::ostringstream os;
4560 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4561 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4562 << strgettext("Continue") << "]";
4564 if (!simple_singleplayer_mode) {
4565 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4566 << strgettext("Change Password") << "]";
4568 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4572 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4573 << strgettext("Sound Volume") << "]";
4574 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4575 << strgettext("Change Keys") << "]";
4577 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4578 << strgettext("Exit to Menu") << "]";
4579 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4580 << strgettext("Exit to OS") << "]"
4581 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4582 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4584 << strgettext("Game info:") << "\n";
4585 const std::string &address = client->getAddressName();
4586 static const std::string mode = strgettext("- Mode: ");
4587 if (!simple_singleplayer_mode) {
4588 Address serverAddress = client->getServerAddress();
4589 if (address != "") {
4590 os << mode << strgettext("Remote server") << "\n"
4591 << strgettext("- Address: ") << address;
4593 os << mode << strgettext("Hosting server");
4595 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4597 os << mode << strgettext("Singleplayer") << "\n";
4599 if (simple_singleplayer_mode || address == "") {
4600 static const std::string on = strgettext("On");
4601 static const std::string off = strgettext("Off");
4602 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4603 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4604 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4605 os << strgettext("- Damage: ") << damage << "\n"
4606 << strgettext("- Creative Mode: ") << creative << "\n";
4607 if (!simple_singleplayer_mode) {
4608 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4609 os << strgettext("- PvP: ") << pvp << "\n"
4610 << strgettext("- Public: ") << announced << "\n";
4611 std::string server_name = g_settings->get("server_name");
4612 str_formspec_escape(server_name);
4613 if (announced == on && server_name != "")
4614 os << strgettext("- Server Name: ") << server_name;
4621 /* Note: FormspecFormSource and LocalFormspecHandler *
4622 * are deleted by guiFormSpecMenu */
4623 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4624 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4626 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
4627 current_formspec->setFocus("btn_continue");
4628 current_formspec->doPause = true;
4631 /****************************************************************************/
4632 /****************************************************************************
4633 extern function for launching the game
4634 ****************************************************************************/
4635 /****************************************************************************/
4637 void the_game(bool *kill,
4639 InputHandler *input,
4640 IrrlichtDevice *device,
4642 const std::string &map_dir,
4643 const std::string &playername,
4644 const std::string &password,
4645 const std::string &address, // If empty local server is created
4648 std::string &error_message,
4649 ChatBackend &chat_backend,
4650 bool *reconnect_requested,
4651 const SubgameSpec &gamespec, // Used for local game
4652 bool simple_singleplayer_mode)
4656 /* Make a copy of the server address because if a local singleplayer server
4657 * is created then this is updated and we don't want to change the value
4658 * passed to us by the calling function
4660 std::string server_address = address;
4664 if (game.startup(kill, random_input, input, device, map_dir,
4665 playername, password, &server_address, port, error_message,
4666 reconnect_requested, &chat_backend, gamespec,
4667 simple_singleplayer_mode)) {
4672 } catch (SerializationError &e) {
4673 error_message = std::string("A serialization error occurred:\n")
4674 + e.what() + "\n\nThe server is probably "
4675 " running a different version of " PROJECT_NAME_C ".";
4676 errorstream << error_message << std::endl;
4677 } catch (ServerError &e) {
4678 error_message = e.what();
4679 errorstream << "ServerError: " << error_message << std::endl;
4680 } catch (ModError &e) {
4681 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4682 errorstream << "ModError: " << error_message << std::endl;