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 if (m_client->getMinimap()) {
719 float minimap_yaw_array[3];
720 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
721 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
722 minimap_yaw_array[0] = minimap_yaw.X;
723 minimap_yaw_array[1] = minimap_yaw.Y;
724 minimap_yaw_array[2] = minimap_yaw.Z;
726 minimap_yaw.getAs3Values(minimap_yaw_array);
728 m_minimap_yaw.set(minimap_yaw_array, services);
732 SamplerLayer_t base_tex = 0,
735 m_base_texture.set(&base_tex, services);
736 m_normal_texture.set(&normal_tex, services);
737 m_texture_flags.set(&flags_tex, services);
742 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
745 bool *m_force_fog_off;
748 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
750 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
751 f32 *fog_range, Client *client) :
753 m_force_fog_off(force_fog_off),
754 m_fog_range(fog_range),
758 void setSky(Sky *sky) {
760 for (size_t i = 0; i < created_nosky.size(); ++i) {
761 created_nosky[i]->setSky(m_sky);
763 created_nosky.clear();
766 virtual IShaderConstantSetter* create()
768 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
769 m_sky, m_force_fog_off, m_fog_range, m_client);
771 created_nosky.push_back(scs);
777 bool nodePlacementPrediction(Client &client,
778 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
780 std::string prediction = playeritem_def.node_placement_prediction;
781 INodeDefManager *nodedef = client.ndef();
782 ClientMap &map = client.getEnv().getClientMap();
784 bool is_valid_position;
786 node = map.getNodeNoEx(nodepos, &is_valid_position);
787 if (!is_valid_position)
790 if (prediction != "" && !nodedef->get(node).rightclickable) {
791 verbosestream << "Node placement prediction for "
792 << playeritem_def.name << " is "
793 << prediction << std::endl;
794 v3s16 p = neighbourpos;
796 // Place inside node itself if buildable_to
797 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
798 if (is_valid_position)
800 if (nodedef->get(n_under).buildable_to)
803 node = map.getNodeNoEx(p, &is_valid_position);
804 if (is_valid_position &&!nodedef->get(node).buildable_to)
809 // Find id of predicted node
811 bool found = nodedef->getId(prediction, id);
814 errorstream << "Node placement prediction failed for "
815 << playeritem_def.name << " (places "
817 << ") - Name not known" << std::endl;
821 // Predict param2 for facedir and wallmounted nodes
824 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
825 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED) {
826 v3s16 dir = nodepos - neighbourpos;
828 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
829 param2 = dir.Y < 0 ? 1 : 0;
830 } else if (abs(dir.X) > abs(dir.Z)) {
831 param2 = dir.X < 0 ? 3 : 2;
833 param2 = dir.Z < 0 ? 5 : 4;
837 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR ||
838 nodedef->get(id).param_type_2 == CPT2_COLORED_FACEDIR) {
839 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
841 if (abs(dir.X) > abs(dir.Z)) {
842 param2 = dir.X < 0 ? 3 : 1;
844 param2 = dir.Z < 0 ? 2 : 0;
850 //Check attachment if node is in group attached_node
851 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
852 static v3s16 wallmounted_dirs[8] = {
862 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
863 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED)
864 pp = p + wallmounted_dirs[param2];
866 pp = p + v3s16(0, -1, 0);
868 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
872 // Add node to client map
873 MapNode n(id, 0, param2);
876 LocalPlayer *player = client.getEnv().getLocalPlayer();
878 // Dont place node when player would be inside new node
879 // NOTE: This is to be eventually implemented by a mod as client-side Lua
880 if (!nodedef->get(n).walkable ||
881 g_settings->getBool("enable_build_where_you_stand") ||
882 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
883 (nodedef->get(n).walkable &&
884 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
885 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
887 // This triggers the required mesh update too
888 client.addNode(p, n);
891 } catch (InvalidPositionException &e) {
892 errorstream << "Node placement prediction failed for "
893 << playeritem_def.name << " (places "
895 << ") - Position not loaded" << std::endl;
902 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
903 Client *client, IrrlichtDevice *device, JoystickController *joystick,
904 IFormSource *fs_src, TextDest *txt_dest)
907 if (*cur_formspec == 0) {
908 *cur_formspec = new GUIFormSpecMenu(device, joystick,
909 guiroot, -1, &g_menumgr, client, client->getTextureSource(),
911 (*cur_formspec)->doPause = false;
914 Caution: do not call (*cur_formspec)->drop() here --
915 the reference might outlive the menu, so we will
916 periodically check if *cur_formspec is the only
917 remaining reference (i.e. the menu was removed)
918 and delete it in that case.
922 (*cur_formspec)->setFormSource(fs_src);
923 (*cur_formspec)->setTextDest(txt_dest);
929 #define SIZE_TAG "size[11,5.5]"
931 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
934 /******************************************************************************/
935 static void updateChat(Client &client, f32 dtime, bool show_debug,
936 const v2u32 &screensize, bool show_chat, u32 show_profiler,
937 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
939 // Add chat log output for errors to be shown in chat
940 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
942 // Get new messages from error log buffer
943 while (!chat_log_error_buf.empty()) {
944 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
945 if (!g_settings->getBool("disable_escape_sequences")) {
946 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
948 chat_backend.addMessage(L"", error_message);
951 // Get new messages from client
952 std::wstring message;
954 while (client.getChatMessage(message)) {
955 chat_backend.addUnparsedMessage(message);
958 // Remove old messages
959 chat_backend.step(dtime);
961 // Display all messages in a static text element
962 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
963 EnrichedString recent_chat = chat_backend.getRecentChat();
964 unsigned int line_height = g_fontengine->getLineHeight();
966 setStaticText(guitext_chat, recent_chat);
968 // Update gui element size and position
972 chat_y += 2 * line_height;
974 // first pass to calculate height of text to be set
975 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
976 porting::getWindowSize().X - 20);
977 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
978 guitext_chat->setRelativePosition(rect);
980 //now use real height of text and adjust rect according to this size
981 rect = core::rect<s32>(10, chat_y, width,
982 chat_y + guitext_chat->getTextHeight());
985 guitext_chat->setRelativePosition(rect);
986 // Don't show chat if disabled or empty or profiler is enabled
987 guitext_chat->setVisible(
988 show_chat && recent_chat_count != 0 && !show_profiler);
992 /****************************************************************************
993 Fast key cache for main game loop
994 ****************************************************************************/
996 /* This is faster than using getKeySetting with the tradeoff that functions
997 * using it must make sure that it's initialised before using it and there is
998 * no error handling (for example bounds checking). This is really intended for
999 * use only in the main running loop of the client (the_game()) where the faster
1000 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1001 * (e.g. formspecs) should continue using getKeySetting().
1009 populate_nonchanging();
1014 // Keys that are not settings dependent
1015 void populate_nonchanging();
1017 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1018 InputHandler *handler;
1021 void KeyCache::populate_nonchanging()
1023 key[KeyType::ESC] = EscapeKey;
1026 void KeyCache::populate()
1028 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1029 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1030 key[KeyType::LEFT] = getKeySetting("keymap_left");
1031 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1032 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1033 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1034 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1036 key[KeyType::AUTOFORWARD] = getKeySetting("keymap_autoforward");
1038 key[KeyType::DROP] = getKeySetting("keymap_drop");
1039 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1040 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1041 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1042 key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
1043 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1044 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1045 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1046 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1047 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1048 key[KeyType::HOTBAR_PREV] = getKeySetting("keymap_hotbar_previous");
1049 key[KeyType::HOTBAR_NEXT] = getKeySetting("keymap_hotbar_next");
1050 key[KeyType::MUTE] = getKeySetting("keymap_mute");
1051 key[KeyType::INC_VOLUME] = getKeySetting("keymap_increase_volume");
1052 key[KeyType::DEC_VOLUME] = getKeySetting("keymap_decrease_volume");
1053 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1054 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1055 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1056 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1057 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1058 = getKeySetting("keymap_toggle_force_fog_off");
1059 key[KeyType::TOGGLE_UPDATE_CAMERA]
1060 = getKeySetting("keymap_toggle_update_camera");
1061 key[KeyType::TOGGLE_DEBUG]
1062 = getKeySetting("keymap_toggle_debug");
1063 key[KeyType::TOGGLE_PROFILER]
1064 = getKeySetting("keymap_toggle_profiler");
1065 key[KeyType::CAMERA_MODE]
1066 = getKeySetting("keymap_camera_mode");
1067 key[KeyType::INCREASE_VIEWING_RANGE]
1068 = getKeySetting("keymap_increase_viewing_range_min");
1069 key[KeyType::DECREASE_VIEWING_RANGE]
1070 = getKeySetting("keymap_decrease_viewing_range_min");
1071 key[KeyType::RANGESELECT]
1072 = getKeySetting("keymap_rangeselect");
1073 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1075 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1076 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1077 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1078 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1080 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1083 // First clear all keys, then re-add the ones we listen for
1084 handler->dontListenForKeys();
1085 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1086 handler->listenForKey(key[i]);
1088 handler->listenForKey(EscapeKey);
1089 handler->listenForKey(CancelKey);
1090 for (size_t i = 0; i < 10; i++) {
1091 handler->listenForKey(NumberKey[i]);
1097 /****************************************************************************
1099 ****************************************************************************/
1101 const float object_hit_delay = 0.2;
1104 u32 last_time, busy_time, sleep_time;
1108 /* The reason the following structs are not anonymous structs within the
1109 * class is that they are not used by the majority of member functions and
1110 * many functions that do require objects of thse types do not modify them
1111 * (so they can be passed as a const qualified parameter)
1113 struct CameraOrientation {
1114 f32 camera_yaw; // "right/left"
1115 f32 camera_pitch; // "up/down"
1118 struct GameRunData {
1121 PointedThing pointed_old;
1126 bool update_wielded_item_trigger;
1127 bool reset_jump_timer;
1128 float nodig_delay_timer;
1130 float dig_time_complete;
1131 float repeat_rightclick_timer;
1132 float object_hit_delay_timer;
1133 float time_from_last_punch;
1134 ClientActiveObject *selected_object;
1138 float update_draw_list_timer;
1139 float statustext_time;
1143 v3f update_draw_list_last_cam_dir;
1145 u32 profiler_current_page;
1146 u32 profiler_max_page; // Number of pages
1149 float time_of_day_smooth;
1153 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1159 Jitter dtime_jitter, busy_time_jitter;
1162 /****************************************************************************
1164 ****************************************************************************/
1166 /* This is not intended to be a public class. If a public class becomes
1167 * desirable then it may be better to create another 'wrapper' class that
1168 * hides most of the stuff in this class (nothing in this class is required
1169 * by any other file) but exposes the public methods/data only.
1176 bool startup(bool *kill,
1178 InputHandler *input,
1179 IrrlichtDevice *device,
1180 const std::string &map_dir,
1181 const std::string &playername,
1182 const std::string &password,
1183 // If address is "", local server is used and address is updated
1184 std::string *address,
1186 std::string &error_message,
1188 ChatBackend *chat_backend,
1189 const SubgameSpec &gamespec, // Used for local game
1190 bool simple_singleplayer_mode);
1197 void extendedResourceCleanup();
1199 // Basic initialisation
1200 bool init(const std::string &map_dir, std::string *address,
1202 const SubgameSpec &gamespec);
1204 bool createSingleplayerServer(const std::string &map_dir,
1205 const SubgameSpec &gamespec, u16 port, std::string *address);
1208 bool createClient(const std::string &playername,
1209 const std::string &password, std::string *address, u16 port);
1212 // Client connection
1213 bool connectToServer(const std::string &playername,
1214 const std::string &password, std::string *address, u16 port,
1215 bool *connect_ok, bool *aborted);
1216 bool getServerContent(bool *aborted);
1220 void updateInteractTimers(f32 dtime);
1221 bool checkConnection();
1222 bool handleCallbacks();
1223 void processQueues();
1224 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1225 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1226 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1229 void processUserInput(f32 dtime);
1230 void processKeyInput();
1231 void processItemSelection(u16 *new_playeritem);
1233 void dropSelectedItem();
1234 void openInventory();
1235 void openConsole(float scale, const wchar_t *line=NULL);
1236 void toggleFreeMove();
1237 void toggleFreeMoveAlt();
1239 void toggleNoClip();
1240 void toggleCinematic();
1241 void toggleAutoforward();
1245 void toggleMinimap(bool shift_pressed);
1248 void toggleUpdateCamera();
1249 void toggleProfiler();
1251 void increaseViewRange();
1252 void decreaseViewRange();
1253 void toggleFullViewRange();
1255 void updateCameraDirection(CameraOrientation *cam, float dtime);
1256 void updateCameraOrientation(CameraOrientation *cam, float dtime);
1257 void updatePlayerControl(const CameraOrientation &cam);
1258 void step(f32 *dtime);
1259 void processClientEvents(CameraOrientation *cam);
1260 void updateCamera(u32 busy_time, f32 dtime);
1261 void updateSound(f32 dtime);
1262 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
1264 * Returns the object or node the player is pointing at.
1265 * Also updates the selected thing in the Hud.
1267 * @param[in] shootline the shootline, starting from
1268 * the camera position. This also gives the maximal distance
1270 * @param[in] liquids_pointable if false, liquids are ignored
1271 * @param[in] look_for_object if false, objects are ignored
1272 * @param[in] camera_offset offset of the camera
1273 * @param[out] selected_object the selected object or
1276 PointedThing updatePointedThing(
1277 const core::line3d<f32> &shootline, bool liquids_pointable,
1278 bool look_for_object, const v3s16 &camera_offset);
1279 void handlePointingAtNothing(const ItemStack &playerItem);
1280 void handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
1281 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1282 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
1283 const v3f &player_position, bool show_debug);
1284 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
1285 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1286 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
1287 const CameraOrientation &cam);
1288 void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
1289 void updateProfilerGraphs(ProfilerGraph *graph);
1292 void limitFps(FpsControl *fps_timings, f32 *dtime);
1294 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1295 bool draw_clouds = true);
1297 static void settingChangedCallback(const std::string &setting_name, void *data);
1298 void readSettings();
1300 inline bool getLeftClicked()
1302 return input->getLeftClicked() ||
1303 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1305 inline bool getRightClicked()
1307 return input->getRightClicked() ||
1308 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1310 inline bool isLeftPressed()
1312 return input->getLeftState() ||
1313 input->joystick.isKeyDown(KeyType::MOUSE_L);
1315 inline bool isRightPressed()
1317 return input->getRightState() ||
1318 input->joystick.isKeyDown(KeyType::MOUSE_R);
1320 inline bool getLeftReleased()
1322 return input->getLeftReleased() ||
1323 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1326 inline bool isKeyDown(GameKeyType k)
1328 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1330 inline bool wasKeyDown(GameKeyType k)
1332 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1336 void handleAndroidChatInput();
1340 void showPauseMenu();
1342 InputHandler *input;
1347 IWritableTextureSource *texture_src;
1348 IWritableShaderSource *shader_src;
1350 // When created, these will be filled with data received from the server
1351 IWritableItemDefManager *itemdef_manager;
1352 IWritableNodeDefManager *nodedef_manager;
1354 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1355 ISoundManager *sound;
1356 bool sound_is_dummy;
1357 SoundMaker *soundmaker;
1359 ChatBackend *chat_backend;
1361 GUIFormSpecMenu *current_formspec;
1362 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1363 std::string cur_formname;
1365 EventManager *eventmgr;
1366 QuicktuneShortcutter *quicktune;
1368 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1369 MapDrawControl *draw_control;
1371 Clouds *clouds; // Free using ->Drop()
1372 Sky *sky; // Free using ->Drop()
1373 Inventory *local_inventory;
1377 GameRunData runData;
1381 This class does take ownership/responsibily for cleaning up etc of any of
1382 these items (e.g. device)
1384 IrrlichtDevice *device;
1385 video::IVideoDriver *driver;
1386 scene::ISceneManager *smgr;
1388 std::string *error_message;
1389 bool *reconnect_requested;
1390 scene::ISceneNode *skybox;
1393 bool simple_singleplayer_mode;
1396 /* Pre-calculated values
1398 int crack_animation_length;
1402 gui::IGUIStaticText *guitext; // First line of debug text
1403 gui::IGUIStaticText *guitext2; // Second line of debug text
1404 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1405 gui::IGUIStaticText *guitext_status;
1406 gui::IGUIStaticText *guitext_chat; // Chat text
1407 gui::IGUIStaticText *guitext_profiler; // Profiler text
1409 std::wstring infotext;
1410 std::wstring m_statustext;
1414 IntervalLimiter profiler_interval;
1417 * TODO: Local caching of settings is not optimal and should at some stage
1418 * be updated to use a global settings object for getting thse values
1419 * (as opposed to the this local caching). This can be addressed in
1422 bool m_cache_doubletap_jump;
1423 bool m_cache_enable_clouds;
1424 bool m_cache_enable_joysticks;
1425 bool m_cache_enable_particles;
1426 bool m_cache_enable_fog;
1427 bool m_cache_enable_noclip;
1428 bool m_cache_enable_free_move;
1429 f32 m_cache_mouse_sensitivity;
1430 f32 m_cache_joystick_frustum_sensitivity;
1431 f32 m_repeat_right_click_time;
1432 f32 m_cache_cam_smoothing;
1433 f32 m_cache_fog_start;
1435 bool m_invert_mouse;
1436 bool m_first_loop_after_window_activation;
1437 bool m_camera_offset_changed;
1440 bool m_cache_hold_aux1;
1441 bool m_android_chat_open;
1450 itemdef_manager(NULL),
1451 nodedef_manager(NULL),
1453 sound_is_dummy(false),
1456 current_formspec(NULL),
1460 gui_chat_console(NULL),
1465 local_inventory(NULL),
1468 m_invert_mouse(false),
1469 m_first_loop_after_window_activation(false),
1470 m_camera_offset_changed(false)
1472 g_settings->registerChangedCallback("doubletap_jump",
1473 &settingChangedCallback, this);
1474 g_settings->registerChangedCallback("enable_clouds",
1475 &settingChangedCallback, this);
1476 g_settings->registerChangedCallback("doubletap_joysticks",
1477 &settingChangedCallback, this);
1478 g_settings->registerChangedCallback("enable_particles",
1479 &settingChangedCallback, this);
1480 g_settings->registerChangedCallback("enable_fog",
1481 &settingChangedCallback, this);
1482 g_settings->registerChangedCallback("mouse_sensitivity",
1483 &settingChangedCallback, this);
1484 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1485 &settingChangedCallback, this);
1486 g_settings->registerChangedCallback("repeat_rightclick_time",
1487 &settingChangedCallback, this);
1488 g_settings->registerChangedCallback("noclip",
1489 &settingChangedCallback, this);
1490 g_settings->registerChangedCallback("free_move",
1491 &settingChangedCallback, this);
1492 g_settings->registerChangedCallback("cinematic",
1493 &settingChangedCallback, this);
1494 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1495 &settingChangedCallback, this);
1496 g_settings->registerChangedCallback("camera_smoothing",
1497 &settingChangedCallback, this);
1502 m_cache_hold_aux1 = false; // This is initialised properly later
1509 /****************************************************************************
1511 ****************************************************************************/
1517 if (!sound_is_dummy)
1520 delete server; // deleted first to stop all server threads
1523 delete local_inventory;
1529 delete nodedef_manager;
1530 delete itemdef_manager;
1531 delete draw_control;
1533 extendedResourceCleanup();
1535 g_settings->deregisterChangedCallback("doubletap_jump",
1536 &settingChangedCallback, this);
1537 g_settings->deregisterChangedCallback("enable_clouds",
1538 &settingChangedCallback, this);
1539 g_settings->deregisterChangedCallback("enable_particles",
1540 &settingChangedCallback, this);
1541 g_settings->deregisterChangedCallback("enable_fog",
1542 &settingChangedCallback, this);
1543 g_settings->deregisterChangedCallback("mouse_sensitivity",
1544 &settingChangedCallback, this);
1545 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1546 &settingChangedCallback, this);
1547 g_settings->deregisterChangedCallback("noclip",
1548 &settingChangedCallback, this);
1549 g_settings->deregisterChangedCallback("free_move",
1550 &settingChangedCallback, this);
1551 g_settings->deregisterChangedCallback("cinematic",
1552 &settingChangedCallback, this);
1553 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1554 &settingChangedCallback, this);
1555 g_settings->deregisterChangedCallback("camera_smoothing",
1556 &settingChangedCallback, this);
1559 bool Game::startup(bool *kill,
1561 InputHandler *input,
1562 IrrlichtDevice *device,
1563 const std::string &map_dir,
1564 const std::string &playername,
1565 const std::string &password,
1566 std::string *address, // can change if simple_singleplayer_mode
1568 std::string &error_message,
1570 ChatBackend *chat_backend,
1571 const SubgameSpec &gamespec,
1572 bool simple_singleplayer_mode)
1575 this->device = device;
1577 this->error_message = &error_message;
1578 this->reconnect_requested = reconnect;
1579 this->random_input = random_input;
1580 this->input = input;
1581 this->chat_backend = chat_backend;
1582 this->simple_singleplayer_mode = simple_singleplayer_mode;
1584 keycache.handler = input;
1585 keycache.populate();
1587 driver = device->getVideoDriver();
1588 smgr = device->getSceneManager();
1590 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1592 memset(&runData, 0, sizeof(runData));
1593 runData.time_from_last_punch = 10.0;
1594 runData.profiler_max_page = 3;
1595 runData.update_wielded_item_trigger = true;
1597 memset(&flags, 0, sizeof(flags));
1598 flags.show_chat = true;
1599 flags.show_hud = true;
1600 flags.show_debug = g_settings->getBool("show_debug");
1601 m_invert_mouse = g_settings->getBool("invert_mouse");
1602 m_first_loop_after_window_activation = true;
1604 if (!init(map_dir, address, port, gamespec))
1607 if (!createClient(playername, password, address, port))
1616 ProfilerGraph graph;
1617 RunStats stats = { 0 };
1618 CameraOrientation cam_view_target = { 0 };
1619 CameraOrientation cam_view = { 0 };
1620 FpsControl draw_times = { 0 };
1621 f32 dtime; // in seconds
1623 /* Clear the profiler */
1624 Profiler::GraphValues dummyvalues;
1625 g_profiler->graphGet(dummyvalues);
1627 draw_times.last_time = device->getTimer()->getTime();
1629 set_light_table(g_settings->getFloat("display_gamma"));
1632 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1633 && client->checkPrivilege("fast");
1636 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1637 g_settings->getU16("screen_h"));
1639 while (device->run()
1640 && !(*kill || g_gamecallback->shutdown_requested
1641 || (server && server->getShutdownRequested()))) {
1643 const irr::core::dimension2d<u32> ¤t_screen_size =
1644 device->getVideoDriver()->getScreenSize();
1645 // Verify if window size has changed and save it if it's the case
1646 // Ensure evaluating settings->getBool after verifying screensize
1647 // First condition is cheaper
1648 if (previous_screen_size != current_screen_size &&
1649 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1650 g_settings->getBool("autosave_screensize")) {
1651 g_settings->setU16("screen_w", current_screen_size.Width);
1652 g_settings->setU16("screen_h", current_screen_size.Height);
1653 previous_screen_size = current_screen_size;
1656 /* Must be called immediately after a device->run() call because it
1657 * uses device->getTimer()->getTime()
1659 limitFps(&draw_times, &dtime);
1661 updateStats(&stats, draw_times, dtime);
1662 updateInteractTimers(dtime);
1664 if (!checkConnection())
1666 if (!handleCallbacks())
1672 hud->resizeHotbar();
1674 updateProfilers(stats, draw_times, dtime);
1675 processUserInput(dtime);
1676 // Update camera before player movement to avoid camera lag of one frame
1677 updateCameraDirection(&cam_view_target, dtime);
1678 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1679 cam_view.camera_yaw) * m_cache_cam_smoothing;
1680 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1681 cam_view.camera_pitch) * m_cache_cam_smoothing;
1682 updatePlayerControl(cam_view);
1684 processClientEvents(&cam_view_target);
1685 updateCamera(draw_times.busy_time, dtime);
1687 processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
1688 updateFrame(&graph, &stats, dtime, cam_view);
1689 updateProfilerGraphs(&graph);
1691 // Update if minimap has been disabled by the server
1692 flags.show_minimap &= client->shouldShowMinimap();
1697 void Game::shutdown()
1699 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1700 if (g_settings->get("3d_mode") == "pageflip") {
1701 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1704 if (current_formspec)
1705 current_formspec->quitMenu();
1707 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1712 if (gui_chat_console)
1713 gui_chat_console->drop();
1719 while (g_menumgr.menuCount() > 0) {
1720 g_menumgr.m_stack.front()->setVisible(false);
1721 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1724 if (current_formspec) {
1725 current_formspec->drop();
1726 current_formspec = NULL;
1729 chat_backend->addMessage(L"", L"# Disconnected.");
1730 chat_backend->addMessage(L"", L"");
1734 while (!client->isShutdown()) {
1735 assert(texture_src != NULL);
1736 assert(shader_src != NULL);
1737 texture_src->processQueue();
1738 shader_src->processQueue();
1745 /****************************************************************************/
1746 /****************************************************************************
1748 ****************************************************************************/
1749 /****************************************************************************/
1752 const std::string &map_dir,
1753 std::string *address,
1755 const SubgameSpec &gamespec)
1757 texture_src = createTextureSource(device);
1759 showOverlayMessage(wgettext("Loading..."), 0, 0);
1761 shader_src = createShaderSource(device);
1763 itemdef_manager = createItemDefManager();
1764 nodedef_manager = createNodeDefManager();
1766 eventmgr = new EventManager();
1767 quicktune = new QuicktuneShortcutter();
1769 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1770 && eventmgr && quicktune))
1776 // Create a server if not connecting to an existing one
1777 if (*address == "") {
1778 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1785 bool Game::initSound()
1788 if (g_settings->getBool("enable_sound")) {
1789 infostream << "Attempting to use OpenAL audio" << std::endl;
1790 sound = createOpenALSoundManager(&soundfetcher);
1792 infostream << "Failed to initialize OpenAL audio" << std::endl;
1794 infostream << "Sound disabled." << std::endl;
1798 infostream << "Using dummy audio." << std::endl;
1799 sound = &dummySoundManager;
1800 sound_is_dummy = true;
1803 soundmaker = new SoundMaker(sound, nodedef_manager);
1807 soundmaker->registerReceiver(eventmgr);
1812 bool Game::createSingleplayerServer(const std::string &map_dir,
1813 const SubgameSpec &gamespec, u16 port, std::string *address)
1815 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1817 std::string bind_str = g_settings->get("bind_address");
1818 Address bind_addr(0, 0, 0, 0, port);
1820 if (g_settings->getBool("ipv6_server")) {
1821 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1825 bind_addr.Resolve(bind_str.c_str());
1826 } catch (ResolveError &e) {
1827 infostream << "Resolving bind address \"" << bind_str
1828 << "\" failed: " << e.what()
1829 << " -- Listening on all addresses." << std::endl;
1832 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1833 *error_message = "Unable to listen on " +
1834 bind_addr.serializeString() +
1835 " because IPv6 is disabled";
1836 errorstream << *error_message << std::endl;
1840 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1841 bind_addr.isIPv6(), false);
1843 server->start(bind_addr);
1848 bool Game::createClient(const std::string &playername,
1849 const std::string &password, std::string *address, u16 port)
1851 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1853 draw_control = new MapDrawControl;
1857 bool could_connect, connect_aborted;
1859 if (!connectToServer(playername, password, address, port,
1860 &could_connect, &connect_aborted))
1863 if (!could_connect) {
1864 if (error_message->empty() && !connect_aborted) {
1865 // Should not happen if error messages are set properly
1866 *error_message = "Connection failed for unknown reason";
1867 errorstream << *error_message << std::endl;
1872 if (!getServerContent(&connect_aborted)) {
1873 if (error_message->empty() && !connect_aborted) {
1874 // Should not happen if error messages are set properly
1875 *error_message = "Connection failed for unknown reason";
1876 errorstream << *error_message << std::endl;
1881 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1882 &flags.force_fog_off, &runData.fog_range, client);
1883 shader_src->addShaderConstantSetterFactory(scsf);
1885 // Update cached textures, meshes and materials
1886 client->afterContentReceived(device);
1890 camera = new Camera(smgr, *draw_control, client);
1891 if (!camera || !camera->successfullyCreated(*error_message))
1893 client->setCamera(camera);
1897 if (m_cache_enable_clouds) {
1898 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1900 *error_message = "Memory allocation error (clouds)";
1901 errorstream << *error_message << std::endl;
1908 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
1910 skybox = NULL; // This is used/set later on in the main run loop
1912 local_inventory = new Inventory(itemdef_manager);
1914 if (!(sky && local_inventory)) {
1915 *error_message = "Memory allocation error (sky or local inventory)";
1916 errorstream << *error_message << std::endl;
1920 /* Pre-calculated values
1922 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1924 v2u32 size = t->getOriginalSize();
1925 crack_animation_length = size.Y / size.X;
1927 crack_animation_length = 5;
1933 /* Set window caption
1935 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1937 str += utf8_to_wide(g_version_hash);
1939 str += driver->getName();
1941 device->setWindowCaption(str.c_str());
1943 LocalPlayer *player = client->getEnv().getLocalPlayer();
1944 player->hurt_tilt_timer = 0;
1945 player->hurt_tilt_strength = 0;
1947 hud = new Hud(driver, smgr, guienv, client, player, local_inventory);
1950 *error_message = "Memory error: could not create HUD";
1951 errorstream << *error_message << std::endl;
1955 mapper = client->getMinimap();
1957 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1962 bool Game::initGui()
1964 // First line of debug text
1965 guitext = addStaticText(guienv,
1966 utf8_to_wide(PROJECT_NAME_C).c_str(),
1967 core::rect<s32>(0, 0, 0, 0),
1968 false, false, guiroot);
1970 // Second line of debug text
1971 guitext2 = addStaticText(guienv,
1973 core::rect<s32>(0, 0, 0, 0),
1974 false, false, guiroot);
1976 // At the middle of the screen
1977 // Object infos are shown in this
1978 guitext_info = addStaticText(guienv,
1980 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
1981 false, true, guiroot);
1983 // Status text (displays info when showing and hiding GUI stuff, etc.)
1984 guitext_status = addStaticText(guienv,
1986 core::rect<s32>(0, 0, 0, 0),
1987 false, false, guiroot);
1988 guitext_status->setVisible(false);
1991 guitext_chat = addStaticText(
1994 core::rect<s32>(0, 0, 0, 0),
1995 //false, false); // Disable word wrap as of now
1996 false, true, guiroot);
1998 // Remove stale "recent" chat messages from previous connections
1999 chat_backend->clearRecentChat();
2001 // Chat backend and console
2002 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2003 -1, chat_backend, client, &g_menumgr);
2004 if (!gui_chat_console) {
2005 *error_message = "Could not allocate memory for chat console";
2006 errorstream << *error_message << std::endl;
2010 // Profiler text (size is updated when text is updated)
2011 guitext_profiler = addStaticText(guienv,
2013 core::rect<s32>(0, 0, 0, 0),
2014 false, false, guiroot);
2015 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2016 guitext_profiler->setVisible(false);
2017 guitext_profiler->setWordWrap(true);
2019 #ifdef HAVE_TOUCHSCREENGUI
2021 if (g_touchscreengui)
2022 g_touchscreengui->init(texture_src);
2029 bool Game::connectToServer(const std::string &playername,
2030 const std::string &password, std::string *address, u16 port,
2031 bool *connect_ok, bool *aborted)
2033 *connect_ok = false; // Let's not be overly optimistic
2035 bool local_server_mode = false;
2037 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2039 Address connect_address(0, 0, 0, 0, port);
2042 connect_address.Resolve(address->c_str());
2044 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2045 //connect_address.Resolve("localhost");
2046 if (connect_address.isIPv6()) {
2047 IPv6AddressBytes addr_bytes;
2048 addr_bytes.bytes[15] = 1;
2049 connect_address.setAddress(&addr_bytes);
2051 connect_address.setAddress(127, 0, 0, 1);
2053 local_server_mode = true;
2055 } catch (ResolveError &e) {
2056 *error_message = std::string("Couldn't resolve address: ") + e.what();
2057 errorstream << *error_message << std::endl;
2061 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2062 *error_message = "Unable to connect to " +
2063 connect_address.serializeString() +
2064 " because IPv6 is disabled";
2065 errorstream << *error_message << std::endl;
2069 client = new Client(device,
2070 playername.c_str(), password, *address,
2071 *draw_control, texture_src, shader_src,
2072 itemdef_manager, nodedef_manager, sound, eventmgr,
2073 connect_address.isIPv6(), &flags);
2078 infostream << "Connecting to server at ";
2079 connect_address.print(&infostream);
2080 infostream << std::endl;
2082 client->connect(connect_address,
2083 simple_singleplayer_mode || local_server_mode);
2086 Wait for server to accept connection
2092 FpsControl fps_control = { 0 };
2094 f32 wait_time = 0; // in seconds
2096 fps_control.last_time = device->getTimer()->getTime();
2100 while (device->run()) {
2102 limitFps(&fps_control, &dtime);
2104 // Update client and server
2105 client->step(dtime);
2108 server->step(dtime);
2111 if (client->getState() == LC_Init) {
2117 if (client->accessDenied()) {
2118 *error_message = "Access denied. Reason: "
2119 + client->accessDeniedReason();
2120 *reconnect_requested = client->reconnectRequested();
2121 errorstream << *error_message << std::endl;
2125 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2127 infostream << "Connect aborted [Escape]" << std::endl;
2132 // Only time out if we aren't waiting for the server we started
2133 if ((*address != "") && (wait_time > 10)) {
2134 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2135 // If no pre v25 init was sent, and no answer was received,
2136 // but the low level connection could be established
2137 // (meaning that we have a peer id), then we probably wanted
2138 // to connect to a legacy server. In this case, tell the user
2139 // to enable the option to be able to connect.
2140 if (!sent_old_init &&
2141 (client->getProtoVersion() == 0) &&
2142 client->connectedToServer()) {
2143 *error_message = "Connection failure: init packet not "
2144 "recognized by server.\n"
2145 "Most likely the server uses an old protocol version (<v25).\n"
2146 "Please ask the server owner to update to 0.4.13 or later.\n"
2147 "To still connect to the server in the meantime,\n"
2148 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2149 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2150 "entry in the advanced settings menu.";
2152 *error_message = "Connection timed out.";
2154 errorstream << *error_message << std::endl;
2159 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2161 } catch (con::PeerNotFoundException &e) {
2162 // TODO: Should something be done here? At least an info/error
2170 bool Game::getServerContent(bool *aborted)
2174 FpsControl fps_control = { 0 };
2175 f32 dtime; // in seconds
2177 fps_control.last_time = device->getTimer()->getTime();
2179 while (device->run()) {
2181 limitFps(&fps_control, &dtime);
2183 // Update client and server
2184 client->step(dtime);
2187 server->step(dtime);
2190 if (client->mediaReceived() && client->itemdefReceived() &&
2191 client->nodedefReceived()) {
2196 if (!checkConnection())
2199 if (client->getState() < LC_Init) {
2200 *error_message = "Client disconnected";
2201 errorstream << *error_message << std::endl;
2205 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2207 infostream << "Connect aborted [Escape]" << std::endl;
2214 if (!client->itemdefReceived()) {
2215 const wchar_t *text = wgettext("Item definitions...");
2217 draw_load_screen(text, device, guienv, texture_src,
2220 } else if (!client->nodedefReceived()) {
2221 const wchar_t *text = wgettext("Node definitions...");
2223 draw_load_screen(text, device, guienv, texture_src,
2227 std::stringstream message;
2228 std::fixed(message);
2229 message.precision(0);
2230 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2231 message.precision(2);
2233 if ((USE_CURL == 0) ||
2234 (!g_settings->getBool("enable_remote_media_server"))) {
2235 float cur = client->getCurRate();
2236 std::string cur_unit = gettext("KiB/s");
2240 cur_unit = gettext("MiB/s");
2243 message << " (" << cur << ' ' << cur_unit << ")";
2246 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2247 draw_load_screen(utf8_to_wide(message.str()), device,
2248 guienv, texture_src, dtime, progress);
2256 /****************************************************************************/
2257 /****************************************************************************
2259 ****************************************************************************/
2260 /****************************************************************************/
2262 inline void Game::updateInteractTimers(f32 dtime)
2264 if (runData.nodig_delay_timer >= 0)
2265 runData.nodig_delay_timer -= dtime;
2267 if (runData.object_hit_delay_timer >= 0)
2268 runData.object_hit_delay_timer -= dtime;
2270 runData.time_from_last_punch += dtime;
2274 /* returns false if game should exit, otherwise true
2276 inline bool Game::checkConnection()
2278 if (client->accessDenied()) {
2279 *error_message = "Access denied. Reason: "
2280 + client->accessDeniedReason();
2281 *reconnect_requested = client->reconnectRequested();
2282 errorstream << *error_message << std::endl;
2290 /* returns false if game should exit, otherwise true
2292 inline bool Game::handleCallbacks()
2294 if (g_gamecallback->disconnect_requested) {
2295 g_gamecallback->disconnect_requested = false;
2299 if (g_gamecallback->changepassword_requested) {
2300 (new GUIPasswordChange(guienv, guiroot, -1,
2301 &g_menumgr, client))->drop();
2302 g_gamecallback->changepassword_requested = false;
2305 if (g_gamecallback->changevolume_requested) {
2306 (new GUIVolumeChange(guienv, guiroot, -1,
2307 &g_menumgr))->drop();
2308 g_gamecallback->changevolume_requested = false;
2311 if (g_gamecallback->keyconfig_requested) {
2312 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2313 &g_menumgr))->drop();
2314 g_gamecallback->keyconfig_requested = false;
2317 if (g_gamecallback->keyconfig_changed) {
2318 keycache.populate(); // update the cache with new settings
2319 g_gamecallback->keyconfig_changed = false;
2326 void Game::processQueues()
2328 texture_src->processQueue();
2329 itemdef_manager->processQueue(client);
2330 shader_src->processQueue();
2334 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2336 float profiler_print_interval =
2337 g_settings->getFloat("profiler_print_interval");
2338 bool print_to_log = true;
2340 if (profiler_print_interval == 0) {
2341 print_to_log = false;
2342 profiler_print_interval = 5;
2345 if (profiler_interval.step(dtime, profiler_print_interval)) {
2347 infostream << "Profiler:" << std::endl;
2348 g_profiler->print(infostream);
2351 update_profiler_gui(guitext_profiler, g_fontengine,
2352 runData.profiler_current_page, runData.profiler_max_page,
2353 driver->getScreenSize().Height);
2355 g_profiler->clear();
2358 addProfilerGraphs(stats, draw_times, dtime);
2362 void Game::addProfilerGraphs(const RunStats &stats,
2363 const FpsControl &draw_times, f32 dtime)
2365 g_profiler->graphAdd("mainloop_other",
2366 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2368 if (draw_times.sleep_time != 0)
2369 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2370 g_profiler->graphAdd("mainloop_dtime", dtime);
2372 g_profiler->add("Elapsed time", dtime);
2373 g_profiler->avg("FPS", 1. / dtime);
2377 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2384 /* Time average and jitter calculation
2386 jp = &stats->dtime_jitter;
2387 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2389 jitter = dtime - jp->avg;
2391 if (jitter > jp->max)
2394 jp->counter += dtime;
2396 if (jp->counter > 0.0) {
2398 jp->max_sample = jp->max;
2399 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2403 /* Busytime average and jitter calculation
2405 jp = &stats->busy_time_jitter;
2406 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2408 jitter = draw_times.busy_time - jp->avg;
2410 if (jitter > jp->max)
2412 if (jitter < jp->min)
2415 jp->counter += dtime;
2417 if (jp->counter > 0.0) {
2419 jp->max_sample = jp->max;
2420 jp->min_sample = jp->min;
2428 /****************************************************************************
2430 ****************************************************************************/
2432 void Game::processUserInput(f32 dtime)
2434 // Reset input if window not active or some menu is active
2435 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
2437 #ifdef HAVE_TOUCHSCREENGUI
2438 g_touchscreengui->hide();
2441 #ifdef HAVE_TOUCHSCREENGUI
2442 else if (g_touchscreengui) {
2443 /* on touchscreengui step may generate own input events which ain't
2444 * what we want in case we just did clear them */
2445 g_touchscreengui->step(dtime);
2449 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2450 gui_chat_console->closeConsoleAtOnce();
2453 // Input handler step() (used by the random input generator)
2457 if (current_formspec != NULL)
2458 current_formspec->getAndroidUIInput();
2460 handleAndroidChatInput();
2463 // Increase timer for double tap of "keymap_jump"
2464 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2465 runData.jump_timer += dtime;
2468 processItemSelection(&runData.new_playeritem);
2472 void Game::processKeyInput()
2474 if (wasKeyDown(KeyType::DROP)) {
2476 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
2477 toggleAutoforward();
2478 } else if (wasKeyDown(KeyType::INVENTORY)) {
2480 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2481 if (!gui_chat_console->isOpenInhibited()) {
2484 } else if (wasKeyDown(KeyType::CHAT)) {
2485 openConsole(0.2, L"");
2486 } else if (wasKeyDown(KeyType::CMD)) {
2487 openConsole(0.2, L"/");
2488 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2489 openConsole(0.2, L".");
2490 } else if (wasKeyDown(KeyType::CONSOLE)) {
2491 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2492 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2494 } else if (wasKeyDown(KeyType::JUMP)) {
2495 toggleFreeMoveAlt();
2496 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2498 } else if (wasKeyDown(KeyType::NOCLIP)) {
2500 } else if (wasKeyDown(KeyType::MUTE)) {
2501 float volume = g_settings->getFloat("sound_volume");
2502 if (volume < 0.001f) {
2503 g_settings->setFloat("sound_volume", 1.0f);
2504 m_statustext = narrow_to_wide(gettext("Volume changed to 100%"));
2506 g_settings->setFloat("sound_volume", 0.0f);
2507 m_statustext = narrow_to_wide(gettext("Volume changed to 0%"));
2509 runData.statustext_time = 0;
2510 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
2511 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
2513 g_settings->setFloat("sound_volume", new_volume);
2514 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2515 m_statustext = narrow_to_wide(buf);
2516 runData.statustext_time = 0;
2517 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
2518 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
2520 g_settings->setFloat("sound_volume", new_volume);
2521 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2522 m_statustext = narrow_to_wide(buf);
2523 runData.statustext_time = 0;
2524 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2526 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2527 client->makeScreenshot();
2528 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2530 } else if (wasKeyDown(KeyType::MINIMAP)) {
2531 toggleMinimap(isKeyDown(KeyType::SNEAK));
2532 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2534 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2536 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2537 toggleUpdateCamera();
2538 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2540 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2542 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2543 increaseViewRange();
2544 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2545 decreaseViewRange();
2546 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2547 toggleFullViewRange();
2548 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2550 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2552 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2554 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2556 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2557 // Print debug stacks
2558 dstream << "-----------------------------------------"
2560 dstream << "Printing debug stacks:" << std::endl;
2561 dstream << "-----------------------------------------"
2563 debug_stacks_print();
2566 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2567 runData.reset_jump_timer = false;
2568 runData.jump_timer = 0.0f;
2571 if (quicktune->hasMessage()) {
2572 m_statustext = utf8_to_wide(quicktune->getMessage());
2573 runData.statustext_time = 0.0f;
2577 void Game::processItemSelection(u16 *new_playeritem)
2579 LocalPlayer *player = client->getEnv().getLocalPlayer();
2581 /* Item selection using mouse wheel
2583 *new_playeritem = client->getPlayerItem();
2585 s32 wheel = input->getMouseWheel();
2586 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2587 player->hud_hotbar_itemcount - 1);
2591 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2592 wasKeyDown(KeyType::HOTBAR_NEXT)) {
2596 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2597 wasKeyDown(KeyType::HOTBAR_PREV)) {
2602 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2604 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2607 /* Item selection using keyboard
2609 for (u16 i = 0; i < 10; i++) {
2610 static const KeyPress *item_keys[10] = {
2611 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2612 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2613 NumberKey + 9, NumberKey + 0,
2616 if (input->wasKeyDown(*item_keys[i])) {
2617 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2618 *new_playeritem = i;
2619 infostream << "Selected item: " << new_playeritem << std::endl;
2627 void Game::dropSelectedItem()
2629 IDropAction *a = new IDropAction();
2631 a->from_inv.setCurrentPlayer();
2632 a->from_list = "main";
2633 a->from_i = client->getPlayerItem();
2634 client->inventoryAction(a);
2638 void Game::openInventory()
2641 * Don't permit to open inventory is CAO or player doesn't exists.
2642 * This prevent showing an empty inventory at player load
2645 LocalPlayer *player = client->getEnv().getLocalPlayer();
2646 if (!player || !player->getCAO())
2649 infostream << "the_game: " << "Launching inventory" << std::endl;
2651 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2652 TextDest *txt_dst = new TextDestPlayerInventory(client);
2654 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
2657 InventoryLocation inventoryloc;
2658 inventoryloc.setCurrentPlayer();
2659 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2663 void Game::openConsole(float scale, const wchar_t *line)
2665 assert(scale > 0.0f && scale <= 1.0f);
2668 porting::showInputDialog(gettext("ok"), "", "", 2);
2669 m_android_chat_open = true;
2671 if (gui_chat_console->isOpenInhibited())
2673 gui_chat_console->openConsole(scale);
2675 gui_chat_console->setCloseOnEnter(true);
2676 gui_chat_console->replaceAndAddToHistory(line);
2682 void Game::handleAndroidChatInput()
2684 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2685 std::string text = porting::getInputDialogValue();
2686 client->typeChatMessage(utf8_to_wide(text));
2692 void Game::toggleFreeMove()
2694 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2696 bool free_move = !g_settings->getBool("free_move");
2697 g_settings->set("free_move", bool_to_cstr(free_move));
2699 runData.statustext_time = 0;
2700 m_statustext = msg[free_move];
2701 if (free_move && !client->checkPrivilege("fly"))
2702 m_statustext += L" (note: no 'fly' privilege)";
2706 void Game::toggleFreeMoveAlt()
2708 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2711 runData.reset_jump_timer = true;
2715 void Game::toggleFast()
2717 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2718 bool fast_move = !g_settings->getBool("fast_move");
2719 g_settings->set("fast_move", bool_to_cstr(fast_move));
2721 runData.statustext_time = 0;
2722 m_statustext = msg[fast_move];
2724 bool has_fast_privs = client->checkPrivilege("fast");
2726 if (fast_move && !has_fast_privs)
2727 m_statustext += L" (note: no 'fast' privilege)";
2730 m_cache_hold_aux1 = fast_move && has_fast_privs;
2735 void Game::toggleNoClip()
2737 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2738 bool noclip = !g_settings->getBool("noclip");
2739 g_settings->set("noclip", bool_to_cstr(noclip));
2741 runData.statustext_time = 0;
2742 m_statustext = msg[noclip];
2744 if (noclip && !client->checkPrivilege("noclip"))
2745 m_statustext += L" (note: no 'noclip' privilege)";
2748 void Game::toggleCinematic()
2750 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2751 bool cinematic = !g_settings->getBool("cinematic");
2752 g_settings->set("cinematic", bool_to_cstr(cinematic));
2754 runData.statustext_time = 0;
2755 m_statustext = msg[cinematic];
2758 // Autoforward by toggling continuous forward.
2759 void Game::toggleAutoforward()
2761 static const wchar_t *msg[] = { L"autoforward disabled", L"autoforward enabled" };
2762 bool autoforward_enabled = !g_settings->getBool("continuous_forward");
2763 g_settings->set("continuous_forward", bool_to_cstr(autoforward_enabled));
2765 runData.statustext_time = 0;
2766 m_statustext = msg[autoforward_enabled ? 1 : 0];
2769 void Game::toggleChat()
2771 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2773 flags.show_chat = !flags.show_chat;
2774 runData.statustext_time = 0;
2775 m_statustext = msg[flags.show_chat];
2779 void Game::toggleHud()
2781 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2783 flags.show_hud = !flags.show_hud;
2784 runData.statustext_time = 0;
2785 m_statustext = msg[flags.show_hud];
2788 void Game::toggleMinimap(bool shift_pressed)
2790 if (!mapper || !flags.show_hud || !g_settings->getBool("enable_minimap"))
2793 if (shift_pressed) {
2794 mapper->toggleMinimapShape();
2798 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2800 MinimapMode mode = MINIMAP_MODE_OFF;
2801 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2802 mode = mapper->getMinimapMode();
2803 mode = (MinimapMode)((int)mode + 1);
2806 flags.show_minimap = true;
2808 case MINIMAP_MODE_SURFACEx1:
2809 m_statustext = L"Minimap in surface mode, Zoom x1";
2811 case MINIMAP_MODE_SURFACEx2:
2812 m_statustext = L"Minimap in surface mode, Zoom x2";
2814 case MINIMAP_MODE_SURFACEx4:
2815 m_statustext = L"Minimap in surface mode, Zoom x4";
2817 case MINIMAP_MODE_RADARx1:
2818 m_statustext = L"Minimap in radar mode, Zoom x1";
2820 case MINIMAP_MODE_RADARx2:
2821 m_statustext = L"Minimap in radar mode, Zoom x2";
2823 case MINIMAP_MODE_RADARx4:
2824 m_statustext = L"Minimap in radar mode, Zoom x4";
2827 mode = MINIMAP_MODE_OFF;
2828 flags.show_minimap = false;
2829 m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2830 L"Minimap hidden" : L"Minimap disabled by server";
2833 runData.statustext_time = 0;
2834 mapper->setMinimapMode(mode);
2837 void Game::toggleFog()
2839 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2841 flags.force_fog_off = !flags.force_fog_off;
2842 runData.statustext_time = 0;
2843 m_statustext = msg[flags.force_fog_off];
2847 void Game::toggleDebug()
2849 // Initial / 4x toggle: Chat only
2850 // 1x toggle: Debug text with chat
2851 // 2x toggle: Debug text with profiler graph
2852 // 3x toggle: Debug text and wireframe
2853 if (!flags.show_debug) {
2854 flags.show_debug = true;
2855 flags.show_profiler_graph = false;
2856 draw_control->show_wireframe = false;
2857 m_statustext = L"Debug info shown";
2858 } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2859 flags.show_profiler_graph = true;
2860 m_statustext = L"Profiler graph shown";
2861 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2862 flags.show_profiler_graph = false;
2863 draw_control->show_wireframe = true;
2864 m_statustext = L"Wireframe shown";
2866 flags.show_debug = false;
2867 flags.show_profiler_graph = false;
2868 draw_control->show_wireframe = false;
2869 if (client->checkPrivilege("debug")) {
2870 m_statustext = L"Debug info, profiler graph, and wireframe hidden";
2872 m_statustext = L"Debug info and profiler graph hidden";
2875 runData.statustext_time = 0;
2879 void Game::toggleUpdateCamera()
2881 static const wchar_t *msg[] = {
2882 L"Camera update enabled",
2883 L"Camera update disabled"
2886 flags.disable_camera_update = !flags.disable_camera_update;
2887 runData.statustext_time = 0;
2888 m_statustext = msg[flags.disable_camera_update];
2892 void Game::toggleProfiler()
2894 runData.profiler_current_page =
2895 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2897 // FIXME: This updates the profiler with incomplete values
2898 update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2899 runData.profiler_max_page, driver->getScreenSize().Height);
2901 if (runData.profiler_current_page != 0) {
2902 std::wstringstream sstr;
2903 sstr << "Profiler shown (page " << runData.profiler_current_page
2904 << " of " << runData.profiler_max_page << ")";
2905 m_statustext = sstr.str();
2907 m_statustext = L"Profiler hidden";
2909 runData.statustext_time = 0;
2913 void Game::increaseViewRange()
2915 s16 range = g_settings->getS16("viewing_range");
2916 s16 range_new = range + 10;
2918 if (range_new > 4000) {
2920 m_statustext = utf8_to_wide("Viewing range is at maximum: "
2923 m_statustext = utf8_to_wide("Viewing range changed to "
2926 g_settings->set("viewing_range", itos(range_new));
2927 runData.statustext_time = 0;
2931 void Game::decreaseViewRange()
2933 s16 range = g_settings->getS16("viewing_range");
2934 s16 range_new = range - 10;
2936 if (range_new < 20) {
2938 m_statustext = utf8_to_wide("Viewing range is at minimum: "
2941 m_statustext = utf8_to_wide("Viewing range changed to "
2944 g_settings->set("viewing_range", itos(range_new));
2945 runData.statustext_time = 0;
2949 void Game::toggleFullViewRange()
2951 static const wchar_t *msg[] = {
2952 L"Disabled full viewing range",
2953 L"Enabled full viewing range"
2956 draw_control->range_all = !draw_control->range_all;
2957 infostream << msg[draw_control->range_all] << std::endl;
2958 m_statustext = msg[draw_control->range_all];
2959 runData.statustext_time = 0;
2963 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2965 if ((device->isWindowActive() && device->isWindowFocused()
2966 && !isMenuActive()) || random_input) {
2969 if (!random_input) {
2970 // Mac OSX gets upset if this is set every frame
2971 if (device->getCursorControl()->isVisible())
2972 device->getCursorControl()->setVisible(false);
2976 if (m_first_loop_after_window_activation)
2977 m_first_loop_after_window_activation = false;
2979 updateCameraOrientation(cam, dtime);
2981 input->setMousePos((driver->getScreenSize().Width / 2),
2982 (driver->getScreenSize().Height / 2));
2986 // Mac OSX gets upset if this is set every frame
2987 if (!device->getCursorControl()->isVisible())
2988 device->getCursorControl()->setVisible(true);
2991 m_first_loop_after_window_activation = true;
2996 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2998 #ifdef HAVE_TOUCHSCREENGUI
2999 if (g_touchscreengui) {
3000 cam->camera_yaw += g_touchscreengui->getYawChange();
3001 cam->camera_pitch = g_touchscreengui->getPitch();
3005 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3006 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3008 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3012 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3013 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3015 #ifdef HAVE_TOUCHSCREENGUI
3019 if (m_cache_enable_joysticks) {
3020 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3021 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
3022 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
3025 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3029 void Game::updatePlayerControl(const CameraOrientation &cam)
3031 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3033 // DO NOT use the isKeyDown method for the forward, backward, left, right
3034 // buttons, as the code that uses the controls needs to be able to
3035 // distinguish between the two in order to know when to use joysticks.
3037 PlayerControl control(
3038 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3039 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3040 input->isKeyDown(keycache.key[KeyType::LEFT]),
3041 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3042 isKeyDown(KeyType::JUMP),
3043 isKeyDown(KeyType::SPECIAL1),
3044 isKeyDown(KeyType::SNEAK),
3045 isKeyDown(KeyType::ZOOM),
3050 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3051 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3055 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3056 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3057 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3058 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3059 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3060 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3061 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3062 ( (u32)(isLeftPressed() & 0x1) << 7) |
3063 ( (u32)(isRightPressed() & 0x1) << 8
3067 /* For Android, simulate holding down AUX1 (fast move) if the user has
3068 * the fast_move setting toggled on. If there is an aux1 key defined for
3069 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3072 if (m_cache_hold_aux1) {
3073 control.aux1 = control.aux1 ^ true;
3074 keypress_bits ^= ((u32)(1U << 5));
3078 client->setPlayerControl(control);
3079 LocalPlayer *player = client->getEnv().getLocalPlayer();
3080 player->keyPressed = keypress_bits;
3086 inline void Game::step(f32 *dtime)
3088 bool can_be_and_is_paused =
3089 (simple_singleplayer_mode && g_menumgr.pausesGame());
3091 if (can_be_and_is_paused) { // This is for a singleplayer server
3092 *dtime = 0; // No time passes
3094 if (server != NULL) {
3095 //TimeTaker timer("server->step(dtime)");
3096 server->step(*dtime);
3099 //TimeTaker timer("client.step(dtime)");
3100 client->step(*dtime);
3105 void Game::processClientEvents(CameraOrientation *cam)
3107 LocalPlayer *player = client->getEnv().getLocalPlayer();
3109 while (client->hasClientEvents()) {
3110 ClientEvent event = client->getClientEvent();
3112 switch (event.type) {
3113 case CE_PLAYER_DAMAGE:
3114 if (client->getHP() == 0)
3116 if (client->moddingEnabled()) {
3117 client->getScript()->on_damage_taken(event.player_damage.amount);
3120 runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3121 runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3123 player->hurt_tilt_timer = 1.5;
3124 player->hurt_tilt_strength =
3125 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3127 client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3130 case CE_PLAYER_FORCE_MOVE:
3131 cam->camera_yaw = event.player_force_move.yaw;
3132 cam->camera_pitch = event.player_force_move.pitch;
3135 case CE_DEATHSCREEN:
3136 // This should be enabled for death formspec in builtin
3137 client->getScript()->on_death();
3139 /* Handle visualization */
3140 runData.damage_flash = 0;
3141 player->hurt_tilt_timer = 0;
3142 player->hurt_tilt_strength = 0;
3145 case CE_SHOW_FORMSPEC:
3146 if (*(event.show_formspec.formspec) == "") {
3147 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3148 current_formspec->quitMenu();
3151 FormspecFormSource *fs_src =
3152 new FormspecFormSource(*(event.show_formspec.formspec));
3153 TextDestPlayerInventory *txt_dst =
3154 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3156 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3158 cur_formname = *(event.show_formspec.formname);
3161 delete event.show_formspec.formspec;
3162 delete event.show_formspec.formname;
3165 case CE_SHOW_LOCAL_FORMSPEC:
3167 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3168 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3169 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3172 delete event.show_formspec.formspec;
3173 delete event.show_formspec.formname;
3176 case CE_SPAWN_PARTICLE:
3177 case CE_ADD_PARTICLESPAWNER:
3178 case CE_DELETE_PARTICLESPAWNER:
3179 client->getParticleManager()->handleParticleEvent(&event, client,
3185 u32 id = event.hudadd.id;
3187 HudElement *e = player->getHud(id);
3190 delete event.hudadd.pos;
3191 delete event.hudadd.name;
3192 delete event.hudadd.scale;
3193 delete event.hudadd.text;
3194 delete event.hudadd.align;
3195 delete event.hudadd.offset;
3196 delete event.hudadd.world_pos;
3197 delete event.hudadd.size;
3202 e->type = (HudElementType)event.hudadd.type;
3203 e->pos = *event.hudadd.pos;
3204 e->name = *event.hudadd.name;
3205 e->scale = *event.hudadd.scale;
3206 e->text = *event.hudadd.text;
3207 e->number = event.hudadd.number;
3208 e->item = event.hudadd.item;
3209 e->dir = event.hudadd.dir;
3210 e->align = *event.hudadd.align;
3211 e->offset = *event.hudadd.offset;
3212 e->world_pos = *event.hudadd.world_pos;
3213 e->size = *event.hudadd.size;
3215 u32 new_id = player->addHud(e);
3216 //if this isn't true our huds aren't consistent
3217 sanity_check(new_id == id);
3220 delete event.hudadd.pos;
3221 delete event.hudadd.name;
3222 delete event.hudadd.scale;
3223 delete event.hudadd.text;
3224 delete event.hudadd.align;
3225 delete event.hudadd.offset;
3226 delete event.hudadd.world_pos;
3227 delete event.hudadd.size;
3232 HudElement *e = player->removeHud(event.hudrm.id);
3240 u32 id = event.hudchange.id;
3241 HudElement *e = player->getHud(id);
3244 delete event.hudchange.v3fdata;
3245 delete event.hudchange.v2fdata;
3246 delete event.hudchange.sdata;
3247 delete event.hudchange.v2s32data;
3251 switch (event.hudchange.stat) {
3253 e->pos = *event.hudchange.v2fdata;
3257 e->name = *event.hudchange.sdata;
3260 case HUD_STAT_SCALE:
3261 e->scale = *event.hudchange.v2fdata;
3265 e->text = *event.hudchange.sdata;
3268 case HUD_STAT_NUMBER:
3269 e->number = event.hudchange.data;
3273 e->item = event.hudchange.data;
3277 e->dir = event.hudchange.data;
3280 case HUD_STAT_ALIGN:
3281 e->align = *event.hudchange.v2fdata;
3284 case HUD_STAT_OFFSET:
3285 e->offset = *event.hudchange.v2fdata;
3288 case HUD_STAT_WORLD_POS:
3289 e->world_pos = *event.hudchange.v3fdata;
3293 e->size = *event.hudchange.v2s32data;
3298 delete event.hudchange.v3fdata;
3299 delete event.hudchange.v2fdata;
3300 delete event.hudchange.sdata;
3301 delete event.hudchange.v2s32data;
3305 sky->setVisible(false);
3306 // Whether clouds are visible in front of a custom skybox
3307 sky->setCloudsEnabled(event.set_sky.clouds);
3314 // Handle according to type
3315 if (*event.set_sky.type == "regular") {
3316 sky->setVisible(true);
3317 sky->setCloudsEnabled(true);
3318 } else if (*event.set_sky.type == "skybox" &&
3319 event.set_sky.params->size() == 6) {
3320 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3321 skybox = smgr->addSkyBoxSceneNode(
3322 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3323 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3324 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3325 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3326 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3327 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3329 // Handle everything else as plain color
3331 if (*event.set_sky.type != "plain")
3332 infostream << "Unknown sky type: "
3333 << (*event.set_sky.type) << std::endl;
3335 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3338 delete event.set_sky.bgcolor;
3339 delete event.set_sky.type;
3340 delete event.set_sky.params;
3343 case CE_OVERRIDE_DAY_NIGHT_RATIO:
3344 client->getEnv().setDayNightRatioOverride(
3345 event.override_day_night_ratio.do_override,
3346 event.override_day_night_ratio.ratio_f * 1000);
3349 case CE_CLOUD_PARAMS:
3351 clouds->setDensity(event.cloud_params.density);
3352 clouds->setColorBright(video::SColor(event.cloud_params.color_bright));
3353 clouds->setColorAmbient(video::SColor(event.cloud_params.color_ambient));
3354 clouds->setHeight(event.cloud_params.height);
3355 clouds->setThickness(event.cloud_params.thickness);
3356 clouds->setSpeed(v2f(
3357 event.cloud_params.speed_x,
3358 event.cloud_params.speed_y));
3363 // unknown or unhandled type
3371 void Game::updateCamera(u32 busy_time, f32 dtime)
3373 LocalPlayer *player = client->getEnv().getLocalPlayer();
3376 For interaction purposes, get info about the held item
3378 - Is it a usable item?
3379 - Can it point to liquids?
3381 ItemStack playeritem;
3383 InventoryList *mlist = local_inventory->getList("main");
3385 if (mlist && client->getPlayerItem() < mlist->getSize())
3386 playeritem = mlist->getItem(client->getPlayerItem());
3389 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3390 InventoryList *hlist = local_inventory->getList("hand");
3392 playeritem = hlist->getItem(0);
3396 ToolCapabilities playeritem_toolcap =
3397 playeritem.getToolCapabilities(itemdef_manager);
3399 v3s16 old_camera_offset = camera->getOffset();
3401 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3402 GenericCAO *playercao = player->getCAO();
3404 // If playercao not loaded, don't change camera
3408 camera->toggleCameraMode();
3410 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3411 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3414 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3415 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3417 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3418 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3420 camera->step(dtime);
3422 v3f camera_position = camera->getPosition();
3423 v3f camera_direction = camera->getDirection();
3424 f32 camera_fov = camera->getFovMax();
3425 v3s16 camera_offset = camera->getOffset();
3427 m_camera_offset_changed = (camera_offset != old_camera_offset);
3429 if (!flags.disable_camera_update) {
3430 client->getEnv().getClientMap().updateCamera(camera_position,
3431 camera_direction, camera_fov, camera_offset);
3433 if (m_camera_offset_changed) {
3434 client->updateCameraOffset(camera_offset);
3435 client->getEnv().updateCameraOffset(camera_offset);
3438 clouds->updateCameraOffset(camera_offset);
3444 void Game::updateSound(f32 dtime)
3446 // Update sound listener
3447 v3s16 camera_offset = camera->getOffset();
3448 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3449 v3f(0, 0, 0), // velocity
3450 camera->getDirection(),
3451 camera->getCameraNode()->getUpVector());
3453 // Check if volume is in the proper range, else fix it.
3454 float old_volume = g_settings->getFloat("sound_volume");
3455 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
3456 sound->setListenerGain(new_volume);
3458 if (old_volume != new_volume) {
3459 g_settings->setFloat("sound_volume", new_volume);
3462 LocalPlayer *player = client->getEnv().getLocalPlayer();
3464 // Tell the sound maker whether to make footstep sounds
3465 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3467 // Update sound maker
3468 if (player->makes_footstep_sound)
3469 soundmaker->step(dtime);
3471 ClientMap &map = client->getEnv().getClientMap();
3472 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3473 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3477 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3479 LocalPlayer *player = client->getEnv().getLocalPlayer();
3481 ItemStack playeritem;
3483 InventoryList *mlist = local_inventory->getList("main");
3485 if (mlist && client->getPlayerItem() < mlist->getSize())
3486 playeritem = mlist->getItem(client->getPlayerItem());
3489 const ItemDefinition &playeritem_def =
3490 playeritem.getDefinition(itemdef_manager);
3491 InventoryList *hlist = local_inventory->getList("hand");
3492 const ItemDefinition &hand_def =
3493 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3495 v3f player_position = player->getPosition();
3496 v3f camera_position = camera->getPosition();
3497 v3f camera_direction = camera->getDirection();
3498 v3s16 camera_offset = camera->getOffset();
3502 Calculate what block is the crosshair pointing to
3505 f32 d = playeritem_def.range; // max. distance
3506 f32 d_hand = hand_def.range;
3508 if (d < 0 && d_hand >= 0)
3513 core::line3d<f32> shootline;
3515 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3516 shootline = core::line3d<f32>(camera_position,
3517 camera_position + camera_direction * BS * d);
3519 // prevent player pointing anything in front-view
3520 shootline = core::line3d<f32>(camera_position,camera_position);
3523 #ifdef HAVE_TOUCHSCREENGUI
3525 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3526 shootline = g_touchscreengui->getShootline();
3527 shootline.start += intToFloat(camera_offset, BS);
3528 shootline.end += intToFloat(camera_offset, BS);
3533 PointedThing pointed = updatePointedThing(shootline,
3534 playeritem_def.liquids_pointable,
3535 !runData.ldown_for_dig,
3538 if (pointed != runData.pointed_old) {
3539 infostream << "Pointing at " << pointed.dump() << std::endl;
3540 hud->updateSelectionMesh(camera_offset);
3545 - releasing left mouse button
3546 - pointing away from node
3548 if (runData.digging) {
3549 if (getLeftReleased()) {
3550 infostream << "Left button released"
3551 << " (stopped digging)" << std::endl;
3552 runData.digging = false;
3553 } else if (pointed != runData.pointed_old) {
3554 if (pointed.type == POINTEDTHING_NODE
3555 && runData.pointed_old.type == POINTEDTHING_NODE
3556 && pointed.node_undersurface
3557 == runData.pointed_old.node_undersurface) {
3558 // Still pointing to the same node, but a different face.
3561 infostream << "Pointing away from node"
3562 << " (stopped digging)" << std::endl;
3563 runData.digging = false;
3564 hud->updateSelectionMesh(camera_offset);
3568 if (!runData.digging) {
3569 client->interact(1, runData.pointed_old);
3570 client->setCrack(-1, v3s16(0, 0, 0));
3571 runData.dig_time = 0.0;
3573 } else if (runData.dig_instantly && getLeftReleased()) {
3574 // Remove e.g. torches faster when clicking instead of holding LMB
3575 runData.nodig_delay_timer = 0;
3576 runData.dig_instantly = false;
3579 if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3580 runData.ldown_for_dig = false;
3583 runData.left_punch = false;
3585 soundmaker->m_player_leftpunch_sound.name = "";
3587 if (isRightPressed())
3588 runData.repeat_rightclick_timer += dtime;
3590 runData.repeat_rightclick_timer = 0;
3592 if (playeritem_def.usable && isLeftPressed()) {
3593 if (getLeftClicked() && (!client->moddingEnabled()
3594 || !client->getScript()->on_item_use(playeritem, pointed)))
3595 client->interact(4, pointed);
3596 } else if (pointed.type == POINTEDTHING_NODE) {
3597 ToolCapabilities playeritem_toolcap =
3598 playeritem.getToolCapabilities(itemdef_manager);
3599 if (playeritem.name.empty() && hand_def.tool_capabilities != NULL) {
3600 playeritem_toolcap = *hand_def.tool_capabilities;
3602 handlePointingAtNode(pointed, playeritem_def, playeritem_toolcap, dtime);
3603 } else if (pointed.type == POINTEDTHING_OBJECT) {
3604 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3605 } else if (isLeftPressed()) {
3606 // When button is held down in air, show continuous animation
3607 runData.left_punch = true;
3608 } else if (getRightClicked()) {
3609 handlePointingAtNothing(playeritem);
3612 runData.pointed_old = pointed;
3614 if (runData.left_punch || getLeftClicked())
3615 camera->setDigging(0); // left click animation
3617 input->resetLeftClicked();
3618 input->resetRightClicked();
3620 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3621 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3623 input->resetLeftReleased();
3624 input->resetRightReleased();
3626 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3627 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3631 PointedThing Game::updatePointedThing(
3632 const core::line3d<f32> &shootline,
3633 bool liquids_pointable,
3634 bool look_for_object,
3635 const v3s16 &camera_offset)
3637 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3638 selectionboxes->clear();
3639 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3640 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3641 "show_entity_selectionbox");
3643 ClientMap &map = client->getEnv().getClientMap();
3644 INodeDefManager *nodedef=client->getNodeDefManager();
3646 runData.selected_object = NULL;
3648 PointedThing result=client->getEnv().getPointedThing(
3649 shootline, liquids_pointable, look_for_object);
3650 if (result.type == POINTEDTHING_OBJECT) {
3651 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3652 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox()) {
3653 aabb3f *selection_box = runData.selected_object->getSelectionBox();
3655 // Box should exist because object was
3656 // returned in the first place
3658 assert(selection_box);
3660 v3f pos = runData.selected_object->getPosition();
3661 selectionboxes->push_back(aabb3f(
3662 selection_box->MinEdge, selection_box->MaxEdge));
3663 selectionboxes->push_back(
3664 aabb3f(selection_box->MinEdge, selection_box->MaxEdge));
3665 hud->setSelectionPos(pos, camera_offset);
3667 } else if (result.type == POINTEDTHING_NODE) {
3668 // Update selection boxes
3669 MapNode n = map.getNodeNoEx(result.node_undersurface);
3670 std::vector<aabb3f> boxes;
3671 n.getSelectionBoxes(nodedef, &boxes,
3672 n.getNeighbors(result.node_undersurface, &map));
3675 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3676 i != boxes.end(); ++i) {
3678 box.MinEdge -= v3f(d, d, d);
3679 box.MaxEdge += v3f(d, d, d);
3680 selectionboxes->push_back(box);
3682 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3684 hud->setSelectedFaceNormal(v3f(
3685 result.intersection_normal.X,
3686 result.intersection_normal.Y,
3687 result.intersection_normal.Z));
3690 // Update selection mesh light level and vertex colors
3691 if (selectionboxes->size() > 0) {
3692 v3f pf = hud->getSelectionPos();
3693 v3s16 p = floatToInt(pf, BS);
3695 // Get selection mesh light level
3696 MapNode n = map.getNodeNoEx(p);
3697 u16 node_light = getInteriorLight(n, -1, nodedef);
3698 u16 light_level = node_light;
3700 for (u8 i = 0; i < 6; i++) {
3701 n = map.getNodeNoEx(p + g_6dirs[i]);
3702 node_light = getInteriorLight(n, -1, nodedef);
3703 if (node_light > light_level)
3704 light_level = node_light;
3707 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3709 final_color_blend(&c, light_level, daynight_ratio);
3711 // Modify final color a bit with time
3712 u32 timer = porting::getTimeMs() % 5000;
3713 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3714 float sin_r = 0.08 * sin(timerf);
3715 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3716 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3717 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3718 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3719 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3721 // Set mesh final color
3722 hud->setSelectionMeshColor(c);
3728 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3730 infostream << "Right Clicked in Air" << std::endl;
3731 PointedThing fauxPointed;
3732 fauxPointed.type = POINTEDTHING_NOTHING;
3733 client->interact(5, fauxPointed);
3737 void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
3738 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3740 v3s16 nodepos = pointed.node_undersurface;
3741 v3s16 neighbourpos = pointed.node_abovesurface;
3744 Check information text of node
3747 ClientMap &map = client->getEnv().getClientMap();
3749 if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3750 && client->checkPrivilege("interact")) {
3751 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3754 // This should be done after digging handling
3755 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3758 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3760 MapNode n = map.getNodeNoEx(nodepos);
3762 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3763 infotext = L"Unknown node: ";
3764 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3768 if ((getRightClicked() ||
3769 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3770 client->checkPrivilege("interact")) {
3771 runData.repeat_rightclick_timer = 0;
3772 infostream << "Ground right-clicked" << std::endl;
3774 if (meta && meta->getString("formspec") != "" && !random_input
3775 && !isKeyDown(KeyType::SNEAK)) {
3776 infostream << "Launching custom inventory view" << std::endl;
3778 InventoryLocation inventoryloc;
3779 inventoryloc.setNodeMeta(nodepos);
3781 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3782 &client->getEnv().getClientMap(), nodepos);
3783 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3785 create_formspec_menu(¤t_formspec, client,
3786 device, &input->joystick, fs_src, txt_dst);
3789 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3791 // Report right click to server
3793 camera->setDigging(1); // right click animation (always shown for feedback)
3795 // If the wielded item has node placement prediction,
3797 bool placed = nodePlacementPrediction(*client,
3799 nodepos, neighbourpos);
3803 client->interact(3, pointed);
3805 soundmaker->m_player_rightpunch_sound =
3806 playeritem_def.sound_place;
3808 if (client->moddingEnabled())
3809 client->getScript()->on_placenode(pointed, playeritem_def);
3811 soundmaker->m_player_rightpunch_sound =
3814 if (playeritem_def.node_placement_prediction == "" ||
3815 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3816 client->interact(3, pointed); // Report to server
3818 soundmaker->m_player_rightpunch_sound =
3819 playeritem_def.sound_place_failed;
3827 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3828 const v3f &player_position, bool show_debug)
3830 infotext = unescape_enriched(
3831 utf8_to_wide(runData.selected_object->infoText()));
3834 if (infotext != L"") {
3837 infotext += unescape_enriched(utf8_to_wide(
3838 runData.selected_object->debugInfoText()));
3841 if (isLeftPressed()) {
3842 bool do_punch = false;
3843 bool do_punch_damage = false;
3845 if (runData.object_hit_delay_timer <= 0.0) {
3847 do_punch_damage = true;
3848 runData.object_hit_delay_timer = object_hit_delay;
3851 if (getLeftClicked())
3855 infostream << "Left-clicked object" << std::endl;
3856 runData.left_punch = true;
3859 if (do_punch_damage) {
3860 // Report direct punch
3861 v3f objpos = runData.selected_object->getPosition();
3862 v3f dir = (objpos - player_position).normalize();
3863 ItemStack item = playeritem;
3864 if (playeritem.name.empty()) {
3865 InventoryList *hlist = local_inventory->getList("hand");
3867 item = hlist->getItem(0);
3871 bool disable_send = runData.selected_object->directReportPunch(
3872 dir, &item, runData.time_from_last_punch);
3873 runData.time_from_last_punch = 0;
3876 client->interact(0, pointed);
3878 } else if (getRightClicked()) {
3879 infostream << "Right-clicked object" << std::endl;
3880 client->interact(3, pointed); // place
3885 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3886 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3888 LocalPlayer *player = client->getEnv().getLocalPlayer();
3889 ClientMap &map = client->getEnv().getClientMap();
3890 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3892 // NOTE: Similar piece of code exists on the server side for
3894 // Get digging parameters
3895 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3896 &playeritem_toolcap);
3898 // If can't dig, try hand
3899 if (!params.diggable) {
3900 InventoryList *hlist = local_inventory->getList("hand");
3901 const ItemDefinition &hand =
3902 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3903 const ToolCapabilities *tp = hand.tool_capabilities;
3906 params = getDigParams(nodedef_manager->get(n).groups, tp);
3909 if (!params.diggable) {
3910 // I guess nobody will wait for this long
3911 runData.dig_time_complete = 10000000.0;
3913 runData.dig_time_complete = params.time;
3915 if (m_cache_enable_particles) {
3916 const ContentFeatures &features =
3917 client->getNodeDefManager()->get(n);
3918 client->getParticleManager()->addPunchingParticles(client, smgr,
3919 player, nodepos, n, features);
3923 if (!runData.digging) {
3924 infostream << "Started digging" << std::endl;
3925 runData.dig_instantly = runData.dig_time_complete == 0;
3926 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3928 client->interact(0, pointed);
3929 runData.digging = true;
3930 runData.ldown_for_dig = true;
3933 if (!runData.dig_instantly) {
3934 runData.dig_index = (float)crack_animation_length
3936 / runData.dig_time_complete;
3938 // This is for e.g. torches
3939 runData.dig_index = crack_animation_length;
3942 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3944 if (sound_dig.exists() && params.diggable) {
3945 if (sound_dig.name == "__group") {
3946 if (params.main_group != "") {
3947 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3948 soundmaker->m_player_leftpunch_sound.name =
3949 std::string("default_dig_") +
3953 soundmaker->m_player_leftpunch_sound = sound_dig;
3957 // Don't show cracks if not diggable
3958 if (runData.dig_time_complete >= 100000.0) {
3959 } else if (runData.dig_index < crack_animation_length) {
3960 //TimeTaker timer("client.setTempMod");
3961 //infostream<<"dig_index="<<dig_index<<std::endl;
3962 client->setCrack(runData.dig_index, nodepos);
3964 infostream << "Digging completed" << std::endl;
3965 client->setCrack(-1, v3s16(0, 0, 0));
3967 runData.dig_time = 0;
3968 runData.digging = false;
3970 runData.nodig_delay_timer =
3971 runData.dig_time_complete / (float)crack_animation_length;
3973 // We don't want a corresponding delay to very time consuming nodes
3974 // and nodes without digging time (e.g. torches) get a fixed delay.
3975 if (runData.nodig_delay_timer > 0.3)
3976 runData.nodig_delay_timer = 0.3;
3977 else if (runData.dig_instantly)
3978 runData.nodig_delay_timer = 0.15;
3980 bool is_valid_position;
3981 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3982 if (is_valid_position) {
3983 if (client->moddingEnabled() &&
3984 client->getScript()->on_dignode(nodepos, wasnode)) {
3987 client->removeNode(nodepos);
3990 client->interact(2, pointed);
3992 if (m_cache_enable_particles) {
3993 const ContentFeatures &features =
3994 client->getNodeDefManager()->get(wasnode);
3995 client->getParticleManager()->addDiggingParticles(client, smgr,
3996 player, nodepos, wasnode, features);
4000 // Send event to trigger sound
4001 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4002 client->event()->put(e);
4005 if (runData.dig_time_complete < 100000.0) {
4006 runData.dig_time += dtime;
4008 runData.dig_time = 0;
4009 client->setCrack(-1, nodepos);
4012 camera->setDigging(0); // left click animation
4016 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
4017 const CameraOrientation &cam)
4019 LocalPlayer *player = client->getEnv().getLocalPlayer();
4025 if (draw_control->range_all) {
4026 runData.fog_range = 100000 * BS;
4028 runData.fog_range = draw_control->wanted_range * BS;
4032 Calculate general brightness
4034 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4035 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4036 float direct_brightness;
4039 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4040 direct_brightness = time_brightness;
4041 sunlight_seen = true;
4043 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4044 float old_brightness = sky->getBrightness();
4045 direct_brightness = client->getEnv().getClientMap()
4046 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
4047 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4051 float time_of_day_smooth = runData.time_of_day_smooth;
4052 float time_of_day = client->getEnv().getTimeOfDayF();
4054 static const float maxsm = 0.05;
4055 static const float todsm = 0.05;
4057 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4058 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4059 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4060 time_of_day_smooth = time_of_day;
4062 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4063 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4064 + (time_of_day + 1.0) * todsm;
4066 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4067 + time_of_day * todsm;
4069 runData.time_of_day = time_of_day;
4070 runData.time_of_day_smooth = time_of_day_smooth;
4072 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4073 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4074 player->getPitch());
4080 v3f player_position = player->getPosition();
4081 if (sky->getCloudsVisible()) {
4082 clouds->setVisible(true);
4083 clouds->step(dtime);
4084 clouds->update(v2f(player_position.X, player_position.Z),
4085 sky->getCloudColor());
4087 clouds->setVisible(false);
4094 client->getParticleManager()->step(dtime);
4100 if (m_cache_enable_fog && !flags.force_fog_off) {
4103 video::EFT_FOG_LINEAR,
4104 runData.fog_range * m_cache_fog_start,
4105 runData.fog_range * 1.0,
4113 video::EFT_FOG_LINEAR,
4123 Get chat messages from client
4126 v2u32 screensize = driver->getScreenSize();
4128 updateChat(*client, dtime, flags.show_debug, screensize,
4129 flags.show_chat, runData.profiler_current_page,
4130 *chat_backend, guitext_chat);
4136 if (client->getPlayerItem() != runData.new_playeritem)
4137 client->selectPlayerItem(runData.new_playeritem);
4139 // Update local inventory if it has changed
4140 if (client->getLocalInventoryUpdated()) {
4141 //infostream<<"Updating local inventory"<<std::endl;
4142 client->getLocalInventory(*local_inventory);
4143 runData.update_wielded_item_trigger = true;
4146 if (runData.update_wielded_item_trigger) {
4147 // Update wielded tool
4148 InventoryList *mlist = local_inventory->getList("main");
4150 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4151 ItemStack item = mlist->getItem(client->getPlayerItem());
4152 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4153 InventoryList *hlist = local_inventory->getList("hand");
4155 item = hlist->getItem(0);
4157 camera->wield(item);
4160 runData.update_wielded_item_trigger = false;
4164 Update block draw list every 200ms or when camera direction has
4167 runData.update_draw_list_timer += dtime;
4169 v3f camera_direction = camera->getDirection();
4170 if (runData.update_draw_list_timer >= 0.2
4171 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4172 || m_camera_offset_changed) {
4173 runData.update_draw_list_timer = 0;
4174 client->getEnv().getClientMap().updateDrawList(driver);
4175 runData.update_draw_list_last_cam_dir = camera_direction;
4178 updateGui(*stats, dtime, cam);
4181 make sure menu is on top
4182 1. Delete formspec menu reference if menu was removed
4183 2. Else, make sure formspec menu is on top
4185 if (current_formspec) {
4186 if (current_formspec->getReferenceCount() == 1) {
4187 current_formspec->drop();
4188 current_formspec = NULL;
4189 } else if (isMenuActive()) {
4190 guiroot->bringToFront(current_formspec);
4198 const video::SColor &skycolor = sky->getSkyColor();
4200 TimeTaker tt_draw("mainloop: draw");
4201 driver->beginScene(true, true, skycolor);
4203 draw_scene(driver, smgr, *camera, *client, player, *hud, mapper,
4204 guienv, screensize, skycolor, flags.show_hud,
4205 flags.show_minimap);
4210 if (flags.show_profiler_graph)
4211 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4216 if (runData.damage_flash > 0.0) {
4217 video::SColor color(runData.damage_flash, 180, 0, 0);
4218 driver->draw2DRectangle(color,
4219 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4222 runData.damage_flash -= 100.0 * dtime;
4228 if (player->hurt_tilt_timer > 0.0) {
4229 player->hurt_tilt_timer -= dtime * 5;
4231 if (player->hurt_tilt_timer < 0)
4232 player->hurt_tilt_strength = 0;
4236 Update minimap pos and rotation
4238 if (mapper && flags.show_minimap && flags.show_hud) {
4239 mapper->setPos(floatToInt(player->getPosition(), BS));
4240 mapper->setAngle(player->getYaw());
4248 stats->drawtime = tt_draw.stop(true);
4249 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4253 inline static const char *yawToDirectionString(int yaw)
4255 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4257 yaw = wrapDegrees_0_360(yaw);
4258 yaw = (yaw + 45) % 360 / 90;
4260 return direction[yaw];
4264 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4266 v2u32 screensize = driver->getScreenSize();
4267 LocalPlayer *player = client->getEnv().getLocalPlayer();
4268 v3f player_position = player->getPosition();
4270 if (flags.show_debug) {
4271 static float drawtime_avg = 0;
4272 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4274 u16 fps = 1.0 / stats.dtime_jitter.avg;
4276 std::ostringstream os(std::ios_base::binary);
4278 << PROJECT_NAME_C " " << g_version_hash
4280 << " (R: range_all=" << draw_control->range_all << ")"
4281 << std::setprecision(0)
4282 << " drawtime = " << drawtime_avg
4283 << std::setprecision(1)
4284 << ", dtime_jitter = "
4285 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4286 << std::setprecision(1)
4287 << ", v_range = " << draw_control->wanted_range
4288 << std::setprecision(3)
4289 << ", RTT = " << client->getRTT();
4290 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4291 guitext->setVisible(true);
4293 guitext->setVisible(false);
4296 if (guitext->isVisible()) {
4297 core::rect<s32> rect(
4299 screensize.X, 5 + g_fontengine->getTextHeight()
4301 guitext->setRelativePosition(rect);
4304 if (flags.show_debug) {
4305 std::ostringstream os(std::ios_base::binary);
4306 os << std::setprecision(1) << std::fixed
4307 << "(" << (player_position.X / BS)
4308 << ", " << (player_position.Y / BS)
4309 << ", " << (player_position.Z / BS)
4310 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4311 << " " << yawToDirectionString(cam.camera_yaw)
4312 << ") (seed = " << ((u64)client->getMapSeed())
4315 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4316 ClientMap &map = client->getEnv().getClientMap();
4317 const INodeDefManager *nodedef = client->getNodeDefManager();
4318 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4319 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4320 const ContentFeatures &features = nodedef->get(n);
4321 os << " (pointing_at = " << nodedef->get(n).name
4322 << " - " << features.tiledef[0].name.c_str()
4327 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4328 guitext2->setVisible(true);
4330 core::rect<s32> rect(
4331 5, 5 + g_fontengine->getTextHeight(),
4332 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4334 guitext2->setRelativePosition(rect);
4336 guitext2->setVisible(false);
4339 setStaticText(guitext_info, infotext.c_str());
4340 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4342 float statustext_time_max = 1.5;
4344 if (!m_statustext.empty()) {
4345 runData.statustext_time += dtime;
4347 if (runData.statustext_time >= statustext_time_max) {
4349 runData.statustext_time = 0;
4353 setStaticText(guitext_status, m_statustext.c_str());
4354 guitext_status->setVisible(!m_statustext.empty());
4356 if (!m_statustext.empty()) {
4357 s32 status_width = guitext_status->getTextWidth();
4358 s32 status_height = guitext_status->getTextHeight();
4359 s32 status_y = screensize.Y - 150;
4360 s32 status_x = (screensize.X - status_width) / 2;
4361 core::rect<s32> rect(
4362 status_x , status_y - status_height,
4363 status_x + status_width, status_y
4365 guitext_status->setRelativePosition(rect);
4368 video::SColor initial_color(255, 0, 0, 0);
4370 if (guienv->getSkin())
4371 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4373 video::SColor final_color = initial_color;
4374 final_color.setAlpha(0);
4375 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4376 initial_color, final_color,
4377 pow(runData.statustext_time / statustext_time_max, 2.0f));
4378 guitext_status->setOverrideColor(fade_color);
4379 guitext_status->enableOverrideColor(true);
4384 /* Log times and stuff for visualization */
4385 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4387 Profiler::GraphValues values;
4388 g_profiler->graphGet(values);
4394 /****************************************************************************
4396 ****************************************************************************/
4398 /* On some computers framerate doesn't seem to be automatically limited
4400 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4402 // not using getRealTime is necessary for wine
4403 device->getTimer()->tick(); // Maker sure device time is up-to-date
4404 u32 time = device->getTimer()->getTime();
4405 u32 last_time = fps_timings->last_time;
4407 if (time > last_time) // Make sure time hasn't overflowed
4408 fps_timings->busy_time = time - last_time;
4410 fps_timings->busy_time = 0;
4412 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4413 ? g_settings->getFloat("pause_fps_max")
4414 : g_settings->getFloat("fps_max"));
4416 if (fps_timings->busy_time < frametime_min) {
4417 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4418 device->sleep(fps_timings->sleep_time);
4420 fps_timings->sleep_time = 0;
4423 /* Get the new value of the device timer. Note that device->sleep() may
4424 * not sleep for the entire requested time as sleep may be interrupted and
4425 * therefore it is arguably more accurate to get the new time from the
4426 * device rather than calculating it by adding sleep_time to time.
4429 device->getTimer()->tick(); // Update device timer
4430 time = device->getTimer()->getTime();
4432 if (time > last_time) // Make sure last_time hasn't overflowed
4433 *dtime = (time - last_time) / 1000.0;
4437 fps_timings->last_time = time;
4440 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4441 // pass a copy of it to this function
4442 // Note: \p msg must be allocated using new (not malloc())
4443 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4444 int percent, bool draw_clouds)
4446 draw_load_screen(msg, device, guienv, texture_src, dtime, percent,
4451 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4453 ((Game *)data)->readSettings();
4456 void Game::readSettings()
4458 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4459 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4460 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4461 m_cache_enable_particles = g_settings->getBool("enable_particles");
4462 m_cache_enable_fog = g_settings->getBool("enable_fog");
4463 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4464 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4465 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4467 m_cache_enable_noclip = g_settings->getBool("noclip");
4468 m_cache_enable_free_move = g_settings->getBool("free_move");
4470 m_cache_fog_start = g_settings->getFloat("fog_start");
4472 m_cache_cam_smoothing = 0;
4473 if (g_settings->getBool("cinematic"))
4474 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4476 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4478 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4479 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4480 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4484 /****************************************************************************/
4485 /****************************************************************************
4487 ****************************************************************************/
4488 /****************************************************************************/
4490 void Game::extendedResourceCleanup()
4492 // Extended resource accounting
4493 infostream << "Irrlicht resources after cleanup:" << std::endl;
4494 infostream << "\tRemaining meshes : "
4495 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4496 infostream << "\tRemaining textures : "
4497 << driver->getTextureCount() << std::endl;
4499 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4500 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4501 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4505 clearTextureNameCache();
4506 infostream << "\tRemaining materials: "
4507 << driver-> getMaterialRendererCount()
4508 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4511 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4512 void Game::showPauseMenu()
4515 static const std::string control_text = strgettext("Default Controls:\n"
4516 "No menu visible:\n"
4517 "- single tap: button activate\n"
4518 "- double tap: place/use\n"
4519 "- slide finger: look around\n"
4520 "Menu/Inventory visible:\n"
4521 "- double tap (outside):\n"
4523 "- touch stack, touch slot:\n"
4525 "- touch&drag, tap 2nd finger\n"
4526 " --> place single item to slot\n"
4529 static const std::string control_text_template = strgettext("Controls:\n"
4530 "- %s: move forwards\n"
4531 "- %s: move backwards\n"
4533 "- %s: move right\n"
4534 "- %s: jump/climb\n"
4535 "- %s: sneak/go down\n"
4538 "- Mouse: turn/look\n"
4539 "- Mouse left: dig/punch\n"
4540 "- Mouse right: place/use\n"
4541 "- Mouse wheel: select item\n"
4545 char control_text_buf[600];
4547 snprintf(control_text_buf, ARRLEN(control_text_buf), control_text_template.c_str(),
4548 GET_KEY_NAME(keymap_forward),
4549 GET_KEY_NAME(keymap_backward),
4550 GET_KEY_NAME(keymap_left),
4551 GET_KEY_NAME(keymap_right),
4552 GET_KEY_NAME(keymap_jump),
4553 GET_KEY_NAME(keymap_sneak),
4554 GET_KEY_NAME(keymap_drop),
4555 GET_KEY_NAME(keymap_inventory),
4556 GET_KEY_NAME(keymap_chat)
4559 std::string control_text = std::string(control_text_buf);
4560 str_formspec_escape(control_text);
4563 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4564 std::ostringstream os;
4566 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4567 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4568 << strgettext("Continue") << "]";
4570 if (!simple_singleplayer_mode) {
4571 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4572 << strgettext("Change Password") << "]";
4574 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4578 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4579 << strgettext("Sound Volume") << "]";
4580 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4581 << strgettext("Change Keys") << "]";
4583 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4584 << strgettext("Exit to Menu") << "]";
4585 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4586 << strgettext("Exit to OS") << "]"
4587 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4588 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4590 << strgettext("Game info:") << "\n";
4591 const std::string &address = client->getAddressName();
4592 static const std::string mode = strgettext("- Mode: ");
4593 if (!simple_singleplayer_mode) {
4594 Address serverAddress = client->getServerAddress();
4595 if (address != "") {
4596 os << mode << strgettext("Remote server") << "\n"
4597 << strgettext("- Address: ") << address;
4599 os << mode << strgettext("Hosting server");
4601 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4603 os << mode << strgettext("Singleplayer") << "\n";
4605 if (simple_singleplayer_mode || address == "") {
4606 static const std::string on = strgettext("On");
4607 static const std::string off = strgettext("Off");
4608 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4609 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4610 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4611 os << strgettext("- Damage: ") << damage << "\n"
4612 << strgettext("- Creative Mode: ") << creative << "\n";
4613 if (!simple_singleplayer_mode) {
4614 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4615 os << strgettext("- PvP: ") << pvp << "\n"
4616 << strgettext("- Public: ") << announced << "\n";
4617 std::string server_name = g_settings->get("server_name");
4618 str_formspec_escape(server_name);
4619 if (announced == on && server_name != "")
4620 os << strgettext("- Server Name: ") << server_name;
4627 /* Note: FormspecFormSource and LocalFormspecHandler *
4628 * are deleted by guiFormSpecMenu */
4629 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4630 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4632 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
4633 current_formspec->setFocus("btn_continue");
4634 current_formspec->doPause = true;
4637 /****************************************************************************/
4638 /****************************************************************************
4639 extern function for launching the game
4640 ****************************************************************************/
4641 /****************************************************************************/
4643 void the_game(bool *kill,
4645 InputHandler *input,
4646 IrrlichtDevice *device,
4648 const std::string &map_dir,
4649 const std::string &playername,
4650 const std::string &password,
4651 const std::string &address, // If empty local server is created
4654 std::string &error_message,
4655 ChatBackend &chat_backend,
4656 bool *reconnect_requested,
4657 const SubgameSpec &gamespec, // Used for local game
4658 bool simple_singleplayer_mode)
4662 /* Make a copy of the server address because if a local singleplayer server
4663 * is created then this is updated and we don't want to change the value
4664 * passed to us by the calling function
4666 std::string server_address = address;
4670 if (game.startup(kill, random_input, input, device, map_dir,
4671 playername, password, &server_address, port, error_message,
4672 reconnect_requested, &chat_backend, gamespec,
4673 simple_singleplayer_mode)) {
4678 } catch (SerializationError &e) {
4679 error_message = std::string("A serialization error occurred:\n")
4680 + e.what() + "\n\nThe server is probably "
4681 " running a different version of " PROJECT_NAME_C ".";
4682 errorstream << error_message << std::endl;
4683 } catch (ServerError &e) {
4684 error_message = e.what();
4685 errorstream << "ServerError: " << error_message << std::endl;
4686 } catch (ModError &e) {
4687 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4688 errorstream << "ModError: " << error_message << std::endl;