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") && g_sound_manager_singleton.get()) {
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);
1310 bool Game::createClient(const std::string &playername,
1311 const std::string &password, std::string *address, u16 port)
1313 showOverlayMessage(N_("Creating client..."), 0, 10);
1315 draw_control = new MapDrawControl;
1319 bool could_connect, connect_aborted;
1320 #ifdef HAVE_TOUCHSCREENGUI
1321 if (g_touchscreengui) {
1322 g_touchscreengui->init(texture_src);
1323 g_touchscreengui->hide();
1326 if (!connectToServer(playername, password, address, port,
1327 &could_connect, &connect_aborted))
1330 if (!could_connect) {
1331 if (error_message->empty() && !connect_aborted) {
1332 // Should not happen if error messages are set properly
1333 *error_message = "Connection failed for unknown reason";
1334 errorstream << *error_message << std::endl;
1339 if (!getServerContent(&connect_aborted)) {
1340 if (error_message->empty() && !connect_aborted) {
1341 // Should not happen if error messages are set properly
1342 *error_message = "Connection failed for unknown reason";
1343 errorstream << *error_message << std::endl;
1348 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1349 &m_flags.force_fog_off, &runData.fog_range, client);
1350 shader_src->addShaderConstantSetterFactory(scsf);
1352 // Update cached textures, meshes and materials
1353 client->afterContentReceived();
1357 camera = new Camera(*draw_control, client);
1358 if (!camera || !camera->successfullyCreated(*error_message))
1360 client->setCamera(camera);
1364 if (m_cache_enable_clouds) {
1365 clouds = new Clouds(smgr, -1, time(0));
1367 *error_message = "Memory allocation error (clouds)";
1368 errorstream << *error_message << std::endl;
1375 sky = new Sky(-1, texture_src);
1377 skybox = NULL; // This is used/set later on in the main run loop
1380 *error_message = "Memory allocation error sky";
1381 errorstream << *error_message << std::endl;
1385 /* Pre-calculated values
1387 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1389 v2u32 size = t->getOriginalSize();
1390 crack_animation_length = size.Y / size.X;
1392 crack_animation_length = 5;
1398 /* Set window caption
1400 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1402 str += utf8_to_wide(g_version_hash);
1404 str += driver->getName();
1406 device->setWindowCaption(str.c_str());
1408 LocalPlayer *player = client->getEnv().getLocalPlayer();
1409 player->hurt_tilt_timer = 0;
1410 player->hurt_tilt_strength = 0;
1412 hud = new Hud(guienv, client, player, &player->inventory);
1415 *error_message = "Memory error: could not create HUD";
1416 errorstream << *error_message << std::endl;
1420 mapper = client->getMinimap();
1422 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1423 if (client->modsLoaded())
1424 client->getScript()->on_minimap_ready(mapper);
1430 bool Game::initGui()
1434 // Remove stale "recent" chat messages from previous connections
1435 chat_backend->clearRecentChat();
1437 // Make sure the size of the recent messages buffer is right
1438 chat_backend->applySettings();
1440 // Chat backend and console
1441 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
1442 -1, chat_backend, client, &g_menumgr);
1443 if (!gui_chat_console) {
1444 *error_message = "Could not allocate memory for chat console";
1445 errorstream << *error_message << std::endl;
1449 #ifdef HAVE_TOUCHSCREENGUI
1451 if (g_touchscreengui)
1452 g_touchscreengui->show();
1459 bool Game::connectToServer(const std::string &playername,
1460 const std::string &password, std::string *address, u16 port,
1461 bool *connect_ok, bool *connection_aborted)
1463 *connect_ok = false; // Let's not be overly optimistic
1464 *connection_aborted = false;
1465 bool local_server_mode = false;
1467 showOverlayMessage(N_("Resolving address..."), 0, 15);
1469 Address connect_address(0, 0, 0, 0, port);
1472 connect_address.Resolve(address->c_str());
1474 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1475 //connect_address.Resolve("localhost");
1476 if (connect_address.isIPv6()) {
1477 IPv6AddressBytes addr_bytes;
1478 addr_bytes.bytes[15] = 1;
1479 connect_address.setAddress(&addr_bytes);
1481 connect_address.setAddress(127, 0, 0, 1);
1483 local_server_mode = true;
1485 } catch (ResolveError &e) {
1486 *error_message = std::string("Couldn't resolve address: ") + e.what();
1487 errorstream << *error_message << std::endl;
1491 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1492 *error_message = "Unable to connect to " +
1493 connect_address.serializeString() +
1494 " because IPv6 is disabled";
1495 errorstream << *error_message << std::endl;
1499 client = new Client(playername.c_str(), password, *address,
1500 *draw_control, texture_src, shader_src,
1501 itemdef_manager, nodedef_manager, sound, eventmgr,
1502 connect_address.isIPv6(), m_game_ui.get());
1507 client->m_simple_singleplayer_mode = simple_singleplayer_mode;
1509 infostream << "Connecting to server at ";
1510 connect_address.print(&infostream);
1511 infostream << std::endl;
1513 client->connect(connect_address,
1514 simple_singleplayer_mode || local_server_mode);
1517 Wait for server to accept connection
1523 FpsControl fps_control = { 0 };
1525 f32 wait_time = 0; // in seconds
1527 fps_control.last_time = RenderingEngine::get_timer_time();
1529 while (RenderingEngine::run()) {
1531 limitFps(&fps_control, &dtime);
1533 // Update client and server
1534 client->step(dtime);
1537 server->step(dtime);
1540 if (client->getState() == LC_Init) {
1546 if (*connection_aborted)
1549 if (client->accessDenied()) {
1550 *error_message = "Access denied. Reason: "
1551 + client->accessDeniedReason();
1552 *reconnect_requested = client->reconnectRequested();
1553 errorstream << *error_message << std::endl;
1557 if (input->cancelPressed()) {
1558 *connection_aborted = true;
1559 infostream << "Connect aborted [Escape]" << std::endl;
1563 if (client->m_is_registration_confirmation_state) {
1564 if (registration_confirmation_shown) {
1565 // Keep drawing the GUI
1566 RenderingEngine::draw_menu_scene(guienv, dtime, true);
1568 registration_confirmation_shown = true;
1569 (new GUIConfirmRegistration(guienv, guienv->getRootGUIElement(), -1,
1570 &g_menumgr, client, playername, password,
1571 connection_aborted, texture_src))->drop();
1575 // Only time out if we aren't waiting for the server we started
1576 if (!address->empty() && wait_time > 10) {
1577 *error_message = "Connection timed out.";
1578 errorstream << *error_message << std::endl;
1583 showOverlayMessage(N_("Connecting to server..."), dtime, 20);
1586 } catch (con::PeerNotFoundException &e) {
1587 // TODO: Should something be done here? At least an info/error
1595 bool Game::getServerContent(bool *aborted)
1599 FpsControl fps_control = { 0 };
1600 f32 dtime; // in seconds
1602 fps_control.last_time = RenderingEngine::get_timer_time();
1604 while (RenderingEngine::run()) {
1606 limitFps(&fps_control, &dtime);
1608 // Update client and server
1609 client->step(dtime);
1612 server->step(dtime);
1615 if (client->mediaReceived() && client->itemdefReceived() &&
1616 client->nodedefReceived()) {
1621 if (!checkConnection())
1624 if (client->getState() < LC_Init) {
1625 *error_message = "Client disconnected";
1626 errorstream << *error_message << std::endl;
1630 if (input->cancelPressed()) {
1632 infostream << "Connect aborted [Escape]" << std::endl;
1639 if (!client->itemdefReceived()) {
1640 const wchar_t *text = wgettext("Item definitions...");
1642 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1645 } else if (!client->nodedefReceived()) {
1646 const wchar_t *text = wgettext("Node definitions...");
1648 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1652 std::stringstream message;
1653 std::fixed(message);
1654 message.precision(0);
1655 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
1656 message.precision(2);
1658 if ((USE_CURL == 0) ||
1659 (!g_settings->getBool("enable_remote_media_server"))) {
1660 float cur = client->getCurRate();
1661 std::string cur_unit = gettext("KiB/s");
1665 cur_unit = gettext("MiB/s");
1668 message << " (" << cur << ' ' << cur_unit << ")";
1671 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
1672 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
1673 texture_src, dtime, progress);
1681 /****************************************************************************/
1682 /****************************************************************************
1684 ****************************************************************************/
1685 /****************************************************************************/
1687 inline void Game::updateInteractTimers(f32 dtime)
1689 if (runData.nodig_delay_timer >= 0)
1690 runData.nodig_delay_timer -= dtime;
1692 if (runData.object_hit_delay_timer >= 0)
1693 runData.object_hit_delay_timer -= dtime;
1695 runData.time_from_last_punch += dtime;
1699 /* returns false if game should exit, otherwise true
1701 inline bool Game::checkConnection()
1703 if (client->accessDenied()) {
1704 *error_message = "Access denied. Reason: "
1705 + client->accessDeniedReason();
1706 *reconnect_requested = client->reconnectRequested();
1707 errorstream << *error_message << std::endl;
1715 /* returns false if game should exit, otherwise true
1717 inline bool Game::handleCallbacks()
1719 if (g_gamecallback->disconnect_requested) {
1720 g_gamecallback->disconnect_requested = false;
1724 if (g_gamecallback->changepassword_requested) {
1725 (new GUIPasswordChange(guienv, guiroot, -1,
1726 &g_menumgr, client, texture_src))->drop();
1727 g_gamecallback->changepassword_requested = false;
1730 if (g_gamecallback->changevolume_requested) {
1731 (new GUIVolumeChange(guienv, guiroot, -1,
1732 &g_menumgr, texture_src))->drop();
1733 g_gamecallback->changevolume_requested = false;
1736 if (g_gamecallback->keyconfig_requested) {
1737 (new GUIKeyChangeMenu(guienv, guiroot, -1,
1738 &g_menumgr, texture_src))->drop();
1739 g_gamecallback->keyconfig_requested = false;
1742 if (g_gamecallback->keyconfig_changed) {
1743 input->keycache.populate(); // update the cache with new settings
1744 g_gamecallback->keyconfig_changed = false;
1751 void Game::processQueues()
1753 texture_src->processQueue();
1754 itemdef_manager->processQueue(client);
1755 shader_src->processQueue();
1759 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times,
1762 float profiler_print_interval =
1763 g_settings->getFloat("profiler_print_interval");
1764 bool print_to_log = true;
1766 if (profiler_print_interval == 0) {
1767 print_to_log = false;
1768 profiler_print_interval = 3;
1771 if (profiler_interval.step(dtime, profiler_print_interval)) {
1773 infostream << "Profiler:" << std::endl;
1774 g_profiler->print(infostream);
1777 m_game_ui->updateProfiler();
1778 g_profiler->clear();
1781 // Update update graphs
1782 g_profiler->graphAdd("Time non-rendering [ms]",
1783 draw_times.busy_time - stats.drawtime);
1785 g_profiler->graphAdd("Sleep [ms]", draw_times.sleep_time);
1786 g_profiler->graphAdd("FPS", 1.0f / dtime);
1789 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
1796 /* Time average and jitter calculation
1798 jp = &stats->dtime_jitter;
1799 jp->avg = jp->avg * 0.96 + dtime * 0.04;
1801 jitter = dtime - jp->avg;
1803 if (jitter > jp->max)
1806 jp->counter += dtime;
1808 if (jp->counter > 0.0) {
1810 jp->max_sample = jp->max;
1811 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
1815 /* Busytime average and jitter calculation
1817 jp = &stats->busy_time_jitter;
1818 jp->avg = jp->avg + draw_times.busy_time * 0.02;
1820 jitter = draw_times.busy_time - jp->avg;
1822 if (jitter > jp->max)
1824 if (jitter < jp->min)
1827 jp->counter += dtime;
1829 if (jp->counter > 0.0) {
1831 jp->max_sample = jp->max;
1832 jp->min_sample = jp->min;
1840 /****************************************************************************
1842 ****************************************************************************/
1844 void Game::processUserInput(f32 dtime)
1846 // Reset input if window not active or some menu is active
1847 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
1849 #ifdef HAVE_TOUCHSCREENGUI
1850 g_touchscreengui->hide();
1853 #ifdef HAVE_TOUCHSCREENGUI
1854 else if (g_touchscreengui) {
1855 /* on touchscreengui step may generate own input events which ain't
1856 * what we want in case we just did clear them */
1857 g_touchscreengui->step(dtime);
1861 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
1862 gui_chat_console->closeConsoleAtOnce();
1865 // Input handler step() (used by the random input generator)
1869 auto formspec = m_game_ui->getFormspecGUI();
1871 formspec->getAndroidUIInput();
1873 handleAndroidChatInput();
1876 // Increase timer for double tap of "keymap_jump"
1877 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
1878 runData.jump_timer += dtime;
1881 processItemSelection(&runData.new_playeritem);
1885 void Game::processKeyInput()
1887 if (wasKeyDown(KeyType::DROP)) {
1888 dropSelectedItem(isKeyDown(KeyType::SNEAK));
1889 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
1890 toggleAutoforward();
1891 } else if (wasKeyDown(KeyType::BACKWARD)) {
1892 if (g_settings->getBool("continuous_forward"))
1893 toggleAutoforward();
1894 } else if (wasKeyDown(KeyType::INVENTORY)) {
1896 } else if (input->cancelPressed()) {
1898 m_android_chat_open = false;
1900 if (!gui_chat_console->isOpenInhibited()) {
1903 } else if (wasKeyDown(KeyType::CHAT)) {
1904 openConsole(0.2, L"");
1905 } else if (wasKeyDown(KeyType::CMD)) {
1906 openConsole(0.2, L"/");
1907 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
1908 if (client->modsLoaded())
1909 openConsole(0.2, L".");
1911 m_game_ui->showStatusText(wgettext("Client side scripting is disabled"));
1912 } else if (wasKeyDown(KeyType::CONSOLE)) {
1913 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
1914 } else if (wasKeyDown(KeyType::FREEMOVE)) {
1916 } else if (wasKeyDown(KeyType::JUMP)) {
1917 toggleFreeMoveAlt();
1918 } else if (wasKeyDown(KeyType::PITCHMOVE)) {
1920 } else if (wasKeyDown(KeyType::FASTMOVE)) {
1922 } else if (wasKeyDown(KeyType::NOCLIP)) {
1925 } else if (wasKeyDown(KeyType::MUTE)) {
1926 if (g_settings->getBool("enable_sound")) {
1927 bool new_mute_sound = !g_settings->getBool("mute_sound");
1928 g_settings->setBool("mute_sound", new_mute_sound);
1930 m_game_ui->showTranslatedStatusText("Sound muted");
1932 m_game_ui->showTranslatedStatusText("Sound unmuted");
1934 m_game_ui->showTranslatedStatusText("Sound system is disabled");
1936 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
1937 if (g_settings->getBool("enable_sound")) {
1938 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
1940 g_settings->setFloat("sound_volume", new_volume);
1941 const wchar_t *str = wgettext("Volume changed to %d%%");
1942 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1944 m_game_ui->showStatusText(buf);
1946 m_game_ui->showTranslatedStatusText("Sound system is disabled");
1948 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
1949 if (g_settings->getBool("enable_sound")) {
1950 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
1952 g_settings->setFloat("sound_volume", new_volume);
1953 const wchar_t *str = wgettext("Volume changed to %d%%");
1954 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1956 m_game_ui->showStatusText(buf);
1958 m_game_ui->showTranslatedStatusText("Sound system is disabled");
1961 } else if (wasKeyDown(KeyType::MUTE) || wasKeyDown(KeyType::INC_VOLUME)
1962 || wasKeyDown(KeyType::DEC_VOLUME)) {
1963 m_game_ui->showTranslatedStatusText("Sound system is not supported on this build");
1965 } else if (wasKeyDown(KeyType::CINEMATIC)) {
1967 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
1968 client->makeScreenshot();
1969 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
1970 m_game_ui->toggleHud();
1971 } else if (wasKeyDown(KeyType::MINIMAP)) {
1972 toggleMinimap(isKeyDown(KeyType::SNEAK));
1973 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
1974 m_game_ui->toggleChat();
1975 } else if (wasKeyDown(KeyType::TOGGLE_FOG)) {
1977 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
1978 toggleUpdateCamera();
1979 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
1981 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
1982 m_game_ui->toggleProfiler();
1983 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
1984 increaseViewRange();
1985 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
1986 decreaseViewRange();
1987 } else if (wasKeyDown(KeyType::RANGESELECT)) {
1988 toggleFullViewRange();
1989 } else if (wasKeyDown(KeyType::ZOOM)) {
1991 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
1993 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
1995 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
1997 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2001 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2002 runData.reset_jump_timer = false;
2003 runData.jump_timer = 0.0f;
2006 if (quicktune->hasMessage()) {
2007 m_game_ui->showStatusText(utf8_to_wide(quicktune->getMessage()));
2011 void Game::processItemSelection(u16 *new_playeritem)
2013 LocalPlayer *player = client->getEnv().getLocalPlayer();
2015 /* Item selection using mouse wheel
2017 *new_playeritem = player->getWieldIndex();
2019 s32 wheel = input->getMouseWheel();
2020 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2021 player->hud_hotbar_itemcount - 1);
2025 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2026 wasKeyDown(KeyType::HOTBAR_NEXT)) {
2030 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2031 wasKeyDown(KeyType::HOTBAR_PREV)) {
2036 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2038 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2041 /* Item selection using hotbar slot keys
2043 for (u16 i = 0; i <= max_item; i++) {
2044 if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
2045 *new_playeritem = i;
2052 void Game::dropSelectedItem(bool single_item)
2054 IDropAction *a = new IDropAction();
2055 a->count = single_item ? 1 : 0;
2056 a->from_inv.setCurrentPlayer();
2057 a->from_list = "main";
2058 a->from_i = client->getEnv().getLocalPlayer()->getWieldIndex();
2059 client->inventoryAction(a);
2063 void Game::openInventory()
2066 * Don't permit to open inventory is CAO or player doesn't exists.
2067 * This prevent showing an empty inventory at player load
2070 LocalPlayer *player = client->getEnv().getLocalPlayer();
2071 if (!player || !player->getCAO())
2074 infostream << "Game: Launching inventory" << std::endl;
2076 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2078 InventoryLocation inventoryloc;
2079 inventoryloc.setCurrentPlayer();
2081 if (!client->modsLoaded()
2082 || !client->getScript()->on_inventory_open(fs_src->m_client->getInventory(inventoryloc))) {
2083 TextDest *txt_dst = new TextDestPlayerInventory(client);
2084 auto *&formspec = m_game_ui->updateFormspec("");
2085 GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
2086 txt_dst, client->getFormspecPrepend());
2088 formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2093 void Game::openConsole(float scale, const wchar_t *line)
2095 assert(scale > 0.0f && scale <= 1.0f);
2098 porting::showInputDialog(gettext("ok"), "", "", 2);
2099 m_android_chat_open = true;
2101 if (gui_chat_console->isOpenInhibited())
2103 gui_chat_console->openConsole(scale);
2105 gui_chat_console->setCloseOnEnter(true);
2106 gui_chat_console->replaceAndAddToHistory(line);
2112 void Game::handleAndroidChatInput()
2114 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2115 std::string text = porting::getInputDialogValue();
2116 client->typeChatMessage(utf8_to_wide(text));
2117 m_android_chat_open = false;
2123 void Game::toggleFreeMove()
2125 bool free_move = !g_settings->getBool("free_move");
2126 g_settings->set("free_move", bool_to_cstr(free_move));
2129 if (client->checkPrivilege("fly")) {
2130 m_game_ui->showTranslatedStatusText("Fly mode enabled");
2132 m_game_ui->showTranslatedStatusText("Fly mode enabled (note: no 'fly' privilege)");
2135 m_game_ui->showTranslatedStatusText("Fly mode disabled");
2139 void Game::toggleFreeMoveAlt()
2141 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2144 runData.reset_jump_timer = true;
2148 void Game::togglePitchMove()
2150 bool pitch_move = !g_settings->getBool("pitch_move");
2151 g_settings->set("pitch_move", bool_to_cstr(pitch_move));
2154 m_game_ui->showTranslatedStatusText("Pitch move mode enabled");
2156 m_game_ui->showTranslatedStatusText("Pitch move mode disabled");
2161 void Game::toggleFast()
2163 bool fast_move = !g_settings->getBool("fast_move");
2164 bool has_fast_privs = client->checkPrivilege("fast");
2165 g_settings->set("fast_move", bool_to_cstr(fast_move));
2168 if (has_fast_privs) {
2169 m_game_ui->showTranslatedStatusText("Fast mode enabled");
2171 m_game_ui->showTranslatedStatusText("Fast mode enabled (note: no 'fast' privilege)");
2174 m_game_ui->showTranslatedStatusText("Fast mode disabled");
2178 m_cache_hold_aux1 = fast_move && has_fast_privs;
2183 void Game::toggleNoClip()
2185 bool noclip = !g_settings->getBool("noclip");
2186 g_settings->set("noclip", bool_to_cstr(noclip));
2189 if (client->checkPrivilege("noclip")) {
2190 m_game_ui->showTranslatedStatusText("Noclip mode enabled");
2192 m_game_ui->showTranslatedStatusText("Noclip mode enabled (note: no 'noclip' privilege)");
2195 m_game_ui->showTranslatedStatusText("Noclip mode disabled");
2199 void Game::toggleCinematic()
2201 bool cinematic = !g_settings->getBool("cinematic");
2202 g_settings->set("cinematic", bool_to_cstr(cinematic));
2205 m_game_ui->showTranslatedStatusText("Cinematic mode enabled");
2207 m_game_ui->showTranslatedStatusText("Cinematic mode disabled");
2210 // Autoforward by toggling continuous forward.
2211 void Game::toggleAutoforward()
2213 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2214 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2216 if (autorun_enabled)
2217 m_game_ui->showTranslatedStatusText("Automatic forward enabled");
2219 m_game_ui->showTranslatedStatusText("Automatic forward disabled");
2222 void Game::toggleMinimap(bool shift_pressed)
2224 if (!mapper || !m_game_ui->m_flags.show_hud || !g_settings->getBool("enable_minimap"))
2227 if (shift_pressed) {
2228 mapper->toggleMinimapShape();
2232 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2234 MinimapMode mode = MINIMAP_MODE_OFF;
2235 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2236 mode = mapper->getMinimapMode();
2237 mode = (MinimapMode)((int)mode + 1);
2238 // If radar is disabled and in, or switching to, radar mode
2239 if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE) && mode > 3)
2240 mode = MINIMAP_MODE_OFF;
2243 m_game_ui->m_flags.show_minimap = true;
2245 case MINIMAP_MODE_SURFACEx1:
2246 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1");
2248 case MINIMAP_MODE_SURFACEx2:
2249 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2");
2251 case MINIMAP_MODE_SURFACEx4:
2252 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4");
2254 case MINIMAP_MODE_RADARx1:
2255 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1");
2257 case MINIMAP_MODE_RADARx2:
2258 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2");
2260 case MINIMAP_MODE_RADARx4:
2261 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4");
2264 mode = MINIMAP_MODE_OFF;
2265 m_game_ui->m_flags.show_minimap = false;
2266 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE)
2267 m_game_ui->showTranslatedStatusText("Minimap hidden");
2269 m_game_ui->showTranslatedStatusText("Minimap currently disabled by game or mod");
2272 mapper->setMinimapMode(mode);
2275 void Game::toggleFog()
2277 bool fog_enabled = g_settings->getBool("enable_fog");
2278 g_settings->setBool("enable_fog", !fog_enabled);
2280 m_game_ui->showTranslatedStatusText("Fog disabled");
2282 m_game_ui->showTranslatedStatusText("Fog enabled");
2286 void Game::toggleDebug()
2288 // Initial / 4x toggle: Chat only
2289 // 1x toggle: Debug text with chat
2290 // 2x toggle: Debug text with profiler graph
2291 // 3x toggle: Debug text and wireframe
2292 if (!m_game_ui->m_flags.show_debug) {
2293 m_game_ui->m_flags.show_debug = true;
2294 m_game_ui->m_flags.show_profiler_graph = false;
2295 draw_control->show_wireframe = false;
2296 m_game_ui->showTranslatedStatusText("Debug info shown");
2297 } else if (!m_game_ui->m_flags.show_profiler_graph && !draw_control->show_wireframe) {
2298 m_game_ui->m_flags.show_profiler_graph = true;
2299 m_game_ui->showTranslatedStatusText("Profiler graph shown");
2300 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2301 m_game_ui->m_flags.show_profiler_graph = false;
2302 draw_control->show_wireframe = true;
2303 m_game_ui->showTranslatedStatusText("Wireframe shown");
2305 m_game_ui->m_flags.show_debug = false;
2306 m_game_ui->m_flags.show_profiler_graph = false;
2307 draw_control->show_wireframe = false;
2308 if (client->checkPrivilege("debug")) {
2309 m_game_ui->showTranslatedStatusText("Debug info, profiler graph, and wireframe hidden");
2311 m_game_ui->showTranslatedStatusText("Debug info and profiler graph hidden");
2317 void Game::toggleUpdateCamera()
2319 m_flags.disable_camera_update = !m_flags.disable_camera_update;
2320 if (m_flags.disable_camera_update)
2321 m_game_ui->showTranslatedStatusText("Camera update disabled");
2323 m_game_ui->showTranslatedStatusText("Camera update enabled");
2327 void Game::increaseViewRange()
2329 s16 range = g_settings->getS16("viewing_range");
2330 s16 range_new = range + 10;
2334 if (range_new > 4000) {
2336 str = wgettext("Viewing range is at maximum: %d");
2337 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2339 m_game_ui->showStatusText(buf);
2342 str = wgettext("Viewing range changed to %d");
2343 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2345 m_game_ui->showStatusText(buf);
2347 g_settings->set("viewing_range", itos(range_new));
2351 void Game::decreaseViewRange()
2353 s16 range = g_settings->getS16("viewing_range");
2354 s16 range_new = range - 10;
2358 if (range_new < 20) {
2360 str = wgettext("Viewing range is at minimum: %d");
2361 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2363 m_game_ui->showStatusText(buf);
2365 str = wgettext("Viewing range changed to %d");
2366 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2368 m_game_ui->showStatusText(buf);
2370 g_settings->set("viewing_range", itos(range_new));
2374 void Game::toggleFullViewRange()
2376 draw_control->range_all = !draw_control->range_all;
2377 if (draw_control->range_all)
2378 m_game_ui->showTranslatedStatusText("Enabled unlimited viewing range");
2380 m_game_ui->showTranslatedStatusText("Disabled unlimited viewing range");
2384 void Game::checkZoomEnabled()
2386 LocalPlayer *player = client->getEnv().getLocalPlayer();
2387 if (player->getZoomFOV() < 0.001f || player->getFov().fov > 0.0f)
2388 m_game_ui->showTranslatedStatusText("Zoom currently disabled by game or mod");
2392 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2394 if ((device->isWindowActive() && device->isWindowFocused()
2395 && !isMenuActive()) || random_input) {
2398 if (!random_input) {
2399 // Mac OSX gets upset if this is set every frame
2400 if (device->getCursorControl()->isVisible())
2401 device->getCursorControl()->setVisible(false);
2405 if (m_first_loop_after_window_activation) {
2406 m_first_loop_after_window_activation = false;
2408 input->setMousePos(driver->getScreenSize().Width / 2,
2409 driver->getScreenSize().Height / 2);
2411 updateCameraOrientation(cam, dtime);
2417 // Mac OSX gets upset if this is set every frame
2418 if (!device->getCursorControl()->isVisible())
2419 device->getCursorControl()->setVisible(true);
2422 m_first_loop_after_window_activation = true;
2427 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2429 #ifdef HAVE_TOUCHSCREENGUI
2430 if (g_touchscreengui) {
2431 cam->camera_yaw += g_touchscreengui->getYawChange();
2432 cam->camera_pitch = g_touchscreengui->getPitch();
2435 v2s32 center(driver->getScreenSize().Width / 2, driver->getScreenSize().Height / 2);
2436 v2s32 dist = input->getMousePos() - center;
2438 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2442 cam->camera_yaw -= dist.X * m_cache_mouse_sensitivity;
2443 cam->camera_pitch += dist.Y * m_cache_mouse_sensitivity;
2445 if (dist.X != 0 || dist.Y != 0)
2446 input->setMousePos(center.X, center.Y);
2447 #ifdef HAVE_TOUCHSCREENGUI
2451 if (m_cache_enable_joysticks) {
2452 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
2453 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
2454 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
2457 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2461 void Game::updatePlayerControl(const CameraOrientation &cam)
2463 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2465 // DO NOT use the isKeyDown method for the forward, backward, left, right
2466 // buttons, as the code that uses the controls needs to be able to
2467 // distinguish between the two in order to know when to use joysticks.
2469 PlayerControl control(
2470 input->isKeyDown(KeyType::FORWARD),
2471 input->isKeyDown(KeyType::BACKWARD),
2472 input->isKeyDown(KeyType::LEFT),
2473 input->isKeyDown(KeyType::RIGHT),
2474 isKeyDown(KeyType::JUMP),
2475 isKeyDown(KeyType::SPECIAL1),
2476 isKeyDown(KeyType::SNEAK),
2477 isKeyDown(KeyType::ZOOM),
2478 input->getLeftState(),
2479 input->getRightState(),
2482 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
2483 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
2487 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
2488 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
2489 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
2490 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
2491 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
2492 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
2493 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
2494 ( (u32)(input->getLeftState() & 0x1) << 7) |
2495 ( (u32)(input->getRightState() & 0x1) << 8
2499 /* For Android, simulate holding down AUX1 (fast move) if the user has
2500 * the fast_move setting toggled on. If there is an aux1 key defined for
2501 * Android then its meaning is inverted (i.e. holding aux1 means walk and
2504 if (m_cache_hold_aux1) {
2505 control.aux1 = control.aux1 ^ true;
2506 keypress_bits ^= ((u32)(1U << 5));
2510 LocalPlayer *player = client->getEnv().getLocalPlayer();
2512 // autojump if set: simulate "jump" key
2513 if (player->getAutojump()) {
2514 control.jump = true;
2515 keypress_bits |= 1U << 4;
2518 // autoforward if set: simulate "up" key
2519 if (player->getPlayerSettings().continuous_forward &&
2520 client->activeObjectsReceived() && !player->isDead()) {
2522 keypress_bits |= 1U << 0;
2525 client->setPlayerControl(control);
2526 player->keyPressed = keypress_bits;
2532 inline void Game::step(f32 *dtime)
2534 bool can_be_and_is_paused =
2535 (simple_singleplayer_mode && g_menumgr.pausesGame());
2537 if (can_be_and_is_paused) { // This is for a singleplayer server
2538 *dtime = 0; // No time passes
2541 server->step(*dtime);
2543 client->step(*dtime);
2547 const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = {
2548 {&Game::handleClientEvent_None},
2549 {&Game::handleClientEvent_PlayerDamage},
2550 {&Game::handleClientEvent_PlayerForceMove},
2551 {&Game::handleClientEvent_Deathscreen},
2552 {&Game::handleClientEvent_ShowFormSpec},
2553 {&Game::handleClientEvent_ShowLocalFormSpec},
2554 {&Game::handleClientEvent_HandleParticleEvent},
2555 {&Game::handleClientEvent_HandleParticleEvent},
2556 {&Game::handleClientEvent_HandleParticleEvent},
2557 {&Game::handleClientEvent_HudAdd},
2558 {&Game::handleClientEvent_HudRemove},
2559 {&Game::handleClientEvent_HudChange},
2560 {&Game::handleClientEvent_SetSky},
2561 {&Game::handleClientEvent_SetSun},
2562 {&Game::handleClientEvent_SetMoon},
2563 {&Game::handleClientEvent_SetStars},
2564 {&Game::handleClientEvent_OverrideDayNigthRatio},
2565 {&Game::handleClientEvent_CloudParams},
2568 void Game::handleClientEvent_None(ClientEvent *event, CameraOrientation *cam)
2570 FATAL_ERROR("ClientEvent type None received");
2573 void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam)
2575 if (client->modsLoaded())
2576 client->getScript()->on_damage_taken(event->player_damage.amount);
2578 // Damage flash and hurt tilt are not used at death
2579 if (client->getHP() > 0) {
2580 runData.damage_flash += 95.0f + 3.2f * event->player_damage.amount;
2581 runData.damage_flash = MYMIN(runData.damage_flash, 127.0f);
2583 LocalPlayer *player = client->getEnv().getLocalPlayer();
2585 player->hurt_tilt_timer = 1.5f;
2586 player->hurt_tilt_strength =
2587 rangelim(event->player_damage.amount / 4.0f, 1.0f, 4.0f);
2590 // Play damage sound
2591 client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::PLAYER_DAMAGE));
2594 void Game::handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam)
2596 cam->camera_yaw = event->player_force_move.yaw;
2597 cam->camera_pitch = event->player_force_move.pitch;
2600 void Game::handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam)
2602 // If client scripting is enabled, deathscreen is handled by CSM code in
2603 // builtin/client/init.lua
2604 if (client->modsLoaded())
2605 client->getScript()->on_death();
2607 showDeathFormspec();
2609 /* Handle visualization */
2610 LocalPlayer *player = client->getEnv().getLocalPlayer();
2611 runData.damage_flash = 0;
2612 player->hurt_tilt_timer = 0;
2613 player->hurt_tilt_strength = 0;
2616 void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam)
2618 if (event->show_formspec.formspec->empty()) {
2619 auto formspec = m_game_ui->getFormspecGUI();
2620 if (formspec && (event->show_formspec.formname->empty()
2621 || *(event->show_formspec.formname) == m_game_ui->getFormspecName())) {
2622 formspec->quitMenu();
2625 FormspecFormSource *fs_src =
2626 new FormspecFormSource(*(event->show_formspec.formspec));
2627 TextDestPlayerInventory *txt_dst =
2628 new TextDestPlayerInventory(client, *(event->show_formspec.formname));
2630 auto *&formspec = m_game_ui->updateFormspec(*(event->show_formspec.formname));
2631 GUIFormSpecMenu::create(formspec, client, &input->joystick,
2632 fs_src, txt_dst, client->getFormspecPrepend());
2635 delete event->show_formspec.formspec;
2636 delete event->show_formspec.formname;
2639 void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam)
2641 FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec);
2642 LocalFormspecHandler *txt_dst =
2643 new LocalFormspecHandler(*event->show_formspec.formname, client);
2644 GUIFormSpecMenu::create(m_game_ui->getFormspecGUI(), client, &input->joystick,
2645 fs_src, txt_dst, client->getFormspecPrepend());
2647 delete event->show_formspec.formspec;
2648 delete event->show_formspec.formname;
2651 void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event,
2652 CameraOrientation *cam)
2654 LocalPlayer *player = client->getEnv().getLocalPlayer();
2655 client->getParticleManager()->handleParticleEvent(event, client, player);
2658 void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
2660 LocalPlayer *player = client->getEnv().getLocalPlayer();
2661 auto &hud_server_to_client = client->getHUDTranslationMap();
2663 u32 server_id = event->hudadd.server_id;
2664 // ignore if we already have a HUD with that ID
2665 auto i = hud_server_to_client.find(server_id);
2666 if (i != hud_server_to_client.end()) {
2667 delete event->hudadd.pos;
2668 delete event->hudadd.name;
2669 delete event->hudadd.scale;
2670 delete event->hudadd.text;
2671 delete event->hudadd.align;
2672 delete event->hudadd.offset;
2673 delete event->hudadd.world_pos;
2674 delete event->hudadd.size;
2675 delete event->hudadd.text2;
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 e->text2 = *event->hudadd.text2;
2694 hud_server_to_client[server_id] = player->addHud(e);
2696 delete event->hudadd.pos;
2697 delete event->hudadd.name;
2698 delete event->hudadd.scale;
2699 delete event->hudadd.text;
2700 delete event->hudadd.align;
2701 delete event->hudadd.offset;
2702 delete event->hudadd.world_pos;
2703 delete event->hudadd.size;
2704 delete event->hudadd.text2;
2707 void Game::handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam)
2709 LocalPlayer *player = client->getEnv().getLocalPlayer();
2710 HudElement *e = player->removeHud(event->hudrm.id);
2714 void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam)
2716 LocalPlayer *player = client->getEnv().getLocalPlayer();
2718 u32 id = event->hudchange.id;
2719 HudElement *e = player->getHud(id);
2722 delete event->hudchange.v3fdata;
2723 delete event->hudchange.v2fdata;
2724 delete event->hudchange.sdata;
2725 delete event->hudchange.v2s32data;
2729 switch (event->hudchange.stat) {
2731 e->pos = *event->hudchange.v2fdata;
2735 e->name = *event->hudchange.sdata;
2738 case HUD_STAT_SCALE:
2739 e->scale = *event->hudchange.v2fdata;
2743 e->text = *event->hudchange.sdata;
2746 case HUD_STAT_NUMBER:
2747 e->number = event->hudchange.data;
2751 e->item = event->hudchange.data;
2755 e->dir = event->hudchange.data;
2758 case HUD_STAT_ALIGN:
2759 e->align = *event->hudchange.v2fdata;
2762 case HUD_STAT_OFFSET:
2763 e->offset = *event->hudchange.v2fdata;
2766 case HUD_STAT_WORLD_POS:
2767 e->world_pos = *event->hudchange.v3fdata;
2771 e->size = *event->hudchange.v2s32data;
2774 case HUD_STAT_Z_INDEX:
2775 e->z_index = event->hudchange.data;
2778 case HUD_STAT_TEXT2:
2779 e->text2 = *event->hudchange.sdata;
2783 delete event->hudchange.v3fdata;
2784 delete event->hudchange.v2fdata;
2785 delete event->hudchange.sdata;
2786 delete event->hudchange.v2s32data;
2789 void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
2791 sky->setVisible(false);
2792 // Whether clouds are visible in front of a custom skybox.
2793 sky->setCloudsEnabled(event->set_sky->clouds);
2799 // Clear the old textures out in case we switch rendering type.
2800 sky->clearSkyboxTextures();
2801 // Handle according to type
2802 if (event->set_sky->type == "regular") {
2803 // Shows the mesh skybox
2804 sky->setVisible(true);
2805 // Update mesh based skybox colours if applicable.
2806 sky->setSkyColors(*event->set_sky);
2807 sky->setHorizonTint(
2808 event->set_sky->fog_sun_tint,
2809 event->set_sky->fog_moon_tint,
2810 event->set_sky->fog_tint_type
2812 } else if (event->set_sky->type == "skybox" &&
2813 event->set_sky->textures.size() == 6) {
2814 // Disable the dyanmic mesh skybox:
2815 sky->setVisible(false);
2817 sky->setFallbackBgColor(event->set_sky->bgcolor);
2818 // Set sunrise and sunset fog tinting:
2819 sky->setHorizonTint(
2820 event->set_sky->fog_sun_tint,
2821 event->set_sky->fog_moon_tint,
2822 event->set_sky->fog_tint_type
2824 // Add textures to skybox.
2825 for (int i = 0; i < 6; i++)
2826 sky->addTextureToSkybox(event->set_sky->textures[i], i, texture_src);
2828 // Handle everything else as plain color.
2829 if (event->set_sky->type != "plain")
2830 infostream << "Unknown sky type: "
2831 << (event->set_sky->type) << std::endl;
2832 sky->setVisible(false);
2833 sky->setFallbackBgColor(event->set_sky->bgcolor);
2834 // Disable directional sun/moon tinting on plain or invalid skyboxes.
2835 sky->setHorizonTint(
2836 event->set_sky->bgcolor,
2837 event->set_sky->bgcolor,
2841 delete event->set_sky;
2844 void Game::handleClientEvent_SetSun(ClientEvent *event, CameraOrientation *cam)
2846 sky->setSunVisible(event->sun_params->visible);
2847 sky->setSunTexture(event->sun_params->texture,
2848 event->sun_params->tonemap, texture_src);
2849 sky->setSunScale(event->sun_params->scale);
2850 sky->setSunriseVisible(event->sun_params->sunrise_visible);
2851 sky->setSunriseTexture(event->sun_params->sunrise, texture_src);
2852 delete event->sun_params;
2855 void Game::handleClientEvent_SetMoon(ClientEvent *event, CameraOrientation *cam)
2857 sky->setMoonVisible(event->moon_params->visible);
2858 sky->setMoonTexture(event->moon_params->texture,
2859 event->moon_params->tonemap, texture_src);
2860 sky->setMoonScale(event->moon_params->scale);
2861 delete event->moon_params;
2864 void Game::handleClientEvent_SetStars(ClientEvent *event, CameraOrientation *cam)
2866 sky->setStarsVisible(event->star_params->visible);
2867 sky->setStarCount(event->star_params->count, false);
2868 sky->setStarColor(event->star_params->starcolor);
2869 sky->setStarScale(event->star_params->scale);
2870 delete event->star_params;
2873 void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
2874 CameraOrientation *cam)
2876 client->getEnv().setDayNightRatioOverride(
2877 event->override_day_night_ratio.do_override,
2878 event->override_day_night_ratio.ratio_f * 1000.0f);
2881 void Game::handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam)
2886 clouds->setDensity(event->cloud_params.density);
2887 clouds->setColorBright(video::SColor(event->cloud_params.color_bright));
2888 clouds->setColorAmbient(video::SColor(event->cloud_params.color_ambient));
2889 clouds->setHeight(event->cloud_params.height);
2890 clouds->setThickness(event->cloud_params.thickness);
2891 clouds->setSpeed(v2f(event->cloud_params.speed_x, event->cloud_params.speed_y));
2894 void Game::processClientEvents(CameraOrientation *cam)
2896 while (client->hasClientEvents()) {
2897 std::unique_ptr<ClientEvent> event(client->getClientEvent());
2898 FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, "Invalid clientevent type");
2899 const ClientEventHandler& evHandler = clientEventHandler[event->type];
2900 (this->*evHandler.handler)(event.get(), cam);
2904 void Game::updateChat(f32 dtime, const v2u32 &screensize)
2906 // Add chat log output for errors to be shown in chat
2907 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
2909 // Get new messages from error log buffer
2910 while (!chat_log_error_buf.empty()) {
2911 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
2912 if (!g_settings->getBool("disable_escape_sequences")) {
2913 error_message.insert(0, L"\x1b(c@red)");
2914 error_message.append(L"\x1b(c@white)");
2916 chat_backend->addMessage(L"", error_message);
2919 // Get new messages from client
2920 std::wstring message;
2921 while (client->getChatMessage(message)) {
2922 chat_backend->addUnparsedMessage(message);
2925 // Remove old messages
2926 chat_backend->step(dtime);
2928 // Display all messages in a static text element
2929 m_game_ui->setChatText(chat_backend->getRecentChat(),
2930 chat_backend->getRecentBuffer().getLineCount());
2933 void Game::updateCamera(u32 busy_time, f32 dtime)
2935 LocalPlayer *player = client->getEnv().getLocalPlayer();
2938 For interaction purposes, get info about the held item
2940 - Is it a usable item?
2941 - Can it point to liquids?
2943 ItemStack playeritem;
2945 ItemStack selected, hand;
2946 playeritem = player->getWieldedItem(&selected, &hand);
2949 ToolCapabilities playeritem_toolcap =
2950 playeritem.getToolCapabilities(itemdef_manager);
2952 v3s16 old_camera_offset = camera->getOffset();
2954 if (wasKeyDown(KeyType::CAMERA_MODE)) {
2955 GenericCAO *playercao = player->getCAO();
2957 // If playercao not loaded, don't change camera
2961 camera->toggleCameraMode();
2963 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2964 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2967 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2968 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
2970 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2971 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio);
2972 camera->step(dtime);
2974 v3f camera_position = camera->getPosition();
2975 v3f camera_direction = camera->getDirection();
2976 f32 camera_fov = camera->getFovMax();
2977 v3s16 camera_offset = camera->getOffset();
2979 m_camera_offset_changed = (camera_offset != old_camera_offset);
2981 if (!m_flags.disable_camera_update) {
2982 client->getEnv().getClientMap().updateCamera(camera_position,
2983 camera_direction, camera_fov, camera_offset);
2985 if (m_camera_offset_changed) {
2986 client->updateCameraOffset(camera_offset);
2987 client->getEnv().updateCameraOffset(camera_offset);
2990 clouds->updateCameraOffset(camera_offset);
2996 void Game::updateSound(f32 dtime)
2998 // Update sound listener
2999 v3s16 camera_offset = camera->getOffset();
3000 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3001 v3f(0, 0, 0), // velocity
3002 camera->getDirection(),
3003 camera->getCameraNode()->getUpVector());
3005 bool mute_sound = g_settings->getBool("mute_sound");
3007 sound->setListenerGain(0.0f);
3009 // Check if volume is in the proper range, else fix it.
3010 float old_volume = g_settings->getFloat("sound_volume");
3011 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
3012 sound->setListenerGain(new_volume);
3014 if (old_volume != new_volume) {
3015 g_settings->setFloat("sound_volume", new_volume);
3019 LocalPlayer *player = client->getEnv().getLocalPlayer();
3021 // Tell the sound maker whether to make footstep sounds
3022 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3024 // Update sound maker
3025 if (player->makes_footstep_sound)
3026 soundmaker->step(dtime);
3028 ClientMap &map = client->getEnv().getClientMap();
3029 MapNode n = map.getNode(player->getFootstepNodePos());
3030 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3034 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3036 LocalPlayer *player = client->getEnv().getLocalPlayer();
3038 const v3f camera_direction = camera->getDirection();
3039 const v3s16 camera_offset = camera->getOffset();
3042 Calculate what block is the crosshair pointing to
3045 ItemStack selected_item, hand_item;
3046 const ItemStack &tool_item = player->getWieldedItem(&selected_item, &hand_item);
3048 const ItemDefinition &selected_def = selected_item.getDefinition(itemdef_manager);
3049 f32 d = getToolRange(selected_def, hand_item.getDefinition(itemdef_manager));
3051 core::line3d<f32> shootline;
3053 switch (camera->getCameraMode()) {
3054 case CAMERA_MODE_FIRST:
3055 // Shoot from camera position, with bobbing
3056 shootline.start = camera->getPosition();
3058 case CAMERA_MODE_THIRD:
3059 // Shoot from player head, no bobbing
3060 shootline.start = camera->getHeadPosition();
3062 case CAMERA_MODE_THIRD_FRONT:
3063 shootline.start = camera->getHeadPosition();
3064 // prevent player pointing anything in front-view
3068 shootline.end = shootline.start + camera_direction * BS * d;
3070 #ifdef HAVE_TOUCHSCREENGUI
3072 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3073 shootline = g_touchscreengui->getShootline();
3074 // Scale shootline to the acual distance the player can reach
3075 shootline.end = shootline.start
3076 + shootline.getVector().normalize() * BS * d;
3077 shootline.start += intToFloat(camera_offset, BS);
3078 shootline.end += intToFloat(camera_offset, BS);
3083 PointedThing pointed = updatePointedThing(shootline,
3084 selected_def.liquids_pointable,
3085 !runData.ldown_for_dig,
3088 if (pointed != runData.pointed_old) {
3089 infostream << "Pointing at " << pointed.dump() << std::endl;
3090 hud->updateSelectionMesh(camera_offset);
3093 if (runData.digging_blocked && !input->getLeftState()) {
3094 // allow digging again if button is not pressed
3095 runData.digging_blocked = false;
3100 - releasing left mouse button
3101 - pointing away from node
3103 if (runData.digging) {
3104 if (input->getLeftReleased()) {
3105 infostream << "Left button released"
3106 << " (stopped digging)" << std::endl;
3107 runData.digging = false;
3108 } else if (pointed != runData.pointed_old) {
3109 if (pointed.type == POINTEDTHING_NODE
3110 && runData.pointed_old.type == POINTEDTHING_NODE
3111 && pointed.node_undersurface
3112 == runData.pointed_old.node_undersurface) {
3113 // Still pointing to the same node, but a different face.
3116 infostream << "Pointing away from node"
3117 << " (stopped digging)" << std::endl;
3118 runData.digging = false;
3119 hud->updateSelectionMesh(camera_offset);
3123 if (!runData.digging) {
3124 client->interact(INTERACT_STOP_DIGGING, runData.pointed_old);
3125 client->setCrack(-1, v3s16(0, 0, 0));
3126 runData.dig_time = 0.0;
3128 } else if (runData.dig_instantly && input->getLeftReleased()) {
3129 // Remove e.g. torches faster when clicking instead of holding LMB
3130 runData.nodig_delay_timer = 0;
3131 runData.dig_instantly = false;
3134 if (!runData.digging && runData.ldown_for_dig && !input->getLeftState()) {
3135 runData.ldown_for_dig = false;
3138 runData.left_punch = false;
3140 soundmaker->m_player_leftpunch_sound.name = "";
3142 // Prepare for repeating, unless we're not supposed to
3143 if (input->getRightState() && !g_settings->getBool("safe_dig_and_place"))
3144 runData.repeat_rightclick_timer += dtime;
3146 runData.repeat_rightclick_timer = 0;
3148 if (selected_def.usable && input->getLeftState()) {
3149 if (input->getLeftClicked() && (!client->modsLoaded()
3150 || !client->getScript()->on_item_use(selected_item, pointed)))
3151 client->interact(INTERACT_USE, pointed);
3152 } else if (pointed.type == POINTEDTHING_NODE) {
3153 handlePointingAtNode(pointed, selected_item, hand_item, dtime);
3154 } else if (pointed.type == POINTEDTHING_OBJECT) {
3155 v3f player_position = player->getPosition();
3156 handlePointingAtObject(pointed, tool_item, player_position, show_debug);
3157 } else if (input->getLeftState()) {
3158 // When button is held down in air, show continuous animation
3159 runData.left_punch = true;
3160 // Run callback even though item is not usable
3161 if (input->getLeftClicked() && client->modsLoaded())
3162 client->getScript()->on_item_use(selected_item, pointed);
3163 } else if (input->getRightClicked()) {
3164 handlePointingAtNothing(selected_item);
3167 runData.pointed_old = pointed;
3169 if (runData.left_punch || input->getLeftClicked())
3170 camera->setDigging(0); // left click animation
3172 input->resetLeftClicked();
3173 input->resetRightClicked();
3175 input->resetLeftReleased();
3176 input->resetRightReleased();
3180 PointedThing Game::updatePointedThing(
3181 const core::line3d<f32> &shootline,
3182 bool liquids_pointable,
3183 bool look_for_object,
3184 const v3s16 &camera_offset)
3186 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3187 selectionboxes->clear();
3188 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3189 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3190 "show_entity_selectionbox");
3192 ClientEnvironment &env = client->getEnv();
3193 ClientMap &map = env.getClientMap();
3194 const NodeDefManager *nodedef = map.getNodeDefManager();
3196 runData.selected_object = NULL;
3198 RaycastState s(shootline, look_for_object, liquids_pointable);
3199 PointedThing result;
3200 env.continueRaycast(&s, &result);
3201 if (result.type == POINTEDTHING_OBJECT) {
3202 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3203 aabb3f selection_box;
3204 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3205 runData.selected_object->getSelectionBox(&selection_box)) {
3206 v3f pos = runData.selected_object->getPosition();
3207 selectionboxes->push_back(aabb3f(selection_box));
3208 hud->setSelectionPos(pos, camera_offset);
3210 } else if (result.type == POINTEDTHING_NODE) {
3211 // Update selection boxes
3212 MapNode n = map.getNode(result.node_undersurface);
3213 std::vector<aabb3f> boxes;
3214 n.getSelectionBoxes(nodedef, &boxes,
3215 n.getNeighbors(result.node_undersurface, &map));
3218 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3219 i != boxes.end(); ++i) {
3221 box.MinEdge -= v3f(d, d, d);
3222 box.MaxEdge += v3f(d, d, d);
3223 selectionboxes->push_back(box);
3225 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3227 hud->setSelectedFaceNormal(v3f(
3228 result.intersection_normal.X,
3229 result.intersection_normal.Y,
3230 result.intersection_normal.Z));
3233 // Update selection mesh light level and vertex colors
3234 if (!selectionboxes->empty()) {
3235 v3f pf = hud->getSelectionPos();
3236 v3s16 p = floatToInt(pf, BS);
3238 // Get selection mesh light level
3239 MapNode n = map.getNode(p);
3240 u16 node_light = getInteriorLight(n, -1, nodedef);
3241 u16 light_level = node_light;
3243 for (const v3s16 &dir : g_6dirs) {
3244 n = map.getNode(p + dir);
3245 node_light = getInteriorLight(n, -1, nodedef);
3246 if (node_light > light_level)
3247 light_level = node_light;
3250 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3252 final_color_blend(&c, light_level, daynight_ratio);
3254 // Modify final color a bit with time
3255 u32 timer = porting::getTimeMs() % 5000;
3256 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3257 float sin_r = 0.08f * std::sin(timerf);
3258 float sin_g = 0.08f * std::sin(timerf + irr::core::PI * 0.5f);
3259 float sin_b = 0.08f * std::sin(timerf + irr::core::PI);
3260 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3261 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3262 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3264 // Set mesh final color
3265 hud->setSelectionMeshColor(c);
3271 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3273 infostream << "Right Clicked in Air" << std::endl;
3274 PointedThing fauxPointed;
3275 fauxPointed.type = POINTEDTHING_NOTHING;
3276 client->interact(INTERACT_ACTIVATE, fauxPointed);
3280 void Game::handlePointingAtNode(const PointedThing &pointed,
3281 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
3283 v3s16 nodepos = pointed.node_undersurface;
3284 v3s16 neighbourpos = pointed.node_abovesurface;
3287 Check information text of node
3290 ClientMap &map = client->getEnv().getClientMap();
3292 if (runData.nodig_delay_timer <= 0.0 && input->getLeftState()
3293 && !runData.digging_blocked
3294 && client->checkPrivilege("interact")) {
3295 handleDigging(pointed, nodepos, selected_item, hand_item, dtime);
3298 // This should be done after digging handling
3299 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3302 m_game_ui->setInfoText(unescape_translate(utf8_to_wide(
3303 meta->getString("infotext"))));
3305 MapNode n = map.getNode(nodepos);
3307 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3308 m_game_ui->setInfoText(L"Unknown node: " +
3309 utf8_to_wide(nodedef_manager->get(n).name));
3313 if ((input->getRightClicked() ||
3314 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3315 client->checkPrivilege("interact")) {
3316 runData.repeat_rightclick_timer = 0;
3317 infostream << "Ground right-clicked" << std::endl;
3319 camera->setDigging(1); // right click animation (always shown for feedback)
3321 soundmaker->m_player_rightpunch_sound = SimpleSoundSpec();
3323 // If the wielded item has node placement prediction,
3325 // And also set the sound and send the interact
3326 // But first check for meta formspec and rightclickable
3327 auto &def = selected_item.getDefinition(itemdef_manager);
3328 bool placed = nodePlacement(def, selected_item, nodepos, neighbourpos,
3331 if (placed && client->modsLoaded())
3332 client->getScript()->on_placenode(pointed, def);
3336 bool Game::nodePlacement(const ItemDefinition &selected_def,
3337 const ItemStack &selected_item, const v3s16 &nodepos, const v3s16 &neighbourpos,
3338 const PointedThing &pointed, const NodeMetadata *meta)
3340 std::string prediction = selected_def.node_placement_prediction;
3341 const NodeDefManager *nodedef = client->ndef();
3342 ClientMap &map = client->getEnv().getClientMap();
3344 bool is_valid_position;
3346 node = map.getNode(nodepos, &is_valid_position);
3347 if (!is_valid_position) {
3348 soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
3353 if (meta && !meta->getString("formspec").empty() && !random_input
3354 && !isKeyDown(KeyType::SNEAK)) {
3355 // on_rightclick callbacks are called anyway
3356 if (nodedef_manager->get(map.getNode(nodepos)).rightclickable)
3357 client->interact(INTERACT_PLACE, pointed);
3359 infostream << "Launching custom inventory view" << std::endl;
3361 InventoryLocation inventoryloc;
3362 inventoryloc.setNodeMeta(nodepos);
3364 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3365 &client->getEnv().getClientMap(), nodepos);
3366 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3368 auto *&formspec = m_game_ui->updateFormspec("");
3369 GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
3370 txt_dst, client->getFormspecPrepend());
3372 formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3376 // on_rightclick callback
3377 if (prediction.empty() || (nodedef->get(node).rightclickable &&
3378 !isKeyDown(KeyType::SNEAK))) {
3380 client->interact(INTERACT_PLACE, pointed);
3384 verbosestream << "Node placement prediction for "
3385 << selected_def.name << " is "
3386 << prediction << std::endl;
3387 v3s16 p = neighbourpos;
3389 // Place inside node itself if buildable_to
3390 MapNode n_under = map.getNode(nodepos, &is_valid_position);
3391 if (is_valid_position) {
3392 if (nodedef->get(n_under).buildable_to) {
3395 node = map.getNode(p, &is_valid_position);
3396 if (is_valid_position && !nodedef->get(node).buildable_to) {
3398 client->interact(INTERACT_PLACE, pointed);
3404 // Find id of predicted node
3406 bool found = nodedef->getId(prediction, id);
3409 errorstream << "Node placement prediction failed for "
3410 << selected_def.name << " (places "
3412 << ") - Name not known" << std::endl;
3413 // Handle this as if prediction was empty
3415 client->interact(INTERACT_PLACE, pointed);
3419 const ContentFeatures &predicted_f = nodedef->get(id);
3421 // Predict param2 for facedir and wallmounted nodes
3424 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3425 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
3426 v3s16 dir = nodepos - neighbourpos;
3428 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
3429 param2 = dir.Y < 0 ? 1 : 0;
3430 } else if (abs(dir.X) > abs(dir.Z)) {
3431 param2 = dir.X < 0 ? 3 : 2;
3433 param2 = dir.Z < 0 ? 5 : 4;
3437 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
3438 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
3439 v3s16 dir = nodepos - floatToInt(client->getEnv().getLocalPlayer()->getPosition(), BS);
3441 if (abs(dir.X) > abs(dir.Z)) {
3442 param2 = dir.X < 0 ? 3 : 1;
3444 param2 = dir.Z < 0 ? 2 : 0;
3448 assert(param2 <= 5);
3450 //Check attachment if node is in group attached_node
3451 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
3452 static v3s16 wallmounted_dirs[8] = {
3462 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3463 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
3464 pp = p + wallmounted_dirs[param2];
3466 pp = p + v3s16(0, -1, 0);
3468 if (!nodedef->get(map.getNode(pp)).walkable) {
3470 client->interact(INTERACT_PLACE, pointed);
3476 if ((predicted_f.param_type_2 == CPT2_COLOR
3477 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
3478 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
3479 const std::string &indexstr = selected_item.metadata.getString(
3480 "palette_index", 0);
3481 if (!indexstr.empty()) {
3482 s32 index = mystoi(indexstr);
3483 if (predicted_f.param_type_2 == CPT2_COLOR) {
3485 } else if (predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
3486 // param2 = pure palette index + other
3487 param2 = (index & 0xf8) | (param2 & 0x07);
3488 } else if (predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
3489 // param2 = pure palette index + other
3490 param2 = (index & 0xe0) | (param2 & 0x1f);
3495 // Add node to client map
3496 MapNode n(id, 0, param2);
3499 LocalPlayer *player = client->getEnv().getLocalPlayer();
3501 // Dont place node when player would be inside new node
3502 // NOTE: This is to be eventually implemented by a mod as client-side Lua
3503 if (!nodedef->get(n).walkable ||
3504 g_settings->getBool("enable_build_where_you_stand") ||
3505 (client->checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
3506 (nodedef->get(n).walkable &&
3507 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
3508 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
3509 // This triggers the required mesh update too
3510 client->addNode(p, n);
3512 client->interact(INTERACT_PLACE, pointed);
3513 // A node is predicted, also play a sound
3514 soundmaker->m_player_rightpunch_sound = selected_def.sound_place;
3517 soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
3520 } catch (InvalidPositionException &e) {
3521 errorstream << "Node placement prediction failed for "
3522 << selected_def.name << " (places "
3524 << ") - Position not loaded" << std::endl;
3525 soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
3530 void Game::handlePointingAtObject(const PointedThing &pointed,
3531 const ItemStack &tool_item, const v3f &player_position, bool show_debug)
3533 std::wstring infotext = unescape_translate(
3534 utf8_to_wide(runData.selected_object->infoText()));
3537 if (!infotext.empty()) {
3540 infotext += utf8_to_wide(runData.selected_object->debugInfoText());
3543 m_game_ui->setInfoText(infotext);
3545 if (input->getLeftState()) {
3546 bool do_punch = false;
3547 bool do_punch_damage = false;
3549 if (runData.object_hit_delay_timer <= 0.0) {
3551 do_punch_damage = true;
3552 runData.object_hit_delay_timer = object_hit_delay;
3555 if (input->getLeftClicked())
3559 infostream << "Left-clicked object" << std::endl;
3560 runData.left_punch = true;
3563 if (do_punch_damage) {
3564 // Report direct punch
3565 v3f objpos = runData.selected_object->getPosition();
3566 v3f dir = (objpos - player_position).normalize();
3568 bool disable_send = runData.selected_object->directReportPunch(
3569 dir, &tool_item, runData.time_from_last_punch);
3570 runData.time_from_last_punch = 0;
3573 client->interact(INTERACT_START_DIGGING, pointed);
3575 } else if (input->getRightClicked()) {
3576 infostream << "Right-clicked object" << std::endl;
3577 client->interact(INTERACT_PLACE, pointed); // place
3582 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3583 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
3585 // See also: serverpackethandle.cpp, action == 2
3586 LocalPlayer *player = client->getEnv().getLocalPlayer();
3587 ClientMap &map = client->getEnv().getClientMap();
3588 MapNode n = client->getEnv().getClientMap().getNode(nodepos);
3590 // NOTE: Similar piece of code exists on the server side for
3592 // Get digging parameters
3593 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3594 &selected_item.getToolCapabilities(itemdef_manager));
3596 // If can't dig, try hand
3597 if (!params.diggable) {
3598 params = getDigParams(nodedef_manager->get(n).groups,
3599 &hand_item.getToolCapabilities(itemdef_manager));
3602 if (!params.diggable) {
3603 // I guess nobody will wait for this long
3604 runData.dig_time_complete = 10000000.0;
3606 runData.dig_time_complete = params.time;
3608 if (m_cache_enable_particles) {
3609 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3610 client->getParticleManager()->addNodeParticle(client,
3611 player, nodepos, n, features);
3615 if (!runData.digging) {
3616 infostream << "Started digging" << std::endl;
3617 runData.dig_instantly = runData.dig_time_complete == 0;
3618 if (client->modsLoaded() && client->getScript()->on_punchnode(nodepos, n))
3620 client->interact(INTERACT_START_DIGGING, pointed);
3621 runData.digging = true;
3622 runData.ldown_for_dig = true;
3625 if (!runData.dig_instantly) {
3626 runData.dig_index = (float)crack_animation_length
3628 / runData.dig_time_complete;
3630 // This is for e.g. torches
3631 runData.dig_index = crack_animation_length;
3634 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3636 if (sound_dig.exists() && params.diggable) {
3637 if (sound_dig.name == "__group") {
3638 if (!params.main_group.empty()) {
3639 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3640 soundmaker->m_player_leftpunch_sound.name =
3641 std::string("default_dig_") +
3645 soundmaker->m_player_leftpunch_sound = sound_dig;
3649 // Don't show cracks if not diggable
3650 if (runData.dig_time_complete >= 100000.0) {
3651 } else if (runData.dig_index < crack_animation_length) {
3652 //TimeTaker timer("client.setTempMod");
3653 //infostream<<"dig_index="<<dig_index<<std::endl;
3654 client->setCrack(runData.dig_index, nodepos);
3656 infostream << "Digging completed" << std::endl;
3657 client->setCrack(-1, v3s16(0, 0, 0));
3659 runData.dig_time = 0;
3660 runData.digging = false;
3661 // we successfully dug, now block it from repeating if we want to be safe
3662 if (g_settings->getBool("safe_dig_and_place"))
3663 runData.digging_blocked = true;
3665 runData.nodig_delay_timer =
3666 runData.dig_time_complete / (float)crack_animation_length;
3668 // We don't want a corresponding delay to very time consuming nodes
3669 // and nodes without digging time (e.g. torches) get a fixed delay.
3670 if (runData.nodig_delay_timer > 0.3)
3671 runData.nodig_delay_timer = 0.3;
3672 else if (runData.dig_instantly)
3673 runData.nodig_delay_timer = 0.15;
3675 bool is_valid_position;
3676 MapNode wasnode = map.getNode(nodepos, &is_valid_position);
3677 if (is_valid_position) {
3678 if (client->modsLoaded() &&
3679 client->getScript()->on_dignode(nodepos, wasnode)) {
3683 const ContentFeatures &f = client->ndef()->get(wasnode);
3684 if (f.node_dig_prediction == "air") {
3685 client->removeNode(nodepos);
3686 } else if (!f.node_dig_prediction.empty()) {
3688 bool found = client->ndef()->getId(f.node_dig_prediction, id);
3690 client->addNode(nodepos, id, true);
3692 // implicit else: no prediction
3695 client->interact(INTERACT_DIGGING_COMPLETED, pointed);
3697 if (m_cache_enable_particles) {
3698 const ContentFeatures &features =
3699 client->getNodeDefManager()->get(wasnode);
3700 client->getParticleManager()->addDiggingParticles(client,
3701 player, nodepos, wasnode, features);
3705 // Send event to trigger sound
3706 client->getEventManager()->put(new NodeDugEvent(nodepos, wasnode));
3709 if (runData.dig_time_complete < 100000.0) {
3710 runData.dig_time += dtime;
3712 runData.dig_time = 0;
3713 client->setCrack(-1, nodepos);
3716 camera->setDigging(0); // left click animation
3720 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
3721 const CameraOrientation &cam)
3723 TimeTaker tt_update("Game::updateFrame()");
3724 LocalPlayer *player = client->getEnv().getLocalPlayer();
3730 if (draw_control->range_all) {
3731 runData.fog_range = 100000 * BS;
3733 runData.fog_range = draw_control->wanted_range * BS;
3737 Calculate general brightness
3739 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3740 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3741 float direct_brightness;
3744 if (m_cache_enable_noclip && m_cache_enable_free_move) {
3745 direct_brightness = time_brightness;
3746 sunlight_seen = true;
3748 float old_brightness = sky->getBrightness();
3749 direct_brightness = client->getEnv().getClientMap()
3750 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
3751 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3755 float time_of_day_smooth = runData.time_of_day_smooth;
3756 float time_of_day = client->getEnv().getTimeOfDayF();
3758 static const float maxsm = 0.05f;
3759 static const float todsm = 0.05f;
3761 if (std::fabs(time_of_day - time_of_day_smooth) > maxsm &&
3762 std::fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3763 std::fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3764 time_of_day_smooth = time_of_day;
3766 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3767 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3768 + (time_of_day + 1.0) * todsm;
3770 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3771 + time_of_day * todsm;
3773 runData.time_of_day_smooth = time_of_day_smooth;
3775 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3776 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3777 player->getPitch());
3783 if (sky->getCloudsVisible()) {
3784 clouds->setVisible(true);
3785 clouds->step(dtime);
3786 // camera->getPosition is not enough for 3rd person views
3787 v3f camera_node_position = camera->getCameraNode()->getPosition();
3788 v3s16 camera_offset = camera->getOffset();
3789 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
3790 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
3791 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
3792 clouds->update(camera_node_position,
3793 sky->getCloudColor());
3794 if (clouds->isCameraInsideCloud() && m_cache_enable_fog) {
3795 // if inside clouds, and fog enabled, use that as sky
3797 video::SColor clouds_dark = clouds->getColor()
3798 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
3799 sky->overrideColors(clouds_dark, clouds->getColor());
3800 sky->setInClouds(true);
3801 runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
3802 // do not draw clouds after all
3803 clouds->setVisible(false);
3806 clouds->setVisible(false);
3813 client->getParticleManager()->step(dtime);
3819 if (m_cache_enable_fog) {
3822 video::EFT_FOG_LINEAR,
3823 runData.fog_range * m_cache_fog_start,
3824 runData.fog_range * 1.0,
3832 video::EFT_FOG_LINEAR,
3842 Get chat messages from client
3845 v2u32 screensize = driver->getScreenSize();
3847 updateChat(dtime, screensize);
3853 if (player->getWieldIndex() != runData.new_playeritem)
3854 client->setPlayerItem(runData.new_playeritem);
3856 if (client->updateWieldedItem()) {
3857 // Update wielded tool
3858 ItemStack selected_item, hand_item;
3859 ItemStack &tool_item = player->getWieldedItem(&selected_item, &hand_item);
3860 camera->wield(tool_item);
3864 Update block draw list every 200ms or when camera direction has
3867 runData.update_draw_list_timer += dtime;
3869 v3f camera_direction = camera->getDirection();
3870 if (runData.update_draw_list_timer >= 0.2
3871 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3872 || m_camera_offset_changed) {
3873 runData.update_draw_list_timer = 0;
3874 client->getEnv().getClientMap().updateDrawList();
3875 runData.update_draw_list_last_cam_dir = camera_direction;
3878 m_game_ui->update(*stats, client, draw_control, cam, runData.pointed_old, gui_chat_console, dtime);
3881 make sure menu is on top
3882 1. Delete formspec menu reference if menu was removed
3883 2. Else, make sure formspec menu is on top
3885 auto formspec = m_game_ui->getFormspecGUI();
3886 do { // breakable. only runs for one iteration
3890 if (formspec->getReferenceCount() == 1) {
3891 m_game_ui->deleteFormspec();
3895 auto &loc = formspec->getFormspecLocation();
3896 if (loc.type == InventoryLocation::NODEMETA) {
3897 NodeMetadata *meta = client->getEnv().getClientMap().getNodeMetadata(loc.p);
3898 if (!meta || meta->getString("formspec").empty()) {
3899 formspec->quitMenu();
3905 guiroot->bringToFront(formspec);
3911 const video::SColor &skycolor = sky->getSkyColor();
3913 TimeTaker tt_draw("Draw scene");
3914 driver->beginScene(true, true, skycolor);
3916 bool draw_wield_tool = (m_game_ui->m_flags.show_hud &&
3917 (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
3918 (camera->getCameraMode() == CAMERA_MODE_FIRST));
3919 bool draw_crosshair = (
3920 (player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) &&
3921 (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT));
3922 #ifdef HAVE_TOUCHSCREENGUI
3924 draw_crosshair = !g_settings->getBool("touchtarget");
3925 } catch (SettingNotFoundException) {
3928 RenderingEngine::draw_scene(skycolor, m_game_ui->m_flags.show_hud,
3929 m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair);
3934 if (m_game_ui->m_flags.show_profiler_graph)
3935 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3940 if (runData.damage_flash > 0.0f) {
3941 video::SColor color(runData.damage_flash, 180, 0, 0);
3942 driver->draw2DRectangle(color,
3943 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3946 runData.damage_flash -= 384.0f * dtime;
3952 if (player->hurt_tilt_timer > 0.0f) {
3953 player->hurt_tilt_timer -= dtime * 6.0f;
3955 if (player->hurt_tilt_timer < 0.0f)
3956 player->hurt_tilt_strength = 0.0f;
3960 Update minimap pos and rotation
3962 if (mapper && m_game_ui->m_flags.show_minimap && m_game_ui->m_flags.show_hud) {
3963 mapper->setPos(floatToInt(player->getPosition(), BS));
3964 mapper->setAngle(player->getYaw());
3972 stats->drawtime = tt_draw.stop(true);
3973 g_profiler->avg("Game::updateFrame(): draw scene [ms]", stats->drawtime);
3974 g_profiler->graphAdd("Update frame [ms]", tt_update.stop(true));
3977 /* Log times and stuff for visualization */
3978 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
3980 Profiler::GraphValues values;
3981 g_profiler->graphGet(values);
3987 /****************************************************************************
3989 ****************************************************************************/
3991 /* On some computers framerate doesn't seem to be automatically limited
3993 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
3995 // not using getRealTime is necessary for wine
3996 device->getTimer()->tick(); // Maker sure device time is up-to-date
3997 u32 time = device->getTimer()->getTime();
3998 u32 last_time = fps_timings->last_time;
4000 if (time > last_time) // Make sure time hasn't overflowed
4001 fps_timings->busy_time = time - last_time;
4003 fps_timings->busy_time = 0;
4005 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4006 ? g_settings->getFloat("pause_fps_max")
4007 : g_settings->getFloat("fps_max"));
4009 if (fps_timings->busy_time < frametime_min) {
4010 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4011 device->sleep(fps_timings->sleep_time);
4013 fps_timings->sleep_time = 0;
4016 /* Get the new value of the device timer. Note that device->sleep() may
4017 * not sleep for the entire requested time as sleep may be interrupted and
4018 * therefore it is arguably more accurate to get the new time from the
4019 * device rather than calculating it by adding sleep_time to time.
4022 device->getTimer()->tick(); // Update device timer
4023 time = device->getTimer()->getTime();
4025 if (time > last_time) // Make sure last_time hasn't overflowed
4026 *dtime = (time - last_time) / 1000.0;
4030 fps_timings->last_time = time;
4033 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
4035 const wchar_t *wmsg = wgettext(msg);
4036 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
4041 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4043 ((Game *)data)->readSettings();
4046 void Game::readSettings()
4048 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4049 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4050 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4051 m_cache_enable_particles = g_settings->getBool("enable_particles");
4052 m_cache_enable_fog = g_settings->getBool("enable_fog");
4053 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4054 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4055 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4057 m_cache_enable_noclip = g_settings->getBool("noclip");
4058 m_cache_enable_free_move = g_settings->getBool("free_move");
4060 m_cache_fog_start = g_settings->getFloat("fog_start");
4062 m_cache_cam_smoothing = 0;
4063 if (g_settings->getBool("cinematic"))
4064 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4066 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4068 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4069 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4070 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4072 m_does_lost_focus_pause_game = g_settings->getBool("pause_on_lost_focus");
4075 /****************************************************************************/
4076 /****************************************************************************
4078 ****************************************************************************/
4079 /****************************************************************************/
4081 void Game::extendedResourceCleanup()
4083 // Extended resource accounting
4084 infostream << "Irrlicht resources after cleanup:" << std::endl;
4085 infostream << "\tRemaining meshes : "
4086 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
4087 infostream << "\tRemaining textures : "
4088 << driver->getTextureCount() << std::endl;
4090 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4091 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4092 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4096 clearTextureNameCache();
4097 infostream << "\tRemaining materials: "
4098 << driver-> getMaterialRendererCount()
4099 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4102 void Game::showDeathFormspec()
4104 static std::string formspec_str =
4105 std::string("formspec_version[1]") +
4107 "bgcolor[#320000b4;true]"
4108 "label[4.85,1.35;" + gettext("You died") + "]"
4109 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
4113 /* Note: FormspecFormSource and LocalFormspecHandler *
4114 * are deleted by guiFormSpecMenu */
4115 FormspecFormSource *fs_src = new FormspecFormSource(formspec_str);
4116 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
4118 auto *&formspec = m_game_ui->getFormspecGUI();
4119 GUIFormSpecMenu::create(formspec, client, &input->joystick,
4120 fs_src, txt_dst, client->getFormspecPrepend());
4121 formspec->setFocus("btn_respawn");
4124 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4125 void Game::showPauseMenu()
4128 static const std::string control_text = strgettext("Default Controls:\n"
4129 "No menu visible:\n"
4130 "- single tap: button activate\n"
4131 "- double tap: place/use\n"
4132 "- slide finger: look around\n"
4133 "Menu/Inventory visible:\n"
4134 "- double tap (outside):\n"
4136 "- touch stack, touch slot:\n"
4138 "- touch&drag, tap 2nd finger\n"
4139 " --> place single item to slot\n"
4142 static const std::string control_text_template = strgettext("Controls:\n"
4143 "- %s: move forwards\n"
4144 "- %s: move backwards\n"
4146 "- %s: move right\n"
4147 "- %s: jump/climb\n"
4148 "- %s: sneak/go down\n"
4151 "- Mouse: turn/look\n"
4152 "- Mouse left: dig/punch\n"
4153 "- Mouse right: place/use\n"
4154 "- Mouse wheel: select item\n"
4158 char control_text_buf[600];
4160 porting::mt_snprintf(control_text_buf, sizeof(control_text_buf), control_text_template.c_str(),
4161 GET_KEY_NAME(keymap_forward),
4162 GET_KEY_NAME(keymap_backward),
4163 GET_KEY_NAME(keymap_left),
4164 GET_KEY_NAME(keymap_right),
4165 GET_KEY_NAME(keymap_jump),
4166 GET_KEY_NAME(keymap_sneak),
4167 GET_KEY_NAME(keymap_drop),
4168 GET_KEY_NAME(keymap_inventory),
4169 GET_KEY_NAME(keymap_chat)
4172 std::string control_text = std::string(control_text_buf);
4173 str_formspec_escape(control_text);
4176 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4177 std::ostringstream os;
4179 os << "formspec_version[1]" << SIZE_TAG
4180 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4181 << strgettext("Continue") << "]";
4183 if (!simple_singleplayer_mode) {
4184 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4185 << strgettext("Change Password") << "]";
4187 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4192 if (g_settings->getBool("enable_sound")) {
4193 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4194 << strgettext("Sound Volume") << "]";
4197 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4198 << strgettext("Change Keys") << "]";
4200 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4201 << strgettext("Exit to Menu") << "]";
4202 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4203 << strgettext("Exit to OS") << "]"
4204 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4205 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4207 << strgettext("Game info:") << "\n";
4208 const std::string &address = client->getAddressName();
4209 static const std::string mode = strgettext("- Mode: ");
4210 if (!simple_singleplayer_mode) {
4211 Address serverAddress = client->getServerAddress();
4212 if (!address.empty()) {
4213 os << mode << strgettext("Remote server") << "\n"
4214 << strgettext("- Address: ") << address;
4216 os << mode << strgettext("Hosting server");
4218 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4220 os << mode << strgettext("Singleplayer") << "\n";
4222 if (simple_singleplayer_mode || address.empty()) {
4223 static const std::string on = strgettext("On");
4224 static const std::string off = strgettext("Off");
4225 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4226 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4227 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4228 os << strgettext("- Damage: ") << damage << "\n"
4229 << strgettext("- Creative Mode: ") << creative << "\n";
4230 if (!simple_singleplayer_mode) {
4231 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4232 //~ PvP = Player versus Player
4233 os << strgettext("- PvP: ") << pvp << "\n"
4234 << strgettext("- Public: ") << announced << "\n";
4235 std::string server_name = g_settings->get("server_name");
4236 str_formspec_escape(server_name);
4237 if (announced == on && !server_name.empty())
4238 os << strgettext("- Server Name: ") << server_name;
4245 /* Note: FormspecFormSource and LocalFormspecHandler *
4246 * are deleted by guiFormSpecMenu */
4247 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4248 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4250 auto *&formspec = m_game_ui->getFormspecGUI();
4251 GUIFormSpecMenu::create(formspec, client, &input->joystick,
4252 fs_src, txt_dst, client->getFormspecPrepend());
4253 formspec->setFocus("btn_continue");
4254 formspec->doPause = true;
4257 /****************************************************************************/
4258 /****************************************************************************
4259 extern function for launching the game
4260 ****************************************************************************/
4261 /****************************************************************************/
4263 void the_game(bool *kill,
4265 InputHandler *input,
4266 const std::string &map_dir,
4267 const std::string &playername,
4268 const std::string &password,
4269 const std::string &address, // If empty local server is created
4272 std::string &error_message,
4273 ChatBackend &chat_backend,
4274 bool *reconnect_requested,
4275 const SubgameSpec &gamespec, // Used for local game
4276 bool simple_singleplayer_mode)
4280 /* Make a copy of the server address because if a local singleplayer server
4281 * is created then this is updated and we don't want to change the value
4282 * passed to us by the calling function
4284 std::string server_address = address;
4288 if (game.startup(kill, random_input, input, map_dir,
4289 playername, password, &server_address, port, error_message,
4290 reconnect_requested, &chat_backend, gamespec,
4291 simple_singleplayer_mode)) {
4295 } catch (SerializationError &e) {
4296 error_message = std::string("A serialization error occurred:\n")
4297 + e.what() + "\n\nThe server is probably "
4298 " running a different version of " PROJECT_NAME_C ".";
4299 errorstream << error_message << std::endl;
4300 } catch (ServerError &e) {
4301 error_message = e.what();
4302 errorstream << "ServerError: " << error_message << std::endl;
4303 } catch (ModError &e) {
4304 error_message = std::string("ModError: ") + e.what() +
4305 strgettext("\nCheck debug.txt for details.");
4306 errorstream << error_message << std::endl;