3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include "client/renderingengine.h"
27 #include "client/clientevent.h"
28 #include "client/gameui.h"
29 #include "client/inputhandler.h"
30 #include "client/tile.h" // For TextureSource
31 #include "client/keys.h"
32 #include "client/joystick_controller.h"
33 #include "clientmap.h"
36 #include "content_cao.h"
37 #include "client/event_manager.h"
38 #include "fontengine.h"
43 #include "gui/guiChatConsole.h"
44 #include "gui/guiConfirmRegistration.h"
45 #include "gui/guiFormSpecMenu.h"
46 #include "gui/guiKeyChangeMenu.h"
47 #include "gui/guiPasswordChange.h"
48 #include "gui/guiVolumeChange.h"
49 #include "gui/mainmenumanager.h"
50 #include "gui/profilergraph.h"
53 #include "nodedef.h" // Needed for determining pointing to nodes
54 #include "nodemetadata.h"
55 #include "particles.h"
63 #include "translation.h"
64 #include "util/basic_macros.h"
65 #include "util/directiontables.h"
66 #include "util/pointedthing.h"
67 #include "util/quicktune_shortcutter.h"
68 #include "irrlicht_changes/static_text.h"
70 #include "script/scripting_client.h"
74 #include "client/sound_openal.h"
76 #include "client/sound.h"
82 struct TextDestNodeMetadata : public TextDest
84 TextDestNodeMetadata(v3s16 p, Client *client)
89 // This is deprecated I guess? -celeron55
90 void gotText(const std::wstring &text)
92 std::string ntext = wide_to_utf8(text);
93 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
94 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
96 fields["text"] = ntext;
97 m_client->sendNodemetaFields(m_p, "", fields);
99 void gotText(const StringMap &fields)
101 m_client->sendNodemetaFields(m_p, "", fields);
108 struct TextDestPlayerInventory : public TextDest
110 TextDestPlayerInventory(Client *client)
115 TextDestPlayerInventory(Client *client, const std::string &formname)
118 m_formname = formname;
120 void gotText(const StringMap &fields)
122 m_client->sendInventoryFields(m_formname, fields);
128 struct LocalFormspecHandler : public TextDest
130 LocalFormspecHandler(const std::string &formname)
132 m_formname = formname;
135 LocalFormspecHandler(const std::string &formname, Client *client):
138 m_formname = formname;
141 void gotText(const StringMap &fields)
143 if (m_formname == "MT_PAUSE_MENU") {
144 if (fields.find("btn_sound") != fields.end()) {
145 g_gamecallback->changeVolume();
149 if (fields.find("btn_key_config") != fields.end()) {
150 g_gamecallback->keyConfig();
154 if (fields.find("btn_exit_menu") != fields.end()) {
155 g_gamecallback->disconnect();
159 if (fields.find("btn_exit_os") != fields.end()) {
160 g_gamecallback->exitToOS();
162 RenderingEngine::get_raw_device()->closeDevice();
167 if (fields.find("btn_change_password") != fields.end()) {
168 g_gamecallback->changePassword();
172 if (fields.find("quit") != fields.end()) {
176 if (fields.find("btn_continue") != fields.end()) {
181 if (m_formname == "MT_DEATH_SCREEN") {
182 assert(m_client != 0);
183 m_client->sendRespawn();
187 if (m_client && m_client->modsLoaded())
188 m_client->getScript()->on_formspec_input(m_formname, fields);
191 Client *m_client = nullptr;
194 /* Form update callback */
196 class NodeMetadataFormSource: public IFormSource
199 NodeMetadataFormSource(ClientMap *map, v3s16 p):
204 const std::string &getForm() const
206 static const std::string empty_string = "";
207 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
212 return meta->getString("formspec");
215 virtual std::string resolveText(const std::string &str)
217 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
222 return meta->resolveString(str);
229 class PlayerInventoryFormSource: public IFormSource
232 PlayerInventoryFormSource(Client *client):
237 const std::string &getForm() const
239 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
240 return player->inventory_formspec;
246 class NodeDugEvent: public MtEvent
252 NodeDugEvent(v3s16 p, MapNode n):
256 MtEvent::Type getType() const
258 return MtEvent::NODE_DUG;
264 ISoundManager *m_sound;
265 const NodeDefManager *m_ndef;
267 bool makes_footstep_sound;
268 float m_player_step_timer;
269 float m_player_jump_timer;
271 SimpleSoundSpec m_player_step_sound;
272 SimpleSoundSpec m_player_leftpunch_sound;
273 SimpleSoundSpec m_player_rightpunch_sound;
275 SoundMaker(ISoundManager *sound, const NodeDefManager *ndef):
278 makes_footstep_sound(true),
279 m_player_step_timer(0.0f),
280 m_player_jump_timer(0.0f)
284 void playPlayerStep()
286 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
287 m_player_step_timer = 0.03;
288 if (makes_footstep_sound)
289 m_sound->playSound(m_player_step_sound, false);
293 void playPlayerJump()
295 if (m_player_jump_timer <= 0.0f) {
296 m_player_jump_timer = 0.2f;
297 m_sound->playSound(SimpleSoundSpec("player_jump", 0.5f), false);
301 static void viewBobbingStep(MtEvent *e, void *data)
303 SoundMaker *sm = (SoundMaker *)data;
304 sm->playPlayerStep();
307 static void playerRegainGround(MtEvent *e, void *data)
309 SoundMaker *sm = (SoundMaker *)data;
310 sm->playPlayerStep();
313 static void playerJump(MtEvent *e, void *data)
315 SoundMaker *sm = (SoundMaker *)data;
316 sm->playPlayerJump();
319 static void cameraPunchLeft(MtEvent *e, void *data)
321 SoundMaker *sm = (SoundMaker *)data;
322 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
325 static void cameraPunchRight(MtEvent *e, void *data)
327 SoundMaker *sm = (SoundMaker *)data;
328 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
331 static void nodeDug(MtEvent *e, void *data)
333 SoundMaker *sm = (SoundMaker *)data;
334 NodeDugEvent *nde = (NodeDugEvent *)e;
335 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
338 static void playerDamage(MtEvent *e, void *data)
340 SoundMaker *sm = (SoundMaker *)data;
341 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
344 static void playerFallingDamage(MtEvent *e, void *data)
346 SoundMaker *sm = (SoundMaker *)data;
347 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
350 void registerReceiver(MtEventManager *mgr)
352 mgr->reg(MtEvent::VIEW_BOBBING_STEP, SoundMaker::viewBobbingStep, this);
353 mgr->reg(MtEvent::PLAYER_REGAIN_GROUND, SoundMaker::playerRegainGround, this);
354 mgr->reg(MtEvent::PLAYER_JUMP, SoundMaker::playerJump, this);
355 mgr->reg(MtEvent::CAMERA_PUNCH_LEFT, SoundMaker::cameraPunchLeft, this);
356 mgr->reg(MtEvent::CAMERA_PUNCH_RIGHT, SoundMaker::cameraPunchRight, this);
357 mgr->reg(MtEvent::NODE_DUG, SoundMaker::nodeDug, this);
358 mgr->reg(MtEvent::PLAYER_DAMAGE, SoundMaker::playerDamage, this);
359 mgr->reg(MtEvent::PLAYER_FALLING_DAMAGE, SoundMaker::playerFallingDamage, this);
362 void step(float dtime)
364 m_player_step_timer -= dtime;
365 m_player_jump_timer -= dtime;
369 // Locally stored sounds don't need to be preloaded because of this
370 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
372 std::set<std::string> m_fetched;
374 void paths_insert(std::set<std::string> &dst_paths,
375 const std::string &base,
376 const std::string &name)
378 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
379 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
380 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
381 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
382 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
383 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
384 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
385 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
386 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
387 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
388 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
391 void fetchSounds(const std::string &name,
392 std::set<std::string> &dst_paths,
393 std::set<std::string> &dst_datas)
395 if (m_fetched.count(name))
398 m_fetched.insert(name);
400 paths_insert(dst_paths, porting::path_share, name);
401 paths_insert(dst_paths, porting::path_user, name);
406 // before 1.8 there isn't a "integer interface", only float
407 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
408 typedef f32 SamplerLayer_t;
410 typedef s32 SamplerLayer_t;
414 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
417 bool *m_force_fog_off;
420 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
421 CachedPixelShaderSetting<float> m_fog_distance;
422 CachedVertexShaderSetting<float> m_animation_timer_vertex;
423 CachedPixelShaderSetting<float> m_animation_timer_pixel;
424 CachedPixelShaderSetting<float, 3> m_day_light;
425 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
426 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
427 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
428 CachedPixelShaderSetting<float, 3> m_camera_offset_pixel;
429 CachedPixelShaderSetting<float, 3> m_camera_offset_vertex;
430 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
431 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
432 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
436 void onSettingsChange(const std::string &name)
438 if (name == "enable_fog")
439 m_fog_enabled = g_settings->getBool("enable_fog");
442 static void settingsCallback(const std::string &name, void *userdata)
444 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
447 void setSky(Sky *sky) { m_sky = sky; }
449 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
450 f32 *fog_range, Client *client) :
452 m_force_fog_off(force_fog_off),
453 m_fog_range(fog_range),
454 m_sky_bg_color("skyBgColor"),
455 m_fog_distance("fogDistance"),
456 m_animation_timer_vertex("animationTimer"),
457 m_animation_timer_pixel("animationTimer"),
458 m_day_light("dayLight"),
459 m_eye_position_pixel("eyePosition"),
460 m_eye_position_vertex("eyePosition"),
461 m_minimap_yaw("yawVec"),
462 m_camera_offset_pixel("cameraOffset"),
463 m_camera_offset_vertex("cameraOffset"),
464 m_base_texture("baseTexture"),
465 m_normal_texture("normalTexture"),
466 m_texture_flags("textureFlags"),
469 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
470 m_fog_enabled = g_settings->getBool("enable_fog");
473 ~GameGlobalShaderConstantSetter()
475 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
478 virtual void onSetConstants(video::IMaterialRendererServices *services,
485 video::SColor bgcolor = m_sky->getBgColor();
486 video::SColorf bgcolorf(bgcolor);
487 float bgcolorfa[4] = {
493 m_sky_bg_color.set(bgcolorfa, services);
496 float fog_distance = 10000 * BS;
498 if (m_fog_enabled && !*m_force_fog_off)
499 fog_distance = *m_fog_range;
501 m_fog_distance.set(&fog_distance, services);
503 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
504 video::SColorf sunlight;
505 get_sunlight_color(&sunlight, daynight_ratio);
510 m_day_light.set(dnc, services);
512 u32 animation_timer = porting::getTimeMs() % 1000000;
513 float animation_timer_f = (float)animation_timer / 100000.f;
514 m_animation_timer_vertex.set(&animation_timer_f, services);
515 m_animation_timer_pixel.set(&animation_timer_f, services);
517 float eye_position_array[3];
518 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
519 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
520 eye_position_array[0] = epos.X;
521 eye_position_array[1] = epos.Y;
522 eye_position_array[2] = epos.Z;
524 epos.getAs3Values(eye_position_array);
526 m_eye_position_pixel.set(eye_position_array, services);
527 m_eye_position_vertex.set(eye_position_array, services);
529 if (m_client->getMinimap()) {
530 float minimap_yaw_array[3];
531 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
532 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
533 minimap_yaw_array[0] = minimap_yaw.X;
534 minimap_yaw_array[1] = minimap_yaw.Y;
535 minimap_yaw_array[2] = minimap_yaw.Z;
537 minimap_yaw.getAs3Values(minimap_yaw_array);
539 m_minimap_yaw.set(minimap_yaw_array, services);
542 float camera_offset_array[3];
543 v3f offset = intToFloat(m_client->getCamera()->getOffset(), BS);
544 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
545 camera_offset_array[0] = offset.X;
546 camera_offset_array[1] = offset.Y;
547 camera_offset_array[2] = offset.Z;
549 offset.getAs3Values(camera_offset_array);
551 m_camera_offset_pixel.set(camera_offset_array, services);
552 m_camera_offset_vertex.set(camera_offset_array, services);
554 SamplerLayer_t base_tex = 0,
557 m_base_texture.set(&base_tex, services);
558 m_normal_texture.set(&normal_tex, services);
559 m_texture_flags.set(&flags_tex, services);
564 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
567 bool *m_force_fog_off;
570 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
572 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
573 f32 *fog_range, Client *client) :
575 m_force_fog_off(force_fog_off),
576 m_fog_range(fog_range),
580 void setSky(Sky *sky) {
582 for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
583 ggscs->setSky(m_sky);
585 created_nosky.clear();
588 virtual IShaderConstantSetter* create()
590 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
591 m_sky, m_force_fog_off, m_fog_range, m_client);
593 created_nosky.push_back(scs);
599 #define SIZE_TAG "size[11,5.5]"
601 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
604 /****************************************************************************
606 ****************************************************************************/
608 const float object_hit_delay = 0.2;
611 u32 last_time, busy_time, sleep_time;
615 /* The reason the following structs are not anonymous structs within the
616 * class is that they are not used by the majority of member functions and
617 * many functions that do require objects of thse types do not modify them
618 * (so they can be passed as a const qualified parameter)
624 PointedThing pointed_old;
628 bool digging_blocked;
630 bool reset_jump_timer;
631 float nodig_delay_timer;
633 float dig_time_complete;
634 float repeat_rightclick_timer;
635 float object_hit_delay_timer;
636 float time_from_last_punch;
637 ClientActiveObject *selected_object;
641 float update_draw_list_timer;
645 v3f update_draw_list_last_cam_dir;
647 float time_of_day_smooth;
652 struct ClientEventHandler
654 void (Game::*handler)(ClientEvent *, CameraOrientation *);
657 /****************************************************************************
659 ****************************************************************************/
661 /* This is not intended to be a public class. If a public class becomes
662 * desirable then it may be better to create another 'wrapper' class that
663 * hides most of the stuff in this class (nothing in this class is required
664 * by any other file) but exposes the public methods/data only.
671 bool startup(bool *kill,
674 const std::string &map_dir,
675 const std::string &playername,
676 const std::string &password,
677 // If address is "", local server is used and address is updated
678 std::string *address,
680 std::string &error_message,
682 ChatBackend *chat_backend,
683 const SubgameSpec &gamespec, // Used for local game
684 bool simple_singleplayer_mode);
691 void extendedResourceCleanup();
693 // Basic initialisation
694 bool init(const std::string &map_dir, std::string *address,
696 const SubgameSpec &gamespec);
698 bool createSingleplayerServer(const std::string &map_dir,
699 const SubgameSpec &gamespec, u16 port, std::string *address);
702 bool createClient(const std::string &playername,
703 const std::string &password, std::string *address, u16 port);
707 bool connectToServer(const std::string &playername,
708 const std::string &password, std::string *address, u16 port,
709 bool *connect_ok, bool *aborted);
710 bool getServerContent(bool *aborted);
714 void updateInteractTimers(f32 dtime);
715 bool checkConnection();
716 bool handleCallbacks();
717 void processQueues();
718 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
719 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
720 void updateProfilerGraphs(ProfilerGraph *graph);
723 void processUserInput(f32 dtime);
724 void processKeyInput();
725 void processItemSelection(u16 *new_playeritem);
727 void dropSelectedItem(bool single_item = false);
728 void openInventory();
729 void openConsole(float scale, const wchar_t *line=NULL);
730 void toggleFreeMove();
731 void toggleFreeMoveAlt();
732 void togglePitchMove();
735 void toggleCinematic();
736 void toggleAutoforward();
738 void toggleMinimap(bool shift_pressed);
741 void toggleUpdateCamera();
743 void increaseViewRange();
744 void decreaseViewRange();
745 void toggleFullViewRange();
746 void checkZoomEnabled();
748 void updateCameraDirection(CameraOrientation *cam, float dtime);
749 void updateCameraOrientation(CameraOrientation *cam, float dtime);
750 void updatePlayerControl(const CameraOrientation &cam);
751 void step(f32 *dtime);
752 void processClientEvents(CameraOrientation *cam);
753 void updateCamera(u32 busy_time, f32 dtime);
754 void updateSound(f32 dtime);
755 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
757 * Returns the object or node the player is pointing at.
758 * Also updates the selected thing in the Hud.
760 * @param[in] shootline the shootline, starting from
761 * the camera position. This also gives the maximal distance
763 * @param[in] liquids_pointable if false, liquids are ignored
764 * @param[in] look_for_object if false, objects are ignored
765 * @param[in] camera_offset offset of the camera
766 * @param[out] selected_object the selected object or
769 PointedThing updatePointedThing(
770 const core::line3d<f32> &shootline, bool liquids_pointable,
771 bool look_for_object, const v3s16 &camera_offset);
772 void handlePointingAtNothing(const ItemStack &playerItem);
773 void handlePointingAtNode(const PointedThing &pointed,
774 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime);
775 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
776 const v3f &player_position, bool show_debug);
777 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
778 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime);
779 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
780 const CameraOrientation &cam);
783 void limitFps(FpsControl *fps_timings, f32 *dtime);
785 void showOverlayMessage(const char *msg, float dtime, int percent,
786 bool draw_clouds = true);
788 static void settingChangedCallback(const std::string &setting_name, void *data);
791 inline bool isKeyDown(GameKeyType k)
793 return input->isKeyDown(k);
795 inline bool wasKeyDown(GameKeyType k)
797 return input->wasKeyDown(k);
801 void handleAndroidChatInput();
806 bool force_fog_off = false;
807 bool disable_camera_update = false;
810 void showDeathFormspec();
811 void showPauseMenu();
813 // ClientEvent handlers
814 void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam);
815 void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam);
816 void handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam);
817 void handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam);
818 void handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam);
819 void handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam);
820 void handleClientEvent_HandleParticleEvent(ClientEvent *event,
821 CameraOrientation *cam);
822 void handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam);
823 void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam);
824 void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam);
825 void handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam);
826 void handleClientEvent_SetSun(ClientEvent *event, CameraOrientation *cam);
827 void handleClientEvent_SetMoon(ClientEvent *event, CameraOrientation *cam);
828 void handleClientEvent_SetStars(ClientEvent *event, CameraOrientation *cam);
829 void handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
830 CameraOrientation *cam);
831 void handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam);
833 void updateChat(f32 dtime, const v2u32 &screensize);
835 bool nodePlacement(const ItemDefinition &selected_def, const ItemStack &selected_item,
836 const v3s16 &nodepos, const v3s16 &neighbourpos, const PointedThing &pointed,
837 const NodeMetadata *meta);
838 static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX];
840 InputHandler *input = nullptr;
842 Client *client = nullptr;
843 Server *server = nullptr;
845 IWritableTextureSource *texture_src = nullptr;
846 IWritableShaderSource *shader_src = nullptr;
848 // When created, these will be filled with data received from the server
849 IWritableItemDefManager *itemdef_manager = nullptr;
850 NodeDefManager *nodedef_manager = nullptr;
852 GameOnDemandSoundFetcher soundfetcher; // useful when testing
853 ISoundManager *sound = nullptr;
854 bool sound_is_dummy = false;
855 SoundMaker *soundmaker = nullptr;
857 ChatBackend *chat_backend = nullptr;
859 EventManager *eventmgr = nullptr;
860 QuicktuneShortcutter *quicktune = nullptr;
861 bool registration_confirmation_shown = false;
863 std::unique_ptr<GameUI> m_game_ui;
864 GUIChatConsole *gui_chat_console = nullptr; // Free using ->Drop()
865 MapDrawControl *draw_control = nullptr;
866 Camera *camera = nullptr;
867 Clouds *clouds = nullptr; // Free using ->Drop()
868 Sky *sky = nullptr; // Free using ->Drop()
870 Minimap *mapper = nullptr;
876 This class does take ownership/responsibily for cleaning up etc of any of
877 these items (e.g. device)
879 IrrlichtDevice *device;
880 video::IVideoDriver *driver;
881 scene::ISceneManager *smgr;
883 std::string *error_message;
884 bool *reconnect_requested;
885 scene::ISceneNode *skybox;
888 bool simple_singleplayer_mode;
891 /* Pre-calculated values
893 int crack_animation_length;
895 IntervalLimiter profiler_interval;
898 * TODO: Local caching of settings is not optimal and should at some stage
899 * be updated to use a global settings object for getting thse values
900 * (as opposed to the this local caching). This can be addressed in
903 bool m_cache_doubletap_jump;
904 bool m_cache_enable_clouds;
905 bool m_cache_enable_joysticks;
906 bool m_cache_enable_particles;
907 bool m_cache_enable_fog;
908 bool m_cache_enable_noclip;
909 bool m_cache_enable_free_move;
910 f32 m_cache_mouse_sensitivity;
911 f32 m_cache_joystick_frustum_sensitivity;
912 f32 m_repeat_right_click_time;
913 f32 m_cache_cam_smoothing;
914 f32 m_cache_fog_start;
916 bool m_invert_mouse = false;
917 bool m_first_loop_after_window_activation = false;
918 bool m_camera_offset_changed = false;
920 bool m_does_lost_focus_pause_game = false;
923 bool m_cache_hold_aux1;
924 bool m_android_chat_open;
929 m_game_ui(new GameUI())
931 g_settings->registerChangedCallback("doubletap_jump",
932 &settingChangedCallback, this);
933 g_settings->registerChangedCallback("enable_clouds",
934 &settingChangedCallback, this);
935 g_settings->registerChangedCallback("doubletap_joysticks",
936 &settingChangedCallback, this);
937 g_settings->registerChangedCallback("enable_particles",
938 &settingChangedCallback, this);
939 g_settings->registerChangedCallback("enable_fog",
940 &settingChangedCallback, this);
941 g_settings->registerChangedCallback("mouse_sensitivity",
942 &settingChangedCallback, this);
943 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
944 &settingChangedCallback, this);
945 g_settings->registerChangedCallback("repeat_rightclick_time",
946 &settingChangedCallback, this);
947 g_settings->registerChangedCallback("noclip",
948 &settingChangedCallback, this);
949 g_settings->registerChangedCallback("free_move",
950 &settingChangedCallback, this);
951 g_settings->registerChangedCallback("cinematic",
952 &settingChangedCallback, this);
953 g_settings->registerChangedCallback("cinematic_camera_smoothing",
954 &settingChangedCallback, this);
955 g_settings->registerChangedCallback("camera_smoothing",
956 &settingChangedCallback, this);
961 m_cache_hold_aux1 = false; // This is initialised properly later
968 /****************************************************************************
970 ****************************************************************************/
979 delete server; // deleted first to stop all server threads
987 delete nodedef_manager;
988 delete itemdef_manager;
991 extendedResourceCleanup();
993 g_settings->deregisterChangedCallback("doubletap_jump",
994 &settingChangedCallback, this);
995 g_settings->deregisterChangedCallback("enable_clouds",
996 &settingChangedCallback, this);
997 g_settings->deregisterChangedCallback("enable_particles",
998 &settingChangedCallback, this);
999 g_settings->deregisterChangedCallback("enable_fog",
1000 &settingChangedCallback, this);
1001 g_settings->deregisterChangedCallback("mouse_sensitivity",
1002 &settingChangedCallback, this);
1003 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1004 &settingChangedCallback, this);
1005 g_settings->deregisterChangedCallback("noclip",
1006 &settingChangedCallback, this);
1007 g_settings->deregisterChangedCallback("free_move",
1008 &settingChangedCallback, this);
1009 g_settings->deregisterChangedCallback("cinematic",
1010 &settingChangedCallback, this);
1011 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1012 &settingChangedCallback, this);
1013 g_settings->deregisterChangedCallback("camera_smoothing",
1014 &settingChangedCallback, this);
1017 bool Game::startup(bool *kill,
1019 InputHandler *input,
1020 const std::string &map_dir,
1021 const std::string &playername,
1022 const std::string &password,
1023 std::string *address, // can change if simple_singleplayer_mode
1025 std::string &error_message,
1027 ChatBackend *chat_backend,
1028 const SubgameSpec &gamespec,
1029 bool simple_singleplayer_mode)
1032 this->device = RenderingEngine::get_raw_device();
1034 this->error_message = &error_message;
1035 this->reconnect_requested = reconnect;
1036 this->random_input = random_input;
1037 this->input = input;
1038 this->chat_backend = chat_backend;
1039 this->simple_singleplayer_mode = simple_singleplayer_mode;
1041 input->keycache.populate();
1043 driver = device->getVideoDriver();
1044 smgr = RenderingEngine::get_scene_manager();
1046 RenderingEngine::get_scene_manager()->getParameters()->
1047 setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1050 runData = GameRunData();
1051 runData.time_from_last_punch = 10.0;
1053 m_game_ui->initFlags();
1055 m_invert_mouse = g_settings->getBool("invert_mouse");
1056 m_first_loop_after_window_activation = true;
1058 g_client_translations->clear();
1060 if (!init(map_dir, address, port, gamespec))
1063 if (!createClient(playername, password, address, port))
1066 RenderingEngine::initialize(client, hud);
1074 ProfilerGraph graph;
1075 RunStats stats = { 0 };
1076 CameraOrientation cam_view_target = { 0 };
1077 CameraOrientation cam_view = { 0 };
1078 FpsControl draw_times = { 0 };
1079 f32 dtime; // in seconds
1081 /* Clear the profiler */
1082 Profiler::GraphValues dummyvalues;
1083 g_profiler->graphGet(dummyvalues);
1085 draw_times.last_time = RenderingEngine::get_timer_time();
1087 set_light_table(g_settings->getFloat("display_gamma"));
1090 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1091 && client->checkPrivilege("fast");
1094 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1095 g_settings->getU16("screen_h"));
1097 while (RenderingEngine::run()
1098 && !(*kill || g_gamecallback->shutdown_requested
1099 || (server && server->isShutdownRequested()))) {
1101 const irr::core::dimension2d<u32> ¤t_screen_size =
1102 RenderingEngine::get_video_driver()->getScreenSize();
1103 // Verify if window size has changed and save it if it's the case
1104 // Ensure evaluating settings->getBool after verifying screensize
1105 // First condition is cheaper
1106 if (previous_screen_size != current_screen_size &&
1107 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1108 g_settings->getBool("autosave_screensize")) {
1109 g_settings->setU16("screen_w", current_screen_size.Width);
1110 g_settings->setU16("screen_h", current_screen_size.Height);
1111 previous_screen_size = current_screen_size;
1114 // Calculate dtime =
1115 // RenderingEngine::run() from this iteration
1116 // + Sleep time until the wanted FPS are reached
1117 limitFps(&draw_times, &dtime);
1119 // Prepare render data for next iteration
1121 updateStats(&stats, draw_times, dtime);
1122 updateInteractTimers(dtime);
1124 if (!checkConnection())
1126 if (!handleCallbacks())
1131 m_game_ui->clearInfoText();
1132 hud->resizeHotbar();
1134 updateProfilers(stats, draw_times, dtime);
1135 processUserInput(dtime);
1136 // Update camera before player movement to avoid camera lag of one frame
1137 updateCameraDirection(&cam_view_target, dtime);
1138 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1139 cam_view.camera_yaw) * m_cache_cam_smoothing;
1140 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1141 cam_view.camera_pitch) * m_cache_cam_smoothing;
1142 updatePlayerControl(cam_view);
1144 processClientEvents(&cam_view_target);
1145 updateCamera(draw_times.busy_time, dtime);
1147 processPlayerInteraction(dtime, m_game_ui->m_flags.show_hud,
1148 m_game_ui->m_flags.show_debug);
1149 updateFrame(&graph, &stats, dtime, cam_view);
1150 updateProfilerGraphs(&graph);
1152 // Update if minimap has been disabled by the server
1153 m_game_ui->m_flags.show_minimap &= client->shouldShowMinimap();
1155 if (m_does_lost_focus_pause_game && !device->isWindowFocused() && !isMenuActive()) {
1162 void Game::shutdown()
1164 RenderingEngine::finalize();
1165 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1166 if (g_settings->get("3d_mode") == "pageflip") {
1167 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1170 auto formspec = m_game_ui->getFormspecGUI();
1172 formspec->quitMenu();
1174 showOverlayMessage(N_("Shutting down..."), 0, 0, false);
1179 if (gui_chat_console)
1180 gui_chat_console->drop();
1186 while (g_menumgr.menuCount() > 0) {
1187 g_menumgr.m_stack.front()->setVisible(false);
1188 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1191 m_game_ui->deleteFormspec();
1193 chat_backend->addMessage(L"", L"# Disconnected.");
1194 chat_backend->addMessage(L"", L"");
1198 while (!client->isShutdown()) {
1199 assert(texture_src != NULL);
1200 assert(shader_src != NULL);
1201 texture_src->processQueue();
1202 shader_src->processQueue();
1209 /****************************************************************************/
1210 /****************************************************************************
1212 ****************************************************************************/
1213 /****************************************************************************/
1216 const std::string &map_dir,
1217 std::string *address,
1219 const SubgameSpec &gamespec)
1221 texture_src = createTextureSource();
1223 showOverlayMessage(N_("Loading..."), 0, 0);
1225 shader_src = createShaderSource();
1227 itemdef_manager = createItemDefManager();
1228 nodedef_manager = createNodeDefManager();
1230 eventmgr = new EventManager();
1231 quicktune = new QuicktuneShortcutter();
1233 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1234 && eventmgr && quicktune))
1240 // Create a server if not connecting to an existing one
1241 if (address->empty()) {
1242 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1249 bool Game::initSound()
1252 if (g_settings->getBool("enable_sound")) {
1253 infostream << "Attempting to use OpenAL audio" << std::endl;
1254 sound = createOpenALSoundManager(g_sound_manager_singleton.get(), &soundfetcher);
1256 infostream << "Failed to initialize OpenAL audio" << std::endl;
1258 infostream << "Sound disabled." << std::endl;
1262 infostream << "Using dummy audio." << std::endl;
1263 sound = &dummySoundManager;
1264 sound_is_dummy = true;
1267 soundmaker = new SoundMaker(sound, nodedef_manager);
1271 soundmaker->registerReceiver(eventmgr);
1276 bool Game::createSingleplayerServer(const std::string &map_dir,
1277 const SubgameSpec &gamespec, u16 port, std::string *address)
1279 showOverlayMessage(N_("Creating server..."), 0, 5);
1281 std::string bind_str = g_settings->get("bind_address");
1282 Address bind_addr(0, 0, 0, 0, port);
1284 if (g_settings->getBool("ipv6_server")) {
1285 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1289 bind_addr.Resolve(bind_str.c_str());
1290 } catch (ResolveError &e) {
1291 infostream << "Resolving bind address \"" << bind_str
1292 << "\" failed: " << e.what()
1293 << " -- Listening on all addresses." << std::endl;
1296 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1297 *error_message = "Unable to listen on " +
1298 bind_addr.serializeString() +
1299 " because IPv6 is disabled";
1300 errorstream << *error_message << std::endl;
1304 server = new Server(map_dir, gamespec, simple_singleplayer_mode, bind_addr, false);
1311 bool Game::createClient(const std::string &playername,
1312 const std::string &password, std::string *address, u16 port)
1314 showOverlayMessage(N_("Creating client..."), 0, 10);
1316 draw_control = new MapDrawControl;
1320 bool could_connect, connect_aborted;
1321 #ifdef HAVE_TOUCHSCREENGUI
1322 if (g_touchscreengui) {
1323 g_touchscreengui->init(texture_src);
1324 g_touchscreengui->hide();
1327 if (!connectToServer(playername, password, address, port,
1328 &could_connect, &connect_aborted))
1331 if (!could_connect) {
1332 if (error_message->empty() && !connect_aborted) {
1333 // Should not happen if error messages are set properly
1334 *error_message = "Connection failed for unknown reason";
1335 errorstream << *error_message << std::endl;
1340 if (!getServerContent(&connect_aborted)) {
1341 if (error_message->empty() && !connect_aborted) {
1342 // Should not happen if error messages are set properly
1343 *error_message = "Connection failed for unknown reason";
1344 errorstream << *error_message << std::endl;
1349 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1350 &m_flags.force_fog_off, &runData.fog_range, client);
1351 shader_src->addShaderConstantSetterFactory(scsf);
1353 // Update cached textures, meshes and materials
1354 client->afterContentReceived();
1358 camera = new Camera(*draw_control, client);
1359 if (!camera || !camera->successfullyCreated(*error_message))
1361 client->setCamera(camera);
1365 if (m_cache_enable_clouds) {
1366 clouds = new Clouds(smgr, -1, time(0));
1368 *error_message = "Memory allocation error (clouds)";
1369 errorstream << *error_message << std::endl;
1376 sky = new Sky(-1, texture_src);
1378 skybox = NULL; // This is used/set later on in the main run loop
1381 *error_message = "Memory allocation error sky";
1382 errorstream << *error_message << std::endl;
1386 /* Pre-calculated values
1388 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1390 v2u32 size = t->getOriginalSize();
1391 crack_animation_length = size.Y / size.X;
1393 crack_animation_length = 5;
1399 /* Set window caption
1401 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1403 str += utf8_to_wide(g_version_hash);
1405 str += driver->getName();
1407 device->setWindowCaption(str.c_str());
1409 LocalPlayer *player = client->getEnv().getLocalPlayer();
1410 player->hurt_tilt_timer = 0;
1411 player->hurt_tilt_strength = 0;
1413 hud = new Hud(guienv, client, player, &player->inventory);
1416 *error_message = "Memory error: could not create HUD";
1417 errorstream << *error_message << std::endl;
1421 mapper = client->getMinimap();
1423 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1424 if (client->modsLoaded())
1425 client->getScript()->on_minimap_ready(mapper);
1431 bool Game::initGui()
1435 // Remove stale "recent" chat messages from previous connections
1436 chat_backend->clearRecentChat();
1438 // Make sure the size of the recent messages buffer is right
1439 chat_backend->applySettings();
1441 // Chat backend and console
1442 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
1443 -1, chat_backend, client, &g_menumgr);
1444 if (!gui_chat_console) {
1445 *error_message = "Could not allocate memory for chat console";
1446 errorstream << *error_message << std::endl;
1450 #ifdef HAVE_TOUCHSCREENGUI
1452 if (g_touchscreengui)
1453 g_touchscreengui->show();
1460 bool Game::connectToServer(const std::string &playername,
1461 const std::string &password, std::string *address, u16 port,
1462 bool *connect_ok, bool *connection_aborted)
1464 *connect_ok = false; // Let's not be overly optimistic
1465 *connection_aborted = false;
1466 bool local_server_mode = false;
1468 showOverlayMessage(N_("Resolving address..."), 0, 15);
1470 Address connect_address(0, 0, 0, 0, port);
1473 connect_address.Resolve(address->c_str());
1475 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1476 //connect_address.Resolve("localhost");
1477 if (connect_address.isIPv6()) {
1478 IPv6AddressBytes addr_bytes;
1479 addr_bytes.bytes[15] = 1;
1480 connect_address.setAddress(&addr_bytes);
1482 connect_address.setAddress(127, 0, 0, 1);
1484 local_server_mode = true;
1486 } catch (ResolveError &e) {
1487 *error_message = std::string("Couldn't resolve address: ") + e.what();
1488 errorstream << *error_message << std::endl;
1492 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1493 *error_message = "Unable to connect to " +
1494 connect_address.serializeString() +
1495 " because IPv6 is disabled";
1496 errorstream << *error_message << std::endl;
1500 client = new Client(playername.c_str(), password, *address,
1501 *draw_control, texture_src, shader_src,
1502 itemdef_manager, nodedef_manager, sound, eventmgr,
1503 connect_address.isIPv6(), m_game_ui.get());
1508 client->m_simple_singleplayer_mode = simple_singleplayer_mode;
1510 infostream << "Connecting to server at ";
1511 connect_address.print(&infostream);
1512 infostream << std::endl;
1514 client->connect(connect_address,
1515 simple_singleplayer_mode || local_server_mode);
1518 Wait for server to accept connection
1524 FpsControl fps_control = { 0 };
1526 f32 wait_time = 0; // in seconds
1528 fps_control.last_time = RenderingEngine::get_timer_time();
1530 while (RenderingEngine::run()) {
1532 limitFps(&fps_control, &dtime);
1534 // Update client and server
1535 client->step(dtime);
1538 server->step(dtime);
1541 if (client->getState() == LC_Init) {
1547 if (*connection_aborted)
1550 if (client->accessDenied()) {
1551 *error_message = "Access denied. Reason: "
1552 + client->accessDeniedReason();
1553 *reconnect_requested = client->reconnectRequested();
1554 errorstream << *error_message << std::endl;
1558 if (input->cancelPressed()) {
1559 *connection_aborted = true;
1560 infostream << "Connect aborted [Escape]" << std::endl;
1564 if (client->m_is_registration_confirmation_state) {
1565 if (registration_confirmation_shown) {
1566 // Keep drawing the GUI
1567 RenderingEngine::draw_menu_scene(guienv, dtime, true);
1569 registration_confirmation_shown = true;
1570 (new GUIConfirmRegistration(guienv, guienv->getRootGUIElement(), -1,
1571 &g_menumgr, client, playername, password,
1572 connection_aborted, texture_src))->drop();
1576 // Only time out if we aren't waiting for the server we started
1577 if (!address->empty() && wait_time > 10) {
1578 *error_message = "Connection timed out.";
1579 errorstream << *error_message << std::endl;
1584 showOverlayMessage(N_("Connecting to server..."), dtime, 20);
1587 } catch (con::PeerNotFoundException &e) {
1588 // TODO: Should something be done here? At least an info/error
1596 bool Game::getServerContent(bool *aborted)
1600 FpsControl fps_control = { 0 };
1601 f32 dtime; // in seconds
1603 fps_control.last_time = RenderingEngine::get_timer_time();
1605 while (RenderingEngine::run()) {
1607 limitFps(&fps_control, &dtime);
1609 // Update client and server
1610 client->step(dtime);
1613 server->step(dtime);
1616 if (client->mediaReceived() && client->itemdefReceived() &&
1617 client->nodedefReceived()) {
1622 if (!checkConnection())
1625 if (client->getState() < LC_Init) {
1626 *error_message = "Client disconnected";
1627 errorstream << *error_message << std::endl;
1631 if (input->cancelPressed()) {
1633 infostream << "Connect aborted [Escape]" << std::endl;
1640 if (!client->itemdefReceived()) {
1641 const wchar_t *text = wgettext("Item definitions...");
1643 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1646 } else if (!client->nodedefReceived()) {
1647 const wchar_t *text = wgettext("Node definitions...");
1649 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1653 std::stringstream message;
1654 std::fixed(message);
1655 message.precision(0);
1656 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
1657 message.precision(2);
1659 if ((USE_CURL == 0) ||
1660 (!g_settings->getBool("enable_remote_media_server"))) {
1661 float cur = client->getCurRate();
1662 std::string cur_unit = gettext("KiB/s");
1666 cur_unit = gettext("MiB/s");
1669 message << " (" << cur << ' ' << cur_unit << ")";
1672 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
1673 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
1674 texture_src, dtime, progress);
1682 /****************************************************************************/
1683 /****************************************************************************
1685 ****************************************************************************/
1686 /****************************************************************************/
1688 inline void Game::updateInteractTimers(f32 dtime)
1690 if (runData.nodig_delay_timer >= 0)
1691 runData.nodig_delay_timer -= dtime;
1693 if (runData.object_hit_delay_timer >= 0)
1694 runData.object_hit_delay_timer -= dtime;
1696 runData.time_from_last_punch += dtime;
1700 /* returns false if game should exit, otherwise true
1702 inline bool Game::checkConnection()
1704 if (client->accessDenied()) {
1705 *error_message = "Access denied. Reason: "
1706 + client->accessDeniedReason();
1707 *reconnect_requested = client->reconnectRequested();
1708 errorstream << *error_message << std::endl;
1716 /* returns false if game should exit, otherwise true
1718 inline bool Game::handleCallbacks()
1720 if (g_gamecallback->disconnect_requested) {
1721 g_gamecallback->disconnect_requested = false;
1725 if (g_gamecallback->changepassword_requested) {
1726 (new GUIPasswordChange(guienv, guiroot, -1,
1727 &g_menumgr, client, texture_src))->drop();
1728 g_gamecallback->changepassword_requested = false;
1731 if (g_gamecallback->changevolume_requested) {
1732 (new GUIVolumeChange(guienv, guiroot, -1,
1733 &g_menumgr, texture_src))->drop();
1734 g_gamecallback->changevolume_requested = false;
1737 if (g_gamecallback->keyconfig_requested) {
1738 (new GUIKeyChangeMenu(guienv, guiroot, -1,
1739 &g_menumgr, texture_src))->drop();
1740 g_gamecallback->keyconfig_requested = false;
1743 if (g_gamecallback->keyconfig_changed) {
1744 input->keycache.populate(); // update the cache with new settings
1745 g_gamecallback->keyconfig_changed = false;
1752 void Game::processQueues()
1754 texture_src->processQueue();
1755 itemdef_manager->processQueue(client);
1756 shader_src->processQueue();
1760 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times,
1763 float profiler_print_interval =
1764 g_settings->getFloat("profiler_print_interval");
1765 bool print_to_log = true;
1767 if (profiler_print_interval == 0) {
1768 print_to_log = false;
1769 profiler_print_interval = 3;
1772 if (profiler_interval.step(dtime, profiler_print_interval)) {
1774 infostream << "Profiler:" << std::endl;
1775 g_profiler->print(infostream);
1778 m_game_ui->updateProfiler();
1779 g_profiler->clear();
1782 // Update update graphs
1783 g_profiler->graphAdd("Time non-rendering [ms]",
1784 draw_times.busy_time - stats.drawtime);
1786 g_profiler->graphAdd("Sleep [ms]", draw_times.sleep_time);
1787 g_profiler->graphAdd("FPS", 1.0f / dtime);
1790 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
1797 /* Time average and jitter calculation
1799 jp = &stats->dtime_jitter;
1800 jp->avg = jp->avg * 0.96 + dtime * 0.04;
1802 jitter = dtime - jp->avg;
1804 if (jitter > jp->max)
1807 jp->counter += dtime;
1809 if (jp->counter > 0.0) {
1811 jp->max_sample = jp->max;
1812 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
1816 /* Busytime average and jitter calculation
1818 jp = &stats->busy_time_jitter;
1819 jp->avg = jp->avg + draw_times.busy_time * 0.02;
1821 jitter = draw_times.busy_time - jp->avg;
1823 if (jitter > jp->max)
1825 if (jitter < jp->min)
1828 jp->counter += dtime;
1830 if (jp->counter > 0.0) {
1832 jp->max_sample = jp->max;
1833 jp->min_sample = jp->min;
1841 /****************************************************************************
1843 ****************************************************************************/
1845 void Game::processUserInput(f32 dtime)
1847 // Reset input if window not active or some menu is active
1848 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
1850 #ifdef HAVE_TOUCHSCREENGUI
1851 g_touchscreengui->hide();
1854 #ifdef HAVE_TOUCHSCREENGUI
1855 else if (g_touchscreengui) {
1856 /* on touchscreengui step may generate own input events which ain't
1857 * what we want in case we just did clear them */
1858 g_touchscreengui->step(dtime);
1862 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
1863 gui_chat_console->closeConsoleAtOnce();
1866 // Input handler step() (used by the random input generator)
1870 auto formspec = m_game_ui->getFormspecGUI();
1872 formspec->getAndroidUIInput();
1874 handleAndroidChatInput();
1877 // Increase timer for double tap of "keymap_jump"
1878 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
1879 runData.jump_timer += dtime;
1882 processItemSelection(&runData.new_playeritem);
1886 void Game::processKeyInput()
1888 if (wasKeyDown(KeyType::DROP)) {
1889 dropSelectedItem(isKeyDown(KeyType::SNEAK));
1890 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
1891 toggleAutoforward();
1892 } else if (wasKeyDown(KeyType::BACKWARD)) {
1893 if (g_settings->getBool("continuous_forward"))
1894 toggleAutoforward();
1895 } else if (wasKeyDown(KeyType::INVENTORY)) {
1897 } else if (input->cancelPressed()) {
1899 m_android_chat_open = false;
1901 if (!gui_chat_console->isOpenInhibited()) {
1904 } else if (wasKeyDown(KeyType::CHAT)) {
1905 openConsole(0.2, L"");
1906 } else if (wasKeyDown(KeyType::CMD)) {
1907 openConsole(0.2, L"/");
1908 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
1909 if (client->modsLoaded())
1910 openConsole(0.2, L".");
1912 m_game_ui->showStatusText(wgettext("Client side scripting is disabled"));
1913 } else if (wasKeyDown(KeyType::CONSOLE)) {
1914 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
1915 } else if (wasKeyDown(KeyType::FREEMOVE)) {
1917 } else if (wasKeyDown(KeyType::JUMP)) {
1918 toggleFreeMoveAlt();
1919 } else if (wasKeyDown(KeyType::PITCHMOVE)) {
1921 } else if (wasKeyDown(KeyType::FASTMOVE)) {
1923 } else if (wasKeyDown(KeyType::NOCLIP)) {
1926 } else if (wasKeyDown(KeyType::MUTE)) {
1927 if (g_settings->getBool("enable_sound")) {
1928 bool new_mute_sound = !g_settings->getBool("mute_sound");
1929 g_settings->setBool("mute_sound", new_mute_sound);
1931 m_game_ui->showTranslatedStatusText("Sound muted");
1933 m_game_ui->showTranslatedStatusText("Sound unmuted");
1935 m_game_ui->showTranslatedStatusText("Sound system is disabled");
1937 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
1938 if (g_settings->getBool("enable_sound")) {
1939 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
1941 g_settings->setFloat("sound_volume", new_volume);
1942 const wchar_t *str = wgettext("Volume changed to %d%%");
1943 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1945 m_game_ui->showStatusText(buf);
1947 m_game_ui->showTranslatedStatusText("Sound system is disabled");
1949 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
1950 if (g_settings->getBool("enable_sound")) {
1951 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
1953 g_settings->setFloat("sound_volume", new_volume);
1954 const wchar_t *str = wgettext("Volume changed to %d%%");
1955 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1957 m_game_ui->showStatusText(buf);
1959 m_game_ui->showTranslatedStatusText("Sound system is disabled");
1962 } else if (wasKeyDown(KeyType::MUTE) || wasKeyDown(KeyType::INC_VOLUME)
1963 || wasKeyDown(KeyType::DEC_VOLUME)) {
1964 m_game_ui->showTranslatedStatusText("Sound system is not supported on this build");
1966 } else if (wasKeyDown(KeyType::CINEMATIC)) {
1968 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
1969 client->makeScreenshot();
1970 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
1971 m_game_ui->toggleHud();
1972 } else if (wasKeyDown(KeyType::MINIMAP)) {
1973 toggleMinimap(isKeyDown(KeyType::SNEAK));
1974 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
1975 m_game_ui->toggleChat();
1976 } else if (wasKeyDown(KeyType::TOGGLE_FOG)) {
1978 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
1979 toggleUpdateCamera();
1980 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
1982 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
1983 m_game_ui->toggleProfiler();
1984 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
1985 increaseViewRange();
1986 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
1987 decreaseViewRange();
1988 } else if (wasKeyDown(KeyType::RANGESELECT)) {
1989 toggleFullViewRange();
1990 } else if (wasKeyDown(KeyType::ZOOM)) {
1992 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
1994 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
1996 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
1998 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2002 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2003 runData.reset_jump_timer = false;
2004 runData.jump_timer = 0.0f;
2007 if (quicktune->hasMessage()) {
2008 m_game_ui->showStatusText(utf8_to_wide(quicktune->getMessage()));
2012 void Game::processItemSelection(u16 *new_playeritem)
2014 LocalPlayer *player = client->getEnv().getLocalPlayer();
2016 /* Item selection using mouse wheel
2018 *new_playeritem = player->getWieldIndex();
2020 s32 wheel = input->getMouseWheel();
2021 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2022 player->hud_hotbar_itemcount - 1);
2026 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2027 wasKeyDown(KeyType::HOTBAR_NEXT)) {
2031 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2032 wasKeyDown(KeyType::HOTBAR_PREV)) {
2037 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2039 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2042 /* Item selection using hotbar slot keys
2044 for (u16 i = 0; i <= max_item; i++) {
2045 if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
2046 *new_playeritem = i;
2053 void Game::dropSelectedItem(bool single_item)
2055 IDropAction *a = new IDropAction();
2056 a->count = single_item ? 1 : 0;
2057 a->from_inv.setCurrentPlayer();
2058 a->from_list = "main";
2059 a->from_i = client->getEnv().getLocalPlayer()->getWieldIndex();
2060 client->inventoryAction(a);
2064 void Game::openInventory()
2067 * Don't permit to open inventory is CAO or player doesn't exists.
2068 * This prevent showing an empty inventory at player load
2071 LocalPlayer *player = client->getEnv().getLocalPlayer();
2072 if (!player || !player->getCAO())
2075 infostream << "Game: Launching inventory" << std::endl;
2077 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2079 InventoryLocation inventoryloc;
2080 inventoryloc.setCurrentPlayer();
2082 if (!client->modsLoaded()
2083 || !client->getScript()->on_inventory_open(fs_src->m_client->getInventory(inventoryloc))) {
2084 TextDest *txt_dst = new TextDestPlayerInventory(client);
2085 auto *&formspec = m_game_ui->updateFormspec("");
2086 GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
2087 txt_dst, client->getFormspecPrepend());
2089 formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2094 void Game::openConsole(float scale, const wchar_t *line)
2096 assert(scale > 0.0f && scale <= 1.0f);
2099 porting::showInputDialog(gettext("ok"), "", "", 2);
2100 m_android_chat_open = true;
2102 if (gui_chat_console->isOpenInhibited())
2104 gui_chat_console->openConsole(scale);
2106 gui_chat_console->setCloseOnEnter(true);
2107 gui_chat_console->replaceAndAddToHistory(line);
2113 void Game::handleAndroidChatInput()
2115 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2116 std::string text = porting::getInputDialogValue();
2117 client->typeChatMessage(utf8_to_wide(text));
2118 m_android_chat_open = false;
2124 void Game::toggleFreeMove()
2126 bool free_move = !g_settings->getBool("free_move");
2127 g_settings->set("free_move", bool_to_cstr(free_move));
2130 if (client->checkPrivilege("fly")) {
2131 m_game_ui->showTranslatedStatusText("Fly mode enabled");
2133 m_game_ui->showTranslatedStatusText("Fly mode enabled (note: no 'fly' privilege)");
2136 m_game_ui->showTranslatedStatusText("Fly mode disabled");
2140 void Game::toggleFreeMoveAlt()
2142 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2145 runData.reset_jump_timer = true;
2149 void Game::togglePitchMove()
2151 bool pitch_move = !g_settings->getBool("pitch_move");
2152 g_settings->set("pitch_move", bool_to_cstr(pitch_move));
2155 m_game_ui->showTranslatedStatusText("Pitch move mode enabled");
2157 m_game_ui->showTranslatedStatusText("Pitch move mode disabled");
2162 void Game::toggleFast()
2164 bool fast_move = !g_settings->getBool("fast_move");
2165 bool has_fast_privs = client->checkPrivilege("fast");
2166 g_settings->set("fast_move", bool_to_cstr(fast_move));
2169 if (has_fast_privs) {
2170 m_game_ui->showTranslatedStatusText("Fast mode enabled");
2172 m_game_ui->showTranslatedStatusText("Fast mode enabled (note: no 'fast' privilege)");
2175 m_game_ui->showTranslatedStatusText("Fast mode disabled");
2179 m_cache_hold_aux1 = fast_move && has_fast_privs;
2184 void Game::toggleNoClip()
2186 bool noclip = !g_settings->getBool("noclip");
2187 g_settings->set("noclip", bool_to_cstr(noclip));
2190 if (client->checkPrivilege("noclip")) {
2191 m_game_ui->showTranslatedStatusText("Noclip mode enabled");
2193 m_game_ui->showTranslatedStatusText("Noclip mode enabled (note: no 'noclip' privilege)");
2196 m_game_ui->showTranslatedStatusText("Noclip mode disabled");
2200 void Game::toggleCinematic()
2202 bool cinematic = !g_settings->getBool("cinematic");
2203 g_settings->set("cinematic", bool_to_cstr(cinematic));
2206 m_game_ui->showTranslatedStatusText("Cinematic mode enabled");
2208 m_game_ui->showTranslatedStatusText("Cinematic mode disabled");
2211 // Autoforward by toggling continuous forward.
2212 void Game::toggleAutoforward()
2214 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2215 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2217 if (autorun_enabled)
2218 m_game_ui->showTranslatedStatusText("Automatic forward enabled");
2220 m_game_ui->showTranslatedStatusText("Automatic forward disabled");
2223 void Game::toggleMinimap(bool shift_pressed)
2225 if (!mapper || !m_game_ui->m_flags.show_hud || !g_settings->getBool("enable_minimap"))
2228 if (shift_pressed) {
2229 mapper->toggleMinimapShape();
2233 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2235 MinimapMode mode = MINIMAP_MODE_OFF;
2236 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2237 mode = mapper->getMinimapMode();
2238 mode = (MinimapMode)((int)mode + 1);
2239 // If radar is disabled and in, or switching to, radar mode
2240 if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE) && mode > 3)
2241 mode = MINIMAP_MODE_OFF;
2244 m_game_ui->m_flags.show_minimap = true;
2246 case MINIMAP_MODE_SURFACEx1:
2247 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1");
2249 case MINIMAP_MODE_SURFACEx2:
2250 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2");
2252 case MINIMAP_MODE_SURFACEx4:
2253 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4");
2255 case MINIMAP_MODE_RADARx1:
2256 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1");
2258 case MINIMAP_MODE_RADARx2:
2259 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2");
2261 case MINIMAP_MODE_RADARx4:
2262 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4");
2265 mode = MINIMAP_MODE_OFF;
2266 m_game_ui->m_flags.show_minimap = false;
2267 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE)
2268 m_game_ui->showTranslatedStatusText("Minimap hidden");
2270 m_game_ui->showTranslatedStatusText("Minimap currently disabled by game or mod");
2273 mapper->setMinimapMode(mode);
2276 void Game::toggleFog()
2278 bool fog_enabled = g_settings->getBool("enable_fog");
2279 g_settings->setBool("enable_fog", !fog_enabled);
2281 m_game_ui->showTranslatedStatusText("Fog disabled");
2283 m_game_ui->showTranslatedStatusText("Fog enabled");
2287 void Game::toggleDebug()
2289 // Initial / 4x toggle: Chat only
2290 // 1x toggle: Debug text with chat
2291 // 2x toggle: Debug text with profiler graph
2292 // 3x toggle: Debug text and wireframe
2293 if (!m_game_ui->m_flags.show_debug) {
2294 m_game_ui->m_flags.show_debug = true;
2295 m_game_ui->m_flags.show_profiler_graph = false;
2296 draw_control->show_wireframe = false;
2297 m_game_ui->showTranslatedStatusText("Debug info shown");
2298 } else if (!m_game_ui->m_flags.show_profiler_graph && !draw_control->show_wireframe) {
2299 m_game_ui->m_flags.show_profiler_graph = true;
2300 m_game_ui->showTranslatedStatusText("Profiler graph shown");
2301 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2302 m_game_ui->m_flags.show_profiler_graph = false;
2303 draw_control->show_wireframe = true;
2304 m_game_ui->showTranslatedStatusText("Wireframe shown");
2306 m_game_ui->m_flags.show_debug = false;
2307 m_game_ui->m_flags.show_profiler_graph = false;
2308 draw_control->show_wireframe = false;
2309 if (client->checkPrivilege("debug")) {
2310 m_game_ui->showTranslatedStatusText("Debug info, profiler graph, and wireframe hidden");
2312 m_game_ui->showTranslatedStatusText("Debug info and profiler graph hidden");
2318 void Game::toggleUpdateCamera()
2320 m_flags.disable_camera_update = !m_flags.disable_camera_update;
2321 if (m_flags.disable_camera_update)
2322 m_game_ui->showTranslatedStatusText("Camera update disabled");
2324 m_game_ui->showTranslatedStatusText("Camera update enabled");
2328 void Game::increaseViewRange()
2330 s16 range = g_settings->getS16("viewing_range");
2331 s16 range_new = range + 10;
2335 if (range_new > 4000) {
2337 str = wgettext("Viewing range is at maximum: %d");
2338 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2340 m_game_ui->showStatusText(buf);
2343 str = wgettext("Viewing range changed to %d");
2344 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2346 m_game_ui->showStatusText(buf);
2348 g_settings->set("viewing_range", itos(range_new));
2352 void Game::decreaseViewRange()
2354 s16 range = g_settings->getS16("viewing_range");
2355 s16 range_new = range - 10;
2359 if (range_new < 20) {
2361 str = wgettext("Viewing range is at minimum: %d");
2362 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2364 m_game_ui->showStatusText(buf);
2366 str = wgettext("Viewing range changed to %d");
2367 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2369 m_game_ui->showStatusText(buf);
2371 g_settings->set("viewing_range", itos(range_new));
2375 void Game::toggleFullViewRange()
2377 draw_control->range_all = !draw_control->range_all;
2378 if (draw_control->range_all)
2379 m_game_ui->showTranslatedStatusText("Enabled unlimited viewing range");
2381 m_game_ui->showTranslatedStatusText("Disabled unlimited viewing range");
2385 void Game::checkZoomEnabled()
2387 LocalPlayer *player = client->getEnv().getLocalPlayer();
2388 if (player->getZoomFOV() < 0.001f || player->getFov().fov > 0.0f)
2389 m_game_ui->showTranslatedStatusText("Zoom currently disabled by game or mod");
2393 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2395 if ((device->isWindowActive() && device->isWindowFocused()
2396 && !isMenuActive()) || random_input) {
2399 if (!random_input) {
2400 // Mac OSX gets upset if this is set every frame
2401 if (device->getCursorControl()->isVisible())
2402 device->getCursorControl()->setVisible(false);
2406 if (m_first_loop_after_window_activation) {
2407 m_first_loop_after_window_activation = false;
2409 input->setMousePos(driver->getScreenSize().Width / 2,
2410 driver->getScreenSize().Height / 2);
2412 updateCameraOrientation(cam, dtime);
2418 // Mac OSX gets upset if this is set every frame
2419 if (!device->getCursorControl()->isVisible())
2420 device->getCursorControl()->setVisible(true);
2423 m_first_loop_after_window_activation = true;
2428 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2430 #ifdef HAVE_TOUCHSCREENGUI
2431 if (g_touchscreengui) {
2432 cam->camera_yaw += g_touchscreengui->getYawChange();
2433 cam->camera_pitch = g_touchscreengui->getPitch();
2436 v2s32 center(driver->getScreenSize().Width / 2, driver->getScreenSize().Height / 2);
2437 v2s32 dist = input->getMousePos() - center;
2439 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2443 cam->camera_yaw -= dist.X * m_cache_mouse_sensitivity;
2444 cam->camera_pitch += dist.Y * m_cache_mouse_sensitivity;
2446 if (dist.X != 0 || dist.Y != 0)
2447 input->setMousePos(center.X, center.Y);
2448 #ifdef HAVE_TOUCHSCREENGUI
2452 if (m_cache_enable_joysticks) {
2453 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
2454 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
2455 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
2458 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2462 void Game::updatePlayerControl(const CameraOrientation &cam)
2464 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2466 // DO NOT use the isKeyDown method for the forward, backward, left, right
2467 // buttons, as the code that uses the controls needs to be able to
2468 // distinguish between the two in order to know when to use joysticks.
2470 PlayerControl control(
2471 input->isKeyDown(KeyType::FORWARD),
2472 input->isKeyDown(KeyType::BACKWARD),
2473 input->isKeyDown(KeyType::LEFT),
2474 input->isKeyDown(KeyType::RIGHT),
2475 isKeyDown(KeyType::JUMP),
2476 isKeyDown(KeyType::SPECIAL1),
2477 isKeyDown(KeyType::SNEAK),
2478 isKeyDown(KeyType::ZOOM),
2479 input->getLeftState(),
2480 input->getRightState(),
2483 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
2484 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
2488 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
2489 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
2490 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
2491 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
2492 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
2493 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
2494 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
2495 ( (u32)(input->getLeftState() & 0x1) << 7) |
2496 ( (u32)(input->getRightState() & 0x1) << 8
2500 /* For Android, simulate holding down AUX1 (fast move) if the user has
2501 * the fast_move setting toggled on. If there is an aux1 key defined for
2502 * Android then its meaning is inverted (i.e. holding aux1 means walk and
2505 if (m_cache_hold_aux1) {
2506 control.aux1 = control.aux1 ^ true;
2507 keypress_bits ^= ((u32)(1U << 5));
2511 LocalPlayer *player = client->getEnv().getLocalPlayer();
2513 // autojump if set: simulate "jump" key
2514 if (player->getAutojump()) {
2515 control.jump = true;
2516 keypress_bits |= 1U << 4;
2519 // autoforward if set: simulate "up" key
2520 if (player->getPlayerSettings().continuous_forward &&
2521 client->activeObjectsReceived() && !player->isDead()) {
2523 keypress_bits |= 1U << 0;
2526 client->setPlayerControl(control);
2527 player->keyPressed = keypress_bits;
2533 inline void Game::step(f32 *dtime)
2535 bool can_be_and_is_paused =
2536 (simple_singleplayer_mode && g_menumgr.pausesGame());
2538 if (can_be_and_is_paused) { // This is for a singleplayer server
2539 *dtime = 0; // No time passes
2542 server->step(*dtime);
2544 client->step(*dtime);
2548 const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = {
2549 {&Game::handleClientEvent_None},
2550 {&Game::handleClientEvent_PlayerDamage},
2551 {&Game::handleClientEvent_PlayerForceMove},
2552 {&Game::handleClientEvent_Deathscreen},
2553 {&Game::handleClientEvent_ShowFormSpec},
2554 {&Game::handleClientEvent_ShowLocalFormSpec},
2555 {&Game::handleClientEvent_HandleParticleEvent},
2556 {&Game::handleClientEvent_HandleParticleEvent},
2557 {&Game::handleClientEvent_HandleParticleEvent},
2558 {&Game::handleClientEvent_HudAdd},
2559 {&Game::handleClientEvent_HudRemove},
2560 {&Game::handleClientEvent_HudChange},
2561 {&Game::handleClientEvent_SetSky},
2562 {&Game::handleClientEvent_SetSun},
2563 {&Game::handleClientEvent_SetMoon},
2564 {&Game::handleClientEvent_SetStars},
2565 {&Game::handleClientEvent_OverrideDayNigthRatio},
2566 {&Game::handleClientEvent_CloudParams},
2569 void Game::handleClientEvent_None(ClientEvent *event, CameraOrientation *cam)
2571 FATAL_ERROR("ClientEvent type None received");
2574 void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam)
2576 if (client->modsLoaded())
2577 client->getScript()->on_damage_taken(event->player_damage.amount);
2579 // Damage flash and hurt tilt are not used at death
2580 if (client->getHP() > 0) {
2581 runData.damage_flash += 95.0f + 3.2f * event->player_damage.amount;
2582 runData.damage_flash = MYMIN(runData.damage_flash, 127.0f);
2584 LocalPlayer *player = client->getEnv().getLocalPlayer();
2586 player->hurt_tilt_timer = 1.5f;
2587 player->hurt_tilt_strength =
2588 rangelim(event->player_damage.amount / 4.0f, 1.0f, 4.0f);
2591 // Play damage sound
2592 client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::PLAYER_DAMAGE));
2595 void Game::handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam)
2597 cam->camera_yaw = event->player_force_move.yaw;
2598 cam->camera_pitch = event->player_force_move.pitch;
2601 void Game::handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam)
2603 // If client scripting is enabled, deathscreen is handled by CSM code in
2604 // builtin/client/init.lua
2605 if (client->modsLoaded())
2606 client->getScript()->on_death();
2608 showDeathFormspec();
2610 /* Handle visualization */
2611 LocalPlayer *player = client->getEnv().getLocalPlayer();
2612 runData.damage_flash = 0;
2613 player->hurt_tilt_timer = 0;
2614 player->hurt_tilt_strength = 0;
2617 void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam)
2619 if (event->show_formspec.formspec->empty()) {
2620 auto formspec = m_game_ui->getFormspecGUI();
2621 if (formspec && (event->show_formspec.formname->empty()
2622 || *(event->show_formspec.formname) == m_game_ui->getFormspecName())) {
2623 formspec->quitMenu();
2626 FormspecFormSource *fs_src =
2627 new FormspecFormSource(*(event->show_formspec.formspec));
2628 TextDestPlayerInventory *txt_dst =
2629 new TextDestPlayerInventory(client, *(event->show_formspec.formname));
2631 auto *&formspec = m_game_ui->updateFormspec(*(event->show_formspec.formname));
2632 GUIFormSpecMenu::create(formspec, client, &input->joystick,
2633 fs_src, txt_dst, client->getFormspecPrepend());
2636 delete event->show_formspec.formspec;
2637 delete event->show_formspec.formname;
2640 void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam)
2642 FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec);
2643 LocalFormspecHandler *txt_dst =
2644 new LocalFormspecHandler(*event->show_formspec.formname, client);
2645 GUIFormSpecMenu::create(m_game_ui->getFormspecGUI(), client, &input->joystick,
2646 fs_src, txt_dst, client->getFormspecPrepend());
2648 delete event->show_formspec.formspec;
2649 delete event->show_formspec.formname;
2652 void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event,
2653 CameraOrientation *cam)
2655 LocalPlayer *player = client->getEnv().getLocalPlayer();
2656 client->getParticleManager()->handleParticleEvent(event, client, player);
2659 void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
2661 LocalPlayer *player = client->getEnv().getLocalPlayer();
2662 auto &hud_server_to_client = client->getHUDTranslationMap();
2664 u32 server_id = event->hudadd.server_id;
2665 // ignore if we already have a HUD with that ID
2666 auto i = hud_server_to_client.find(server_id);
2667 if (i != hud_server_to_client.end()) {
2668 delete event->hudadd.pos;
2669 delete event->hudadd.name;
2670 delete event->hudadd.scale;
2671 delete event->hudadd.text;
2672 delete event->hudadd.align;
2673 delete event->hudadd.offset;
2674 delete event->hudadd.world_pos;
2675 delete event->hudadd.size;
2679 HudElement *e = new HudElement;
2680 e->type = (HudElementType)event->hudadd.type;
2681 e->pos = *event->hudadd.pos;
2682 e->name = *event->hudadd.name;
2683 e->scale = *event->hudadd.scale;
2684 e->text = *event->hudadd.text;
2685 e->number = event->hudadd.number;
2686 e->item = event->hudadd.item;
2687 e->dir = event->hudadd.dir;
2688 e->align = *event->hudadd.align;
2689 e->offset = *event->hudadd.offset;
2690 e->world_pos = *event->hudadd.world_pos;
2691 e->size = *event->hudadd.size;
2692 e->z_index = event->hudadd.z_index;
2693 hud_server_to_client[server_id] = player->addHud(e);
2695 delete event->hudadd.pos;
2696 delete event->hudadd.name;
2697 delete event->hudadd.scale;
2698 delete event->hudadd.text;
2699 delete event->hudadd.align;
2700 delete event->hudadd.offset;
2701 delete event->hudadd.world_pos;
2702 delete event->hudadd.size;
2705 void Game::handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam)
2707 LocalPlayer *player = client->getEnv().getLocalPlayer();
2708 HudElement *e = player->removeHud(event->hudrm.id);
2712 void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam)
2714 LocalPlayer *player = client->getEnv().getLocalPlayer();
2716 u32 id = event->hudchange.id;
2717 HudElement *e = player->getHud(id);
2720 delete event->hudchange.v3fdata;
2721 delete event->hudchange.v2fdata;
2722 delete event->hudchange.sdata;
2723 delete event->hudchange.v2s32data;
2727 switch (event->hudchange.stat) {
2729 e->pos = *event->hudchange.v2fdata;
2733 e->name = *event->hudchange.sdata;
2736 case HUD_STAT_SCALE:
2737 e->scale = *event->hudchange.v2fdata;
2741 e->text = *event->hudchange.sdata;
2744 case HUD_STAT_NUMBER:
2745 e->number = event->hudchange.data;
2749 e->item = event->hudchange.data;
2753 e->dir = event->hudchange.data;
2756 case HUD_STAT_ALIGN:
2757 e->align = *event->hudchange.v2fdata;
2760 case HUD_STAT_OFFSET:
2761 e->offset = *event->hudchange.v2fdata;
2764 case HUD_STAT_WORLD_POS:
2765 e->world_pos = *event->hudchange.v3fdata;
2769 e->size = *event->hudchange.v2s32data;
2772 case HUD_STAT_Z_INDEX:
2773 e->z_index = event->hudchange.data;
2777 delete event->hudchange.v3fdata;
2778 delete event->hudchange.v2fdata;
2779 delete event->hudchange.sdata;
2780 delete event->hudchange.v2s32data;
2783 void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
2785 sky->setVisible(false);
2786 // Whether clouds are visible in front of a custom skybox.
2787 sky->setCloudsEnabled(event->set_sky->clouds);
2793 // Clear the old textures out in case we switch rendering type.
2794 sky->clearSkyboxTextures();
2795 // Handle according to type
2796 if (event->set_sky->type == "regular") {
2797 // Shows the mesh skybox
2798 sky->setVisible(true);
2799 // Update mesh based skybox colours if applicable.
2800 sky->setSkyColors(*event->set_sky);
2801 sky->setHorizonTint(
2802 event->set_sky->sun_tint,
2803 event->set_sky->moon_tint,
2804 event->set_sky->tint_type
2806 } else if (event->set_sky->type == "skybox" &&
2807 event->set_sky->textures.size() == 6) {
2808 // Disable the dyanmic mesh skybox:
2809 sky->setVisible(false);
2811 sky->setFallbackBgColor(event->set_sky->bgcolor);
2812 // Set sunrise and sunset fog tinting:
2813 sky->setHorizonTint(
2814 event->set_sky->sun_tint,
2815 event->set_sky->moon_tint,
2816 event->set_sky->tint_type
2818 // Add textures to skybox.
2819 for (int i = 0; i < 6; i++)
2820 sky->addTextureToSkybox(event->set_sky->textures[i], i, texture_src);
2822 // Handle everything else as plain color.
2823 if (event->set_sky->type != "plain")
2824 infostream << "Unknown sky type: "
2825 << (event->set_sky->type) << std::endl;
2826 sky->setVisible(false);
2827 sky->setFallbackBgColor(event->set_sky->bgcolor);
2828 // Disable directional sun/moon tinting on plain or invalid skyboxes.
2829 sky->setHorizonTint(
2830 event->set_sky->bgcolor,
2831 event->set_sky->bgcolor,
2835 delete event->set_sky;
2838 void Game::handleClientEvent_SetSun(ClientEvent *event, CameraOrientation *cam)
2840 sky->setSunVisible(event->sun_params->visible);
2841 sky->setSunTexture(event->sun_params->texture,
2842 event->sun_params->tonemap, texture_src);
2843 sky->setSunScale(event->sun_params->scale);
2844 sky->setSunriseVisible(event->sun_params->sunrise_visible);
2845 sky->setSunriseTexture(event->sun_params->sunrise, texture_src);
2846 delete event->sun_params;
2849 void Game::handleClientEvent_SetMoon(ClientEvent *event, CameraOrientation *cam)
2851 sky->setMoonVisible(event->moon_params->visible);
2852 sky->setMoonTexture(event->moon_params->texture,
2853 event->moon_params->tonemap, texture_src);
2854 sky->setMoonScale(event->moon_params->scale);
2855 delete event->moon_params;
2858 void Game::handleClientEvent_SetStars(ClientEvent *event, CameraOrientation *cam)
2860 sky->setStarsVisible(event->star_params->visible);
2861 sky->setStarCount(event->star_params->count, false);
2862 sky->setStarColor(event->star_params->starcolor);
2863 sky->setStarScale(event->star_params->scale);
2864 delete event->star_params;
2867 void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
2868 CameraOrientation *cam)
2870 client->getEnv().setDayNightRatioOverride(
2871 event->override_day_night_ratio.do_override,
2872 event->override_day_night_ratio.ratio_f * 1000.0f);
2875 void Game::handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam)
2880 clouds->setDensity(event->cloud_params.density);
2881 clouds->setColorBright(video::SColor(event->cloud_params.color_bright));
2882 clouds->setColorAmbient(video::SColor(event->cloud_params.color_ambient));
2883 clouds->setHeight(event->cloud_params.height);
2884 clouds->setThickness(event->cloud_params.thickness);
2885 clouds->setSpeed(v2f(event->cloud_params.speed_x, event->cloud_params.speed_y));
2888 void Game::processClientEvents(CameraOrientation *cam)
2890 while (client->hasClientEvents()) {
2891 std::unique_ptr<ClientEvent> event(client->getClientEvent());
2892 FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, "Invalid clientevent type");
2893 const ClientEventHandler& evHandler = clientEventHandler[event->type];
2894 (this->*evHandler.handler)(event.get(), cam);
2898 void Game::updateChat(f32 dtime, const v2u32 &screensize)
2900 // Add chat log output for errors to be shown in chat
2901 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
2903 // Get new messages from error log buffer
2904 while (!chat_log_error_buf.empty()) {
2905 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
2906 if (!g_settings->getBool("disable_escape_sequences")) {
2907 error_message.insert(0, L"\x1b(c@red)");
2908 error_message.append(L"\x1b(c@white)");
2910 chat_backend->addMessage(L"", error_message);
2913 // Get new messages from client
2914 std::wstring message;
2915 while (client->getChatMessage(message)) {
2916 chat_backend->addUnparsedMessage(message);
2919 // Remove old messages
2920 chat_backend->step(dtime);
2922 // Display all messages in a static text element
2923 m_game_ui->setChatText(chat_backend->getRecentChat(),
2924 chat_backend->getRecentBuffer().getLineCount());
2927 void Game::updateCamera(u32 busy_time, f32 dtime)
2929 LocalPlayer *player = client->getEnv().getLocalPlayer();
2932 For interaction purposes, get info about the held item
2934 - Is it a usable item?
2935 - Can it point to liquids?
2937 ItemStack playeritem;
2939 ItemStack selected, hand;
2940 playeritem = player->getWieldedItem(&selected, &hand);
2943 ToolCapabilities playeritem_toolcap =
2944 playeritem.getToolCapabilities(itemdef_manager);
2946 v3s16 old_camera_offset = camera->getOffset();
2948 if (wasKeyDown(KeyType::CAMERA_MODE)) {
2949 GenericCAO *playercao = player->getCAO();
2951 // If playercao not loaded, don't change camera
2955 camera->toggleCameraMode();
2957 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2958 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2961 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2962 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
2964 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2965 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio);
2966 camera->step(dtime);
2968 v3f camera_position = camera->getPosition();
2969 v3f camera_direction = camera->getDirection();
2970 f32 camera_fov = camera->getFovMax();
2971 v3s16 camera_offset = camera->getOffset();
2973 m_camera_offset_changed = (camera_offset != old_camera_offset);
2975 if (!m_flags.disable_camera_update) {
2976 client->getEnv().getClientMap().updateCamera(camera_position,
2977 camera_direction, camera_fov, camera_offset);
2979 if (m_camera_offset_changed) {
2980 client->updateCameraOffset(camera_offset);
2981 client->getEnv().updateCameraOffset(camera_offset);
2984 clouds->updateCameraOffset(camera_offset);
2990 void Game::updateSound(f32 dtime)
2992 // Update sound listener
2993 v3s16 camera_offset = camera->getOffset();
2994 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
2995 v3f(0, 0, 0), // velocity
2996 camera->getDirection(),
2997 camera->getCameraNode()->getUpVector());
2999 bool mute_sound = g_settings->getBool("mute_sound");
3001 sound->setListenerGain(0.0f);
3003 // Check if volume is in the proper range, else fix it.
3004 float old_volume = g_settings->getFloat("sound_volume");
3005 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
3006 sound->setListenerGain(new_volume);
3008 if (old_volume != new_volume) {
3009 g_settings->setFloat("sound_volume", new_volume);
3013 LocalPlayer *player = client->getEnv().getLocalPlayer();
3015 // Tell the sound maker whether to make footstep sounds
3016 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3018 // Update sound maker
3019 if (player->makes_footstep_sound)
3020 soundmaker->step(dtime);
3022 ClientMap &map = client->getEnv().getClientMap();
3023 MapNode n = map.getNode(player->getFootstepNodePos());
3024 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3028 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3030 LocalPlayer *player = client->getEnv().getLocalPlayer();
3032 const v3f camera_direction = camera->getDirection();
3033 const v3s16 camera_offset = camera->getOffset();
3036 Calculate what block is the crosshair pointing to
3039 ItemStack selected_item, hand_item;
3040 const ItemStack &tool_item = player->getWieldedItem(&selected_item, &hand_item);
3042 const ItemDefinition &selected_def = selected_item.getDefinition(itemdef_manager);
3043 f32 d = getToolRange(selected_def, hand_item.getDefinition(itemdef_manager));
3045 core::line3d<f32> shootline;
3047 switch (camera->getCameraMode()) {
3048 case CAMERA_MODE_FIRST:
3049 // Shoot from camera position, with bobbing
3050 shootline.start = camera->getPosition();
3052 case CAMERA_MODE_THIRD:
3053 // Shoot from player head, no bobbing
3054 shootline.start = camera->getHeadPosition();
3056 case CAMERA_MODE_THIRD_FRONT:
3057 shootline.start = camera->getHeadPosition();
3058 // prevent player pointing anything in front-view
3062 shootline.end = shootline.start + camera_direction * BS * d;
3064 #ifdef HAVE_TOUCHSCREENGUI
3066 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3067 shootline = g_touchscreengui->getShootline();
3068 // Scale shootline to the acual distance the player can reach
3069 shootline.end = shootline.start
3070 + shootline.getVector().normalize() * BS * d;
3071 shootline.start += intToFloat(camera_offset, BS);
3072 shootline.end += intToFloat(camera_offset, BS);
3077 PointedThing pointed = updatePointedThing(shootline,
3078 selected_def.liquids_pointable,
3079 !runData.ldown_for_dig,
3082 if (pointed != runData.pointed_old) {
3083 infostream << "Pointing at " << pointed.dump() << std::endl;
3084 hud->updateSelectionMesh(camera_offset);
3087 if (runData.digging_blocked && !input->getLeftState()) {
3088 // allow digging again if button is not pressed
3089 runData.digging_blocked = false;
3094 - releasing left mouse button
3095 - pointing away from node
3097 if (runData.digging) {
3098 if (input->getLeftReleased()) {
3099 infostream << "Left button released"
3100 << " (stopped digging)" << std::endl;
3101 runData.digging = false;
3102 } else if (pointed != runData.pointed_old) {
3103 if (pointed.type == POINTEDTHING_NODE
3104 && runData.pointed_old.type == POINTEDTHING_NODE
3105 && pointed.node_undersurface
3106 == runData.pointed_old.node_undersurface) {
3107 // Still pointing to the same node, but a different face.
3110 infostream << "Pointing away from node"
3111 << " (stopped digging)" << std::endl;
3112 runData.digging = false;
3113 hud->updateSelectionMesh(camera_offset);
3117 if (!runData.digging) {
3118 client->interact(INTERACT_STOP_DIGGING, runData.pointed_old);
3119 client->setCrack(-1, v3s16(0, 0, 0));
3120 runData.dig_time = 0.0;
3122 } else if (runData.dig_instantly && input->getLeftReleased()) {
3123 // Remove e.g. torches faster when clicking instead of holding LMB
3124 runData.nodig_delay_timer = 0;
3125 runData.dig_instantly = false;
3128 if (!runData.digging && runData.ldown_for_dig && !input->getLeftState()) {
3129 runData.ldown_for_dig = false;
3132 runData.left_punch = false;
3134 soundmaker->m_player_leftpunch_sound.name = "";
3136 // Prepare for repeating, unless we're not supposed to
3137 if (input->getRightState() && !g_settings->getBool("safe_dig_and_place"))
3138 runData.repeat_rightclick_timer += dtime;
3140 runData.repeat_rightclick_timer = 0;
3142 if (selected_def.usable && input->getLeftState()) {
3143 if (input->getLeftClicked() && (!client->modsLoaded()
3144 || !client->getScript()->on_item_use(selected_item, pointed)))
3145 client->interact(INTERACT_USE, pointed);
3146 } else if (pointed.type == POINTEDTHING_NODE) {
3147 handlePointingAtNode(pointed, selected_item, hand_item, dtime);
3148 } else if (pointed.type == POINTEDTHING_OBJECT) {
3149 v3f player_position = player->getPosition();
3150 handlePointingAtObject(pointed, tool_item, player_position, show_debug);
3151 } else if (input->getLeftState()) {
3152 // When button is held down in air, show continuous animation
3153 runData.left_punch = true;
3154 // Run callback even though item is not usable
3155 if (input->getLeftClicked() && client->modsLoaded())
3156 client->getScript()->on_item_use(selected_item, pointed);
3157 } else if (input->getRightClicked()) {
3158 handlePointingAtNothing(selected_item);
3161 runData.pointed_old = pointed;
3163 if (runData.left_punch || input->getLeftClicked())
3164 camera->setDigging(0); // left click animation
3166 input->resetLeftClicked();
3167 input->resetRightClicked();
3169 input->resetLeftReleased();
3170 input->resetRightReleased();
3174 PointedThing Game::updatePointedThing(
3175 const core::line3d<f32> &shootline,
3176 bool liquids_pointable,
3177 bool look_for_object,
3178 const v3s16 &camera_offset)
3180 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3181 selectionboxes->clear();
3182 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3183 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3184 "show_entity_selectionbox");
3186 ClientEnvironment &env = client->getEnv();
3187 ClientMap &map = env.getClientMap();
3188 const NodeDefManager *nodedef = map.getNodeDefManager();
3190 runData.selected_object = NULL;
3192 RaycastState s(shootline, look_for_object, liquids_pointable);
3193 PointedThing result;
3194 env.continueRaycast(&s, &result);
3195 if (result.type == POINTEDTHING_OBJECT) {
3196 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3197 aabb3f selection_box;
3198 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3199 runData.selected_object->getSelectionBox(&selection_box)) {
3200 v3f pos = runData.selected_object->getPosition();
3201 selectionboxes->push_back(aabb3f(selection_box));
3202 hud->setSelectionPos(pos, camera_offset);
3204 } else if (result.type == POINTEDTHING_NODE) {
3205 // Update selection boxes
3206 MapNode n = map.getNode(result.node_undersurface);
3207 std::vector<aabb3f> boxes;
3208 n.getSelectionBoxes(nodedef, &boxes,
3209 n.getNeighbors(result.node_undersurface, &map));
3212 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3213 i != boxes.end(); ++i) {
3215 box.MinEdge -= v3f(d, d, d);
3216 box.MaxEdge += v3f(d, d, d);
3217 selectionboxes->push_back(box);
3219 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3221 hud->setSelectedFaceNormal(v3f(
3222 result.intersection_normal.X,
3223 result.intersection_normal.Y,
3224 result.intersection_normal.Z));
3227 // Update selection mesh light level and vertex colors
3228 if (!selectionboxes->empty()) {
3229 v3f pf = hud->getSelectionPos();
3230 v3s16 p = floatToInt(pf, BS);
3232 // Get selection mesh light level
3233 MapNode n = map.getNode(p);
3234 u16 node_light = getInteriorLight(n, -1, nodedef);
3235 u16 light_level = node_light;
3237 for (const v3s16 &dir : g_6dirs) {
3238 n = map.getNode(p + dir);
3239 node_light = getInteriorLight(n, -1, nodedef);
3240 if (node_light > light_level)
3241 light_level = node_light;
3244 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3246 final_color_blend(&c, light_level, daynight_ratio);
3248 // Modify final color a bit with time
3249 u32 timer = porting::getTimeMs() % 5000;
3250 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3251 float sin_r = 0.08f * std::sin(timerf);
3252 float sin_g = 0.08f * std::sin(timerf + irr::core::PI * 0.5f);
3253 float sin_b = 0.08f * std::sin(timerf + irr::core::PI);
3254 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3255 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3256 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3258 // Set mesh final color
3259 hud->setSelectionMeshColor(c);
3265 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3267 infostream << "Right Clicked in Air" << std::endl;
3268 PointedThing fauxPointed;
3269 fauxPointed.type = POINTEDTHING_NOTHING;
3270 client->interact(INTERACT_ACTIVATE, fauxPointed);
3274 void Game::handlePointingAtNode(const PointedThing &pointed,
3275 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
3277 v3s16 nodepos = pointed.node_undersurface;
3278 v3s16 neighbourpos = pointed.node_abovesurface;
3281 Check information text of node
3284 ClientMap &map = client->getEnv().getClientMap();
3286 if (runData.nodig_delay_timer <= 0.0 && input->getLeftState()
3287 && !runData.digging_blocked
3288 && client->checkPrivilege("interact")) {
3289 handleDigging(pointed, nodepos, selected_item, hand_item, dtime);
3292 // This should be done after digging handling
3293 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3296 m_game_ui->setInfoText(unescape_translate(utf8_to_wide(
3297 meta->getString("infotext"))));
3299 MapNode n = map.getNode(nodepos);
3301 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3302 m_game_ui->setInfoText(L"Unknown node: " +
3303 utf8_to_wide(nodedef_manager->get(n).name));
3307 if ((input->getRightClicked() ||
3308 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3309 client->checkPrivilege("interact")) {
3310 runData.repeat_rightclick_timer = 0;
3311 infostream << "Ground right-clicked" << std::endl;
3313 camera->setDigging(1); // right click animation (always shown for feedback)
3315 soundmaker->m_player_rightpunch_sound = SimpleSoundSpec();
3317 // If the wielded item has node placement prediction,
3319 // And also set the sound and send the interact
3320 // But first check for meta formspec and rightclickable
3321 auto &def = selected_item.getDefinition(itemdef_manager);
3322 bool placed = nodePlacement(def, selected_item, nodepos, neighbourpos,
3325 if (placed && client->modsLoaded())
3326 client->getScript()->on_placenode(pointed, def);
3330 bool Game::nodePlacement(const ItemDefinition &selected_def,
3331 const ItemStack &selected_item, const v3s16 &nodepos, const v3s16 &neighbourpos,
3332 const PointedThing &pointed, const NodeMetadata *meta)
3334 std::string prediction = selected_def.node_placement_prediction;
3335 const NodeDefManager *nodedef = client->ndef();
3336 ClientMap &map = client->getEnv().getClientMap();
3338 bool is_valid_position;
3340 node = map.getNode(nodepos, &is_valid_position);
3341 if (!is_valid_position) {
3342 soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
3347 if (meta && !meta->getString("formspec").empty() && !random_input
3348 && !isKeyDown(KeyType::SNEAK)) {
3349 // on_rightclick callbacks are called anyway
3350 if (nodedef_manager->get(map.getNode(nodepos)).rightclickable)
3351 client->interact(INTERACT_PLACE, pointed);
3353 infostream << "Launching custom inventory view" << std::endl;
3355 InventoryLocation inventoryloc;
3356 inventoryloc.setNodeMeta(nodepos);
3358 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3359 &client->getEnv().getClientMap(), nodepos);
3360 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3362 auto *&formspec = m_game_ui->updateFormspec("");
3363 GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
3364 txt_dst, client->getFormspecPrepend());
3366 formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3370 // on_rightclick callback
3371 if (prediction.empty() || (nodedef->get(node).rightclickable &&
3372 !isKeyDown(KeyType::SNEAK))) {
3374 client->interact(INTERACT_PLACE, pointed);
3378 verbosestream << "Node placement prediction for "
3379 << selected_def.name << " is "
3380 << prediction << std::endl;
3381 v3s16 p = neighbourpos;
3383 // Place inside node itself if buildable_to
3384 MapNode n_under = map.getNode(nodepos, &is_valid_position);
3385 if (is_valid_position) {
3386 if (nodedef->get(n_under).buildable_to) {
3389 node = map.getNode(p, &is_valid_position);
3390 if (is_valid_position && !nodedef->get(node).buildable_to) {
3392 client->interact(INTERACT_PLACE, pointed);
3398 // Find id of predicted node
3400 bool found = nodedef->getId(prediction, id);
3403 errorstream << "Node placement prediction failed for "
3404 << selected_def.name << " (places "
3406 << ") - Name not known" << std::endl;
3407 // Handle this as if prediction was empty
3409 client->interact(INTERACT_PLACE, pointed);
3413 const ContentFeatures &predicted_f = nodedef->get(id);
3415 // Predict param2 for facedir and wallmounted nodes
3418 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3419 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
3420 v3s16 dir = nodepos - neighbourpos;
3422 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
3423 param2 = dir.Y < 0 ? 1 : 0;
3424 } else if (abs(dir.X) > abs(dir.Z)) {
3425 param2 = dir.X < 0 ? 3 : 2;
3427 param2 = dir.Z < 0 ? 5 : 4;
3431 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
3432 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
3433 v3s16 dir = nodepos - floatToInt(client->getEnv().getLocalPlayer()->getPosition(), BS);
3435 if (abs(dir.X) > abs(dir.Z)) {
3436 param2 = dir.X < 0 ? 3 : 1;
3438 param2 = dir.Z < 0 ? 2 : 0;
3442 assert(param2 <= 5);
3444 //Check attachment if node is in group attached_node
3445 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
3446 static v3s16 wallmounted_dirs[8] = {
3456 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3457 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
3458 pp = p + wallmounted_dirs[param2];
3460 pp = p + v3s16(0, -1, 0);
3462 if (!nodedef->get(map.getNode(pp)).walkable) {
3464 client->interact(INTERACT_PLACE, pointed);
3470 if ((predicted_f.param_type_2 == CPT2_COLOR
3471 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
3472 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
3473 const std::string &indexstr = selected_item.metadata.getString(
3474 "palette_index", 0);
3475 if (!indexstr.empty()) {
3476 s32 index = mystoi(indexstr);
3477 if (predicted_f.param_type_2 == CPT2_COLOR) {
3479 } else if (predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
3480 // param2 = pure palette index + other
3481 param2 = (index & 0xf8) | (param2 & 0x07);
3482 } else if (predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
3483 // param2 = pure palette index + other
3484 param2 = (index & 0xe0) | (param2 & 0x1f);
3489 // Add node to client map
3490 MapNode n(id, 0, param2);
3493 LocalPlayer *player = client->getEnv().getLocalPlayer();
3495 // Dont place node when player would be inside new node
3496 // NOTE: This is to be eventually implemented by a mod as client-side Lua
3497 if (!nodedef->get(n).walkable ||
3498 g_settings->getBool("enable_build_where_you_stand") ||
3499 (client->checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
3500 (nodedef->get(n).walkable &&
3501 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
3502 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
3503 // This triggers the required mesh update too
3504 client->addNode(p, n);
3506 client->interact(INTERACT_PLACE, pointed);
3507 // A node is predicted, also play a sound
3508 soundmaker->m_player_rightpunch_sound = selected_def.sound_place;
3511 soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
3514 } catch (InvalidPositionException &e) {
3515 errorstream << "Node placement prediction failed for "
3516 << selected_def.name << " (places "
3518 << ") - Position not loaded" << std::endl;
3519 soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
3524 void Game::handlePointingAtObject(const PointedThing &pointed,
3525 const ItemStack &tool_item, const v3f &player_position, bool show_debug)
3527 std::wstring infotext = unescape_translate(
3528 utf8_to_wide(runData.selected_object->infoText()));
3531 if (!infotext.empty()) {
3534 infotext += utf8_to_wide(runData.selected_object->debugInfoText());
3537 m_game_ui->setInfoText(infotext);
3539 if (input->getLeftState()) {
3540 bool do_punch = false;
3541 bool do_punch_damage = false;
3543 if (runData.object_hit_delay_timer <= 0.0) {
3545 do_punch_damage = true;
3546 runData.object_hit_delay_timer = object_hit_delay;
3549 if (input->getLeftClicked())
3553 infostream << "Left-clicked object" << std::endl;
3554 runData.left_punch = true;
3557 if (do_punch_damage) {
3558 // Report direct punch
3559 v3f objpos = runData.selected_object->getPosition();
3560 v3f dir = (objpos - player_position).normalize();
3562 bool disable_send = runData.selected_object->directReportPunch(
3563 dir, &tool_item, runData.time_from_last_punch);
3564 runData.time_from_last_punch = 0;
3567 client->interact(INTERACT_START_DIGGING, pointed);
3569 } else if (input->getRightClicked()) {
3570 infostream << "Right-clicked object" << std::endl;
3571 client->interact(INTERACT_PLACE, pointed); // place
3576 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3577 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
3579 // See also: serverpackethandle.cpp, action == 2
3580 LocalPlayer *player = client->getEnv().getLocalPlayer();
3581 ClientMap &map = client->getEnv().getClientMap();
3582 MapNode n = client->getEnv().getClientMap().getNode(nodepos);
3584 // NOTE: Similar piece of code exists on the server side for
3586 // Get digging parameters
3587 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3588 &selected_item.getToolCapabilities(itemdef_manager));
3590 // If can't dig, try hand
3591 if (!params.diggable) {
3592 params = getDigParams(nodedef_manager->get(n).groups,
3593 &hand_item.getToolCapabilities(itemdef_manager));
3596 if (!params.diggable) {
3597 // I guess nobody will wait for this long
3598 runData.dig_time_complete = 10000000.0;
3600 runData.dig_time_complete = params.time;
3602 if (m_cache_enable_particles) {
3603 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3604 client->getParticleManager()->addNodeParticle(client,
3605 player, nodepos, n, features);
3609 if (!runData.digging) {
3610 infostream << "Started digging" << std::endl;
3611 runData.dig_instantly = runData.dig_time_complete == 0;
3612 if (client->modsLoaded() && client->getScript()->on_punchnode(nodepos, n))
3614 client->interact(INTERACT_START_DIGGING, pointed);
3615 runData.digging = true;
3616 runData.ldown_for_dig = true;
3619 if (!runData.dig_instantly) {
3620 runData.dig_index = (float)crack_animation_length
3622 / runData.dig_time_complete;
3624 // This is for e.g. torches
3625 runData.dig_index = crack_animation_length;
3628 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3630 if (sound_dig.exists() && params.diggable) {
3631 if (sound_dig.name == "__group") {
3632 if (!params.main_group.empty()) {
3633 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3634 soundmaker->m_player_leftpunch_sound.name =
3635 std::string("default_dig_") +
3639 soundmaker->m_player_leftpunch_sound = sound_dig;
3643 // Don't show cracks if not diggable
3644 if (runData.dig_time_complete >= 100000.0) {
3645 } else if (runData.dig_index < crack_animation_length) {
3646 //TimeTaker timer("client.setTempMod");
3647 //infostream<<"dig_index="<<dig_index<<std::endl;
3648 client->setCrack(runData.dig_index, nodepos);
3650 infostream << "Digging completed" << std::endl;
3651 client->setCrack(-1, v3s16(0, 0, 0));
3653 runData.dig_time = 0;
3654 runData.digging = false;
3655 // we successfully dug, now block it from repeating if we want to be safe
3656 if (g_settings->getBool("safe_dig_and_place"))
3657 runData.digging_blocked = true;
3659 runData.nodig_delay_timer =
3660 runData.dig_time_complete / (float)crack_animation_length;
3662 // We don't want a corresponding delay to very time consuming nodes
3663 // and nodes without digging time (e.g. torches) get a fixed delay.
3664 if (runData.nodig_delay_timer > 0.3)
3665 runData.nodig_delay_timer = 0.3;
3666 else if (runData.dig_instantly)
3667 runData.nodig_delay_timer = 0.15;
3669 bool is_valid_position;
3670 MapNode wasnode = map.getNode(nodepos, &is_valid_position);
3671 if (is_valid_position) {
3672 if (client->modsLoaded() &&
3673 client->getScript()->on_dignode(nodepos, wasnode)) {
3677 const ContentFeatures &f = client->ndef()->get(wasnode);
3678 if (f.node_dig_prediction == "air") {
3679 client->removeNode(nodepos);
3680 } else if (!f.node_dig_prediction.empty()) {
3682 bool found = client->ndef()->getId(f.node_dig_prediction, id);
3684 client->addNode(nodepos, id, true);
3686 // implicit else: no prediction
3689 client->interact(INTERACT_DIGGING_COMPLETED, pointed);
3691 if (m_cache_enable_particles) {
3692 const ContentFeatures &features =
3693 client->getNodeDefManager()->get(wasnode);
3694 client->getParticleManager()->addDiggingParticles(client,
3695 player, nodepos, wasnode, features);
3699 // Send event to trigger sound
3700 client->getEventManager()->put(new NodeDugEvent(nodepos, wasnode));
3703 if (runData.dig_time_complete < 100000.0) {
3704 runData.dig_time += dtime;
3706 runData.dig_time = 0;
3707 client->setCrack(-1, nodepos);
3710 camera->setDigging(0); // left click animation
3714 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
3715 const CameraOrientation &cam)
3717 TimeTaker tt_update("Game::updateFrame()");
3718 LocalPlayer *player = client->getEnv().getLocalPlayer();
3724 if (draw_control->range_all) {
3725 runData.fog_range = 100000 * BS;
3727 runData.fog_range = draw_control->wanted_range * BS;
3731 Calculate general brightness
3733 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3734 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3735 float direct_brightness;
3738 if (m_cache_enable_noclip && m_cache_enable_free_move) {
3739 direct_brightness = time_brightness;
3740 sunlight_seen = true;
3742 float old_brightness = sky->getBrightness();
3743 direct_brightness = client->getEnv().getClientMap()
3744 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
3745 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3749 float time_of_day_smooth = runData.time_of_day_smooth;
3750 float time_of_day = client->getEnv().getTimeOfDayF();
3752 static const float maxsm = 0.05f;
3753 static const float todsm = 0.05f;
3755 if (std::fabs(time_of_day - time_of_day_smooth) > maxsm &&
3756 std::fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3757 std::fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3758 time_of_day_smooth = time_of_day;
3760 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3761 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3762 + (time_of_day + 1.0) * todsm;
3764 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3765 + time_of_day * todsm;
3767 runData.time_of_day_smooth = time_of_day_smooth;
3769 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3770 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3771 player->getPitch());
3777 if (sky->getCloudsVisible()) {
3778 clouds->setVisible(true);
3779 clouds->step(dtime);
3780 // camera->getPosition is not enough for 3rd person views
3781 v3f camera_node_position = camera->getCameraNode()->getPosition();
3782 v3s16 camera_offset = camera->getOffset();
3783 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
3784 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
3785 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
3786 clouds->update(camera_node_position,
3787 sky->getCloudColor());
3788 if (clouds->isCameraInsideCloud() && m_cache_enable_fog) {
3789 // if inside clouds, and fog enabled, use that as sky
3791 video::SColor clouds_dark = clouds->getColor()
3792 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
3793 sky->overrideColors(clouds_dark, clouds->getColor());
3794 sky->setInClouds(true);
3795 runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
3796 // do not draw clouds after all
3797 clouds->setVisible(false);
3800 clouds->setVisible(false);
3807 client->getParticleManager()->step(dtime);
3813 if (m_cache_enable_fog) {
3816 video::EFT_FOG_LINEAR,
3817 runData.fog_range * m_cache_fog_start,
3818 runData.fog_range * 1.0,
3826 video::EFT_FOG_LINEAR,
3836 Get chat messages from client
3839 v2u32 screensize = driver->getScreenSize();
3841 updateChat(dtime, screensize);
3847 if (player->getWieldIndex() != runData.new_playeritem)
3848 client->setPlayerItem(runData.new_playeritem);
3850 if (client->updateWieldedItem()) {
3851 // Update wielded tool
3852 ItemStack selected_item, hand_item;
3853 ItemStack &tool_item = player->getWieldedItem(&selected_item, &hand_item);
3854 camera->wield(tool_item);
3858 Update block draw list every 200ms or when camera direction has
3861 runData.update_draw_list_timer += dtime;
3863 v3f camera_direction = camera->getDirection();
3864 if (runData.update_draw_list_timer >= 0.2
3865 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3866 || m_camera_offset_changed) {
3867 runData.update_draw_list_timer = 0;
3868 client->getEnv().getClientMap().updateDrawList();
3869 runData.update_draw_list_last_cam_dir = camera_direction;
3872 m_game_ui->update(*stats, client, draw_control, cam, runData.pointed_old, gui_chat_console, dtime);
3875 make sure menu is on top
3876 1. Delete formspec menu reference if menu was removed
3877 2. Else, make sure formspec menu is on top
3879 auto formspec = m_game_ui->getFormspecGUI();
3880 do { // breakable. only runs for one iteration
3884 if (formspec->getReferenceCount() == 1) {
3885 m_game_ui->deleteFormspec();
3889 auto &loc = formspec->getFormspecLocation();
3890 if (loc.type == InventoryLocation::NODEMETA) {
3891 NodeMetadata *meta = client->getEnv().getClientMap().getNodeMetadata(loc.p);
3892 if (!meta || meta->getString("formspec").empty()) {
3893 formspec->quitMenu();
3899 guiroot->bringToFront(formspec);
3905 const video::SColor &skycolor = sky->getSkyColor();
3907 TimeTaker tt_draw("Draw scene");
3908 driver->beginScene(true, true, skycolor);
3910 bool draw_wield_tool = (m_game_ui->m_flags.show_hud &&
3911 (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
3912 (camera->getCameraMode() == CAMERA_MODE_FIRST));
3913 bool draw_crosshair = (
3914 (player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) &&
3915 (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT));
3916 #ifdef HAVE_TOUCHSCREENGUI
3918 draw_crosshair = !g_settings->getBool("touchtarget");
3919 } catch (SettingNotFoundException) {
3922 RenderingEngine::draw_scene(skycolor, m_game_ui->m_flags.show_hud,
3923 m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair);
3928 if (m_game_ui->m_flags.show_profiler_graph)
3929 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3934 if (runData.damage_flash > 0.0f) {
3935 video::SColor color(runData.damage_flash, 180, 0, 0);
3936 driver->draw2DRectangle(color,
3937 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3940 runData.damage_flash -= 384.0f * dtime;
3946 if (player->hurt_tilt_timer > 0.0f) {
3947 player->hurt_tilt_timer -= dtime * 6.0f;
3949 if (player->hurt_tilt_timer < 0.0f)
3950 player->hurt_tilt_strength = 0.0f;
3954 Update minimap pos and rotation
3956 if (mapper && m_game_ui->m_flags.show_minimap && m_game_ui->m_flags.show_hud) {
3957 mapper->setPos(floatToInt(player->getPosition(), BS));
3958 mapper->setAngle(player->getYaw());
3966 stats->drawtime = tt_draw.stop(true);
3967 g_profiler->avg("Game::updateFrame(): draw scene [ms]", stats->drawtime);
3968 g_profiler->graphAdd("Update frame [ms]", tt_update.stop(true));
3971 /* Log times and stuff for visualization */
3972 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
3974 Profiler::GraphValues values;
3975 g_profiler->graphGet(values);
3981 /****************************************************************************
3983 ****************************************************************************/
3985 /* On some computers framerate doesn't seem to be automatically limited
3987 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
3989 // not using getRealTime is necessary for wine
3990 device->getTimer()->tick(); // Maker sure device time is up-to-date
3991 u32 time = device->getTimer()->getTime();
3992 u32 last_time = fps_timings->last_time;
3994 if (time > last_time) // Make sure time hasn't overflowed
3995 fps_timings->busy_time = time - last_time;
3997 fps_timings->busy_time = 0;
3999 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4000 ? g_settings->getFloat("pause_fps_max")
4001 : g_settings->getFloat("fps_max"));
4003 if (fps_timings->busy_time < frametime_min) {
4004 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4005 device->sleep(fps_timings->sleep_time);
4007 fps_timings->sleep_time = 0;
4010 /* Get the new value of the device timer. Note that device->sleep() may
4011 * not sleep for the entire requested time as sleep may be interrupted and
4012 * therefore it is arguably more accurate to get the new time from the
4013 * device rather than calculating it by adding sleep_time to time.
4016 device->getTimer()->tick(); // Update device timer
4017 time = device->getTimer()->getTime();
4019 if (time > last_time) // Make sure last_time hasn't overflowed
4020 *dtime = (time - last_time) / 1000.0;
4024 fps_timings->last_time = time;
4027 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
4029 const wchar_t *wmsg = wgettext(msg);
4030 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
4035 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4037 ((Game *)data)->readSettings();
4040 void Game::readSettings()
4042 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4043 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4044 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4045 m_cache_enable_particles = g_settings->getBool("enable_particles");
4046 m_cache_enable_fog = g_settings->getBool("enable_fog");
4047 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4048 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4049 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4051 m_cache_enable_noclip = g_settings->getBool("noclip");
4052 m_cache_enable_free_move = g_settings->getBool("free_move");
4054 m_cache_fog_start = g_settings->getFloat("fog_start");
4056 m_cache_cam_smoothing = 0;
4057 if (g_settings->getBool("cinematic"))
4058 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4060 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4062 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4063 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4064 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4066 m_does_lost_focus_pause_game = g_settings->getBool("pause_on_lost_focus");
4069 /****************************************************************************/
4070 /****************************************************************************
4072 ****************************************************************************/
4073 /****************************************************************************/
4075 void Game::extendedResourceCleanup()
4077 // Extended resource accounting
4078 infostream << "Irrlicht resources after cleanup:" << std::endl;
4079 infostream << "\tRemaining meshes : "
4080 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
4081 infostream << "\tRemaining textures : "
4082 << driver->getTextureCount() << std::endl;
4084 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4085 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4086 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4090 clearTextureNameCache();
4091 infostream << "\tRemaining materials: "
4092 << driver-> getMaterialRendererCount()
4093 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4096 void Game::showDeathFormspec()
4098 static std::string formspec_str =
4099 std::string("formspec_version[1]") +
4101 "bgcolor[#320000b4;true]"
4102 "label[4.85,1.35;" + gettext("You died") + "]"
4103 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
4107 /* Note: FormspecFormSource and LocalFormspecHandler *
4108 * are deleted by guiFormSpecMenu */
4109 FormspecFormSource *fs_src = new FormspecFormSource(formspec_str);
4110 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
4112 auto *&formspec = m_game_ui->getFormspecGUI();
4113 GUIFormSpecMenu::create(formspec, client, &input->joystick,
4114 fs_src, txt_dst, client->getFormspecPrepend());
4115 formspec->setFocus("btn_respawn");
4118 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4119 void Game::showPauseMenu()
4122 static const std::string control_text = strgettext("Default Controls:\n"
4123 "No menu visible:\n"
4124 "- single tap: button activate\n"
4125 "- double tap: place/use\n"
4126 "- slide finger: look around\n"
4127 "Menu/Inventory visible:\n"
4128 "- double tap (outside):\n"
4130 "- touch stack, touch slot:\n"
4132 "- touch&drag, tap 2nd finger\n"
4133 " --> place single item to slot\n"
4136 static const std::string control_text_template = strgettext("Controls:\n"
4137 "- %s: move forwards\n"
4138 "- %s: move backwards\n"
4140 "- %s: move right\n"
4141 "- %s: jump/climb\n"
4142 "- %s: sneak/go down\n"
4145 "- Mouse: turn/look\n"
4146 "- Mouse left: dig/punch\n"
4147 "- Mouse right: place/use\n"
4148 "- Mouse wheel: select item\n"
4152 char control_text_buf[600];
4154 porting::mt_snprintf(control_text_buf, sizeof(control_text_buf), control_text_template.c_str(),
4155 GET_KEY_NAME(keymap_forward),
4156 GET_KEY_NAME(keymap_backward),
4157 GET_KEY_NAME(keymap_left),
4158 GET_KEY_NAME(keymap_right),
4159 GET_KEY_NAME(keymap_jump),
4160 GET_KEY_NAME(keymap_sneak),
4161 GET_KEY_NAME(keymap_drop),
4162 GET_KEY_NAME(keymap_inventory),
4163 GET_KEY_NAME(keymap_chat)
4166 std::string control_text = std::string(control_text_buf);
4167 str_formspec_escape(control_text);
4170 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4171 std::ostringstream os;
4173 os << "formspec_version[1]" << SIZE_TAG
4174 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4175 << strgettext("Continue") << "]";
4177 if (!simple_singleplayer_mode) {
4178 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4179 << strgettext("Change Password") << "]";
4181 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4186 if (g_settings->getBool("enable_sound")) {
4187 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4188 << strgettext("Sound Volume") << "]";
4191 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4192 << strgettext("Change Keys") << "]";
4194 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4195 << strgettext("Exit to Menu") << "]";
4196 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4197 << strgettext("Exit to OS") << "]"
4198 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4199 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4201 << strgettext("Game info:") << "\n";
4202 const std::string &address = client->getAddressName();
4203 static const std::string mode = strgettext("- Mode: ");
4204 if (!simple_singleplayer_mode) {
4205 Address serverAddress = client->getServerAddress();
4206 if (!address.empty()) {
4207 os << mode << strgettext("Remote server") << "\n"
4208 << strgettext("- Address: ") << address;
4210 os << mode << strgettext("Hosting server");
4212 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4214 os << mode << strgettext("Singleplayer") << "\n";
4216 if (simple_singleplayer_mode || address.empty()) {
4217 static const std::string on = strgettext("On");
4218 static const std::string off = strgettext("Off");
4219 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4220 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4221 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4222 os << strgettext("- Damage: ") << damage << "\n"
4223 << strgettext("- Creative Mode: ") << creative << "\n";
4224 if (!simple_singleplayer_mode) {
4225 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4226 //~ PvP = Player versus Player
4227 os << strgettext("- PvP: ") << pvp << "\n"
4228 << strgettext("- Public: ") << announced << "\n";
4229 std::string server_name = g_settings->get("server_name");
4230 str_formspec_escape(server_name);
4231 if (announced == on && !server_name.empty())
4232 os << strgettext("- Server Name: ") << server_name;
4239 /* Note: FormspecFormSource and LocalFormspecHandler *
4240 * are deleted by guiFormSpecMenu */
4241 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4242 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4244 auto *&formspec = m_game_ui->getFormspecGUI();
4245 GUIFormSpecMenu::create(formspec, client, &input->joystick,
4246 fs_src, txt_dst, client->getFormspecPrepend());
4247 formspec->setFocus("btn_continue");
4248 formspec->doPause = true;
4251 /****************************************************************************/
4252 /****************************************************************************
4253 extern function for launching the game
4254 ****************************************************************************/
4255 /****************************************************************************/
4257 void the_game(bool *kill,
4259 InputHandler *input,
4260 const std::string &map_dir,
4261 const std::string &playername,
4262 const std::string &password,
4263 const std::string &address, // If empty local server is created
4266 std::string &error_message,
4267 ChatBackend &chat_backend,
4268 bool *reconnect_requested,
4269 const SubgameSpec &gamespec, // Used for local game
4270 bool simple_singleplayer_mode)
4274 /* Make a copy of the server address because if a local singleplayer server
4275 * is created then this is updated and we don't want to change the value
4276 * passed to us by the calling function
4278 std::string server_address = address;
4282 if (game.startup(kill, random_input, input, map_dir,
4283 playername, password, &server_address, port, error_message,
4284 reconnect_requested, &chat_backend, gamespec,
4285 simple_singleplayer_mode)) {
4290 } catch (SerializationError &e) {
4291 error_message = std::string("A serialization error occurred:\n")
4292 + e.what() + "\n\nThe server is probably "
4293 " running a different version of " PROJECT_NAME_C ".";
4294 errorstream << error_message << std::endl;
4295 } catch (ServerError &e) {
4296 error_message = e.what();
4297 errorstream << "ServerError: " << error_message << std::endl;
4298 } catch (ModError &e) {
4299 error_message = std::string("ModError: ") + e.what() +
4300 strgettext("\nCheck debug.txt for details.");
4301 errorstream << error_message << std::endl;