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;
270 SimpleSoundSpec m_player_step_sound;
271 SimpleSoundSpec m_player_leftpunch_sound;
272 SimpleSoundSpec m_player_rightpunch_sound;
274 SoundMaker(ISoundManager *sound, const NodeDefManager *ndef):
277 makes_footstep_sound(true),
278 m_player_step_timer(0)
282 void playPlayerStep()
284 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
285 m_player_step_timer = 0.03;
286 if (makes_footstep_sound)
287 m_sound->playSound(m_player_step_sound, false);
291 static void viewBobbingStep(MtEvent *e, void *data)
293 SoundMaker *sm = (SoundMaker *)data;
294 sm->playPlayerStep();
297 static void playerRegainGround(MtEvent *e, void *data)
299 SoundMaker *sm = (SoundMaker *)data;
300 sm->playPlayerStep();
303 static void playerJump(MtEvent *e, void *data)
305 //SoundMaker *sm = (SoundMaker*)data;
308 static void cameraPunchLeft(MtEvent *e, void *data)
310 SoundMaker *sm = (SoundMaker *)data;
311 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
314 static void cameraPunchRight(MtEvent *e, void *data)
316 SoundMaker *sm = (SoundMaker *)data;
317 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
320 static void nodeDug(MtEvent *e, void *data)
322 SoundMaker *sm = (SoundMaker *)data;
323 NodeDugEvent *nde = (NodeDugEvent *)e;
324 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
327 static void playerDamage(MtEvent *e, void *data)
329 SoundMaker *sm = (SoundMaker *)data;
330 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
333 static void playerFallingDamage(MtEvent *e, void *data)
335 SoundMaker *sm = (SoundMaker *)data;
336 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
339 void registerReceiver(MtEventManager *mgr)
341 mgr->reg(MtEvent::VIEW_BOBBING_STEP, SoundMaker::viewBobbingStep, this);
342 mgr->reg(MtEvent::PLAYER_REGAIN_GROUND, SoundMaker::playerRegainGround, this);
343 mgr->reg(MtEvent::PLAYER_JUMP, SoundMaker::playerJump, this);
344 mgr->reg(MtEvent::CAMERA_PUNCH_LEFT, SoundMaker::cameraPunchLeft, this);
345 mgr->reg(MtEvent::CAMERA_PUNCH_RIGHT, SoundMaker::cameraPunchRight, this);
346 mgr->reg(MtEvent::NODE_DUG, SoundMaker::nodeDug, this);
347 mgr->reg(MtEvent::PLAYER_DAMAGE, SoundMaker::playerDamage, this);
348 mgr->reg(MtEvent::PLAYER_FALLING_DAMAGE, SoundMaker::playerFallingDamage, this);
351 void step(float dtime)
353 m_player_step_timer -= dtime;
357 // Locally stored sounds don't need to be preloaded because of this
358 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
360 std::set<std::string> m_fetched;
362 void paths_insert(std::set<std::string> &dst_paths,
363 const std::string &base,
364 const std::string &name)
366 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
367 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
368 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
369 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
370 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
371 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
372 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
373 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
374 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
375 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
376 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
379 void fetchSounds(const std::string &name,
380 std::set<std::string> &dst_paths,
381 std::set<std::string> &dst_datas)
383 if (m_fetched.count(name))
386 m_fetched.insert(name);
388 paths_insert(dst_paths, porting::path_share, name);
389 paths_insert(dst_paths, porting::path_user, name);
394 // before 1.8 there isn't a "integer interface", only float
395 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
396 typedef f32 SamplerLayer_t;
398 typedef s32 SamplerLayer_t;
402 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
405 bool *m_force_fog_off;
408 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
409 CachedPixelShaderSetting<float> m_fog_distance;
410 CachedVertexShaderSetting<float> m_animation_timer_vertex;
411 CachedPixelShaderSetting<float> m_animation_timer_pixel;
412 CachedPixelShaderSetting<float, 3> m_day_light;
413 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
414 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
415 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
416 CachedPixelShaderSetting<float, 3> m_camera_offset_pixel;
417 CachedPixelShaderSetting<float, 3> m_camera_offset_vertex;
418 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
419 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
420 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
424 void onSettingsChange(const std::string &name)
426 if (name == "enable_fog")
427 m_fog_enabled = g_settings->getBool("enable_fog");
430 static void settingsCallback(const std::string &name, void *userdata)
432 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
435 void setSky(Sky *sky) { m_sky = sky; }
437 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
438 f32 *fog_range, Client *client) :
440 m_force_fog_off(force_fog_off),
441 m_fog_range(fog_range),
442 m_sky_bg_color("skyBgColor"),
443 m_fog_distance("fogDistance"),
444 m_animation_timer_vertex("animationTimer"),
445 m_animation_timer_pixel("animationTimer"),
446 m_day_light("dayLight"),
447 m_eye_position_pixel("eyePosition"),
448 m_eye_position_vertex("eyePosition"),
449 m_minimap_yaw("yawVec"),
450 m_camera_offset_pixel("cameraOffset"),
451 m_camera_offset_vertex("cameraOffset"),
452 m_base_texture("baseTexture"),
453 m_normal_texture("normalTexture"),
454 m_texture_flags("textureFlags"),
457 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
458 m_fog_enabled = g_settings->getBool("enable_fog");
461 ~GameGlobalShaderConstantSetter()
463 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
466 virtual void onSetConstants(video::IMaterialRendererServices *services,
473 video::SColor bgcolor = m_sky->getBgColor();
474 video::SColorf bgcolorf(bgcolor);
475 float bgcolorfa[4] = {
481 m_sky_bg_color.set(bgcolorfa, services);
484 float fog_distance = 10000 * BS;
486 if (m_fog_enabled && !*m_force_fog_off)
487 fog_distance = *m_fog_range;
489 m_fog_distance.set(&fog_distance, services);
491 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
492 video::SColorf sunlight;
493 get_sunlight_color(&sunlight, daynight_ratio);
498 m_day_light.set(dnc, services);
500 u32 animation_timer = porting::getTimeMs() % 1000000;
501 float animation_timer_f = (float)animation_timer / 100000.f;
502 m_animation_timer_vertex.set(&animation_timer_f, services);
503 m_animation_timer_pixel.set(&animation_timer_f, services);
505 float eye_position_array[3];
506 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
507 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
508 eye_position_array[0] = epos.X;
509 eye_position_array[1] = epos.Y;
510 eye_position_array[2] = epos.Z;
512 epos.getAs3Values(eye_position_array);
514 m_eye_position_pixel.set(eye_position_array, services);
515 m_eye_position_vertex.set(eye_position_array, services);
517 if (m_client->getMinimap()) {
518 float minimap_yaw_array[3];
519 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
520 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
521 minimap_yaw_array[0] = minimap_yaw.X;
522 minimap_yaw_array[1] = minimap_yaw.Y;
523 minimap_yaw_array[2] = minimap_yaw.Z;
525 minimap_yaw.getAs3Values(minimap_yaw_array);
527 m_minimap_yaw.set(minimap_yaw_array, services);
530 float camera_offset_array[3];
531 v3f offset = intToFloat(m_client->getCamera()->getOffset(), BS);
532 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
533 camera_offset_array[0] = offset.X;
534 camera_offset_array[1] = offset.Y;
535 camera_offset_array[2] = offset.Z;
537 offset.getAs3Values(camera_offset_array);
539 m_camera_offset_pixel.set(camera_offset_array, services);
540 m_camera_offset_vertex.set(camera_offset_array, services);
542 SamplerLayer_t base_tex = 0,
545 m_base_texture.set(&base_tex, services);
546 m_normal_texture.set(&normal_tex, services);
547 m_texture_flags.set(&flags_tex, services);
552 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
555 bool *m_force_fog_off;
558 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
560 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
561 f32 *fog_range, Client *client) :
563 m_force_fog_off(force_fog_off),
564 m_fog_range(fog_range),
568 void setSky(Sky *sky) {
570 for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
571 ggscs->setSky(m_sky);
573 created_nosky.clear();
576 virtual IShaderConstantSetter* create()
578 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
579 m_sky, m_force_fog_off, m_fog_range, m_client);
581 created_nosky.push_back(scs);
587 #define SIZE_TAG "size[11,5.5]"
589 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
592 /****************************************************************************
594 ****************************************************************************/
596 const float object_hit_delay = 0.2;
599 u32 last_time, busy_time, sleep_time;
603 /* The reason the following structs are not anonymous structs within the
604 * class is that they are not used by the majority of member functions and
605 * many functions that do require objects of thse types do not modify them
606 * (so they can be passed as a const qualified parameter)
612 PointedThing pointed_old;
616 bool digging_blocked;
618 bool reset_jump_timer;
619 float nodig_delay_timer;
621 float dig_time_complete;
622 float repeat_rightclick_timer;
623 float object_hit_delay_timer;
624 float time_from_last_punch;
625 ClientActiveObject *selected_object;
629 float update_draw_list_timer;
633 v3f update_draw_list_last_cam_dir;
635 float time_of_day_smooth;
640 struct ClientEventHandler
642 void (Game::*handler)(ClientEvent *, CameraOrientation *);
645 /****************************************************************************
647 ****************************************************************************/
649 /* This is not intended to be a public class. If a public class becomes
650 * desirable then it may be better to create another 'wrapper' class that
651 * hides most of the stuff in this class (nothing in this class is required
652 * by any other file) but exposes the public methods/data only.
659 bool startup(bool *kill,
662 const std::string &map_dir,
663 const std::string &playername,
664 const std::string &password,
665 // If address is "", local server is used and address is updated
666 std::string *address,
668 std::string &error_message,
670 ChatBackend *chat_backend,
671 const SubgameSpec &gamespec, // Used for local game
672 bool simple_singleplayer_mode);
679 void extendedResourceCleanup();
681 // Basic initialisation
682 bool init(const std::string &map_dir, std::string *address,
684 const SubgameSpec &gamespec);
686 bool createSingleplayerServer(const std::string &map_dir,
687 const SubgameSpec &gamespec, u16 port, std::string *address);
690 bool createClient(const std::string &playername,
691 const std::string &password, std::string *address, u16 port);
695 bool connectToServer(const std::string &playername,
696 const std::string &password, std::string *address, u16 port,
697 bool *connect_ok, bool *aborted);
698 bool getServerContent(bool *aborted);
702 void updateInteractTimers(f32 dtime);
703 bool checkConnection();
704 bool handleCallbacks();
705 void processQueues();
706 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
707 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
708 void updateProfilerGraphs(ProfilerGraph *graph);
711 void processUserInput(f32 dtime);
712 void processKeyInput();
713 void processItemSelection(u16 *new_playeritem);
715 void dropSelectedItem(bool single_item = false);
716 void openInventory();
717 void openConsole(float scale, const wchar_t *line=NULL);
718 void toggleFreeMove();
719 void toggleFreeMoveAlt();
720 void togglePitchMove();
723 void toggleCinematic();
724 void toggleAutoforward();
726 void toggleMinimap(bool shift_pressed);
729 void toggleUpdateCamera();
731 void increaseViewRange();
732 void decreaseViewRange();
733 void toggleFullViewRange();
734 void checkZoomEnabled();
736 void updateCameraDirection(CameraOrientation *cam, float dtime);
737 void updateCameraOrientation(CameraOrientation *cam, float dtime);
738 void updatePlayerControl(const CameraOrientation &cam);
739 void step(f32 *dtime);
740 void processClientEvents(CameraOrientation *cam);
741 void updateCamera(u32 busy_time, f32 dtime);
742 void updateSound(f32 dtime);
743 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
745 * Returns the object or node the player is pointing at.
746 * Also updates the selected thing in the Hud.
748 * @param[in] shootline the shootline, starting from
749 * the camera position. This also gives the maximal distance
751 * @param[in] liquids_pointable if false, liquids are ignored
752 * @param[in] look_for_object if false, objects are ignored
753 * @param[in] camera_offset offset of the camera
754 * @param[out] selected_object the selected object or
757 PointedThing updatePointedThing(
758 const core::line3d<f32> &shootline, bool liquids_pointable,
759 bool look_for_object, const v3s16 &camera_offset);
760 void handlePointingAtNothing(const ItemStack &playerItem);
761 void handlePointingAtNode(const PointedThing &pointed,
762 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime);
763 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
764 const v3f &player_position, bool show_debug);
765 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
766 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime);
767 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
768 const CameraOrientation &cam);
771 void limitFps(FpsControl *fps_timings, f32 *dtime);
773 void showOverlayMessage(const char *msg, float dtime, int percent,
774 bool draw_clouds = true);
776 static void settingChangedCallback(const std::string &setting_name, void *data);
779 inline bool isKeyDown(GameKeyType k)
781 return input->isKeyDown(k);
783 inline bool wasKeyDown(GameKeyType k)
785 return input->wasKeyDown(k);
789 void handleAndroidChatInput();
794 bool force_fog_off = false;
795 bool disable_camera_update = false;
798 void showDeathFormspec();
799 void showPauseMenu();
801 // ClientEvent handlers
802 void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam);
803 void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam);
804 void handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam);
805 void handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam);
806 void handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam);
807 void handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam);
808 void handleClientEvent_HandleParticleEvent(ClientEvent *event,
809 CameraOrientation *cam);
810 void handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam);
811 void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam);
812 void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam);
813 void handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam);
814 void handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
815 CameraOrientation *cam);
816 void handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam);
818 void updateChat(f32 dtime, const v2u32 &screensize);
820 bool nodePlacement(const ItemDefinition &selected_def, const ItemStack &selected_item,
821 const v3s16 &nodepos, const v3s16 &neighbourpos, const PointedThing &pointed,
822 const NodeMetadata *meta);
823 static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX];
825 InputHandler *input = nullptr;
827 Client *client = nullptr;
828 Server *server = nullptr;
830 IWritableTextureSource *texture_src = nullptr;
831 IWritableShaderSource *shader_src = nullptr;
833 // When created, these will be filled with data received from the server
834 IWritableItemDefManager *itemdef_manager = nullptr;
835 NodeDefManager *nodedef_manager = nullptr;
837 GameOnDemandSoundFetcher soundfetcher; // useful when testing
838 ISoundManager *sound = nullptr;
839 bool sound_is_dummy = false;
840 SoundMaker *soundmaker = nullptr;
842 ChatBackend *chat_backend = nullptr;
844 EventManager *eventmgr = nullptr;
845 QuicktuneShortcutter *quicktune = nullptr;
846 bool registration_confirmation_shown = false;
848 std::unique_ptr<GameUI> m_game_ui;
849 GUIChatConsole *gui_chat_console = nullptr; // Free using ->Drop()
850 MapDrawControl *draw_control = nullptr;
851 Camera *camera = nullptr;
852 Clouds *clouds = nullptr; // Free using ->Drop()
853 Sky *sky = nullptr; // Free using ->Drop()
855 Minimap *mapper = nullptr;
861 This class does take ownership/responsibily for cleaning up etc of any of
862 these items (e.g. device)
864 IrrlichtDevice *device;
865 video::IVideoDriver *driver;
866 scene::ISceneManager *smgr;
868 std::string *error_message;
869 bool *reconnect_requested;
870 scene::ISceneNode *skybox;
873 bool simple_singleplayer_mode;
876 /* Pre-calculated values
878 int crack_animation_length;
880 IntervalLimiter profiler_interval;
883 * TODO: Local caching of settings is not optimal and should at some stage
884 * be updated to use a global settings object for getting thse values
885 * (as opposed to the this local caching). This can be addressed in
888 bool m_cache_doubletap_jump;
889 bool m_cache_enable_clouds;
890 bool m_cache_enable_joysticks;
891 bool m_cache_enable_particles;
892 bool m_cache_enable_fog;
893 bool m_cache_enable_noclip;
894 bool m_cache_enable_free_move;
895 f32 m_cache_mouse_sensitivity;
896 f32 m_cache_joystick_frustum_sensitivity;
897 f32 m_repeat_right_click_time;
898 f32 m_cache_cam_smoothing;
899 f32 m_cache_fog_start;
901 bool m_invert_mouse = false;
902 bool m_first_loop_after_window_activation = false;
903 bool m_camera_offset_changed = false;
905 bool m_does_lost_focus_pause_game = false;
908 bool m_cache_hold_aux1;
909 bool m_android_chat_open;
914 m_game_ui(new GameUI())
916 g_settings->registerChangedCallback("doubletap_jump",
917 &settingChangedCallback, this);
918 g_settings->registerChangedCallback("enable_clouds",
919 &settingChangedCallback, this);
920 g_settings->registerChangedCallback("doubletap_joysticks",
921 &settingChangedCallback, this);
922 g_settings->registerChangedCallback("enable_particles",
923 &settingChangedCallback, this);
924 g_settings->registerChangedCallback("enable_fog",
925 &settingChangedCallback, this);
926 g_settings->registerChangedCallback("mouse_sensitivity",
927 &settingChangedCallback, this);
928 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
929 &settingChangedCallback, this);
930 g_settings->registerChangedCallback("repeat_rightclick_time",
931 &settingChangedCallback, this);
932 g_settings->registerChangedCallback("noclip",
933 &settingChangedCallback, this);
934 g_settings->registerChangedCallback("free_move",
935 &settingChangedCallback, this);
936 g_settings->registerChangedCallback("cinematic",
937 &settingChangedCallback, this);
938 g_settings->registerChangedCallback("cinematic_camera_smoothing",
939 &settingChangedCallback, this);
940 g_settings->registerChangedCallback("camera_smoothing",
941 &settingChangedCallback, this);
946 m_cache_hold_aux1 = false; // This is initialised properly later
953 /****************************************************************************
955 ****************************************************************************/
964 delete server; // deleted first to stop all server threads
972 delete nodedef_manager;
973 delete itemdef_manager;
976 extendedResourceCleanup();
978 g_settings->deregisterChangedCallback("doubletap_jump",
979 &settingChangedCallback, this);
980 g_settings->deregisterChangedCallback("enable_clouds",
981 &settingChangedCallback, this);
982 g_settings->deregisterChangedCallback("enable_particles",
983 &settingChangedCallback, this);
984 g_settings->deregisterChangedCallback("enable_fog",
985 &settingChangedCallback, this);
986 g_settings->deregisterChangedCallback("mouse_sensitivity",
987 &settingChangedCallback, this);
988 g_settings->deregisterChangedCallback("repeat_rightclick_time",
989 &settingChangedCallback, this);
990 g_settings->deregisterChangedCallback("noclip",
991 &settingChangedCallback, this);
992 g_settings->deregisterChangedCallback("free_move",
993 &settingChangedCallback, this);
994 g_settings->deregisterChangedCallback("cinematic",
995 &settingChangedCallback, this);
996 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
997 &settingChangedCallback, this);
998 g_settings->deregisterChangedCallback("camera_smoothing",
999 &settingChangedCallback, this);
1002 bool Game::startup(bool *kill,
1004 InputHandler *input,
1005 const std::string &map_dir,
1006 const std::string &playername,
1007 const std::string &password,
1008 std::string *address, // can change if simple_singleplayer_mode
1010 std::string &error_message,
1012 ChatBackend *chat_backend,
1013 const SubgameSpec &gamespec,
1014 bool simple_singleplayer_mode)
1017 this->device = RenderingEngine::get_raw_device();
1019 this->error_message = &error_message;
1020 this->reconnect_requested = reconnect;
1021 this->random_input = random_input;
1022 this->input = input;
1023 this->chat_backend = chat_backend;
1024 this->simple_singleplayer_mode = simple_singleplayer_mode;
1026 input->keycache.populate();
1028 driver = device->getVideoDriver();
1029 smgr = RenderingEngine::get_scene_manager();
1031 RenderingEngine::get_scene_manager()->getParameters()->
1032 setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1035 runData = GameRunData();
1036 runData.time_from_last_punch = 10.0;
1038 m_game_ui->initFlags();
1040 m_invert_mouse = g_settings->getBool("invert_mouse");
1041 m_first_loop_after_window_activation = true;
1043 g_translations->clear();
1045 if (!init(map_dir, address, port, gamespec))
1048 if (!createClient(playername, password, address, port))
1051 RenderingEngine::initialize(client, hud);
1059 ProfilerGraph graph;
1060 RunStats stats = { 0 };
1061 CameraOrientation cam_view_target = { 0 };
1062 CameraOrientation cam_view = { 0 };
1063 FpsControl draw_times = { 0 };
1064 f32 dtime; // in seconds
1066 /* Clear the profiler */
1067 Profiler::GraphValues dummyvalues;
1068 g_profiler->graphGet(dummyvalues);
1070 draw_times.last_time = RenderingEngine::get_timer_time();
1072 set_light_table(g_settings->getFloat("display_gamma"));
1075 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1076 && client->checkPrivilege("fast");
1079 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1080 g_settings->getU16("screen_h"));
1082 while (RenderingEngine::run()
1083 && !(*kill || g_gamecallback->shutdown_requested
1084 || (server && server->isShutdownRequested()))) {
1086 const irr::core::dimension2d<u32> ¤t_screen_size =
1087 RenderingEngine::get_video_driver()->getScreenSize();
1088 // Verify if window size has changed and save it if it's the case
1089 // Ensure evaluating settings->getBool after verifying screensize
1090 // First condition is cheaper
1091 if (previous_screen_size != current_screen_size &&
1092 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1093 g_settings->getBool("autosave_screensize")) {
1094 g_settings->setU16("screen_w", current_screen_size.Width);
1095 g_settings->setU16("screen_h", current_screen_size.Height);
1096 previous_screen_size = current_screen_size;
1099 // Calculate dtime =
1100 // RenderingEngine::run() from this iteration
1101 // + Sleep time until the wanted FPS are reached
1102 limitFps(&draw_times, &dtime);
1104 // Prepare render data for next iteration
1106 updateStats(&stats, draw_times, dtime);
1107 updateInteractTimers(dtime);
1109 if (!checkConnection())
1111 if (!handleCallbacks())
1116 m_game_ui->clearInfoText();
1117 hud->resizeHotbar();
1119 updateProfilers(stats, draw_times, dtime);
1120 processUserInput(dtime);
1121 // Update camera before player movement to avoid camera lag of one frame
1122 updateCameraDirection(&cam_view_target, dtime);
1123 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1124 cam_view.camera_yaw) * m_cache_cam_smoothing;
1125 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1126 cam_view.camera_pitch) * m_cache_cam_smoothing;
1127 updatePlayerControl(cam_view);
1129 processClientEvents(&cam_view_target);
1130 updateCamera(draw_times.busy_time, dtime);
1132 processPlayerInteraction(dtime, m_game_ui->m_flags.show_hud,
1133 m_game_ui->m_flags.show_debug);
1134 updateFrame(&graph, &stats, dtime, cam_view);
1135 updateProfilerGraphs(&graph);
1137 // Update if minimap has been disabled by the server
1138 m_game_ui->m_flags.show_minimap &= client->shouldShowMinimap();
1140 if (m_does_lost_focus_pause_game && !device->isWindowFocused() && !isMenuActive()) {
1147 void Game::shutdown()
1149 RenderingEngine::finalize();
1150 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1151 if (g_settings->get("3d_mode") == "pageflip") {
1152 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1155 auto formspec = m_game_ui->getFormspecGUI();
1157 formspec->quitMenu();
1159 showOverlayMessage(N_("Shutting down..."), 0, 0, false);
1164 if (gui_chat_console)
1165 gui_chat_console->drop();
1171 while (g_menumgr.menuCount() > 0) {
1172 g_menumgr.m_stack.front()->setVisible(false);
1173 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1176 m_game_ui->deleteFormspec();
1178 chat_backend->addMessage(L"", L"# Disconnected.");
1179 chat_backend->addMessage(L"", L"");
1183 while (!client->isShutdown()) {
1184 assert(texture_src != NULL);
1185 assert(shader_src != NULL);
1186 texture_src->processQueue();
1187 shader_src->processQueue();
1194 /****************************************************************************/
1195 /****************************************************************************
1197 ****************************************************************************/
1198 /****************************************************************************/
1201 const std::string &map_dir,
1202 std::string *address,
1204 const SubgameSpec &gamespec)
1206 texture_src = createTextureSource();
1208 showOverlayMessage(N_("Loading..."), 0, 0);
1210 shader_src = createShaderSource();
1212 itemdef_manager = createItemDefManager();
1213 nodedef_manager = createNodeDefManager();
1215 eventmgr = new EventManager();
1216 quicktune = new QuicktuneShortcutter();
1218 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1219 && eventmgr && quicktune))
1225 // Create a server if not connecting to an existing one
1226 if (address->empty()) {
1227 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1234 bool Game::initSound()
1237 if (g_settings->getBool("enable_sound")) {
1238 infostream << "Attempting to use OpenAL audio" << std::endl;
1239 sound = createOpenALSoundManager(g_sound_manager_singleton.get(), &soundfetcher);
1241 infostream << "Failed to initialize OpenAL audio" << std::endl;
1243 infostream << "Sound disabled." << std::endl;
1247 infostream << "Using dummy audio." << std::endl;
1248 sound = &dummySoundManager;
1249 sound_is_dummy = true;
1252 soundmaker = new SoundMaker(sound, nodedef_manager);
1256 soundmaker->registerReceiver(eventmgr);
1261 bool Game::createSingleplayerServer(const std::string &map_dir,
1262 const SubgameSpec &gamespec, u16 port, std::string *address)
1264 showOverlayMessage(N_("Creating server..."), 0, 5);
1266 std::string bind_str = g_settings->get("bind_address");
1267 Address bind_addr(0, 0, 0, 0, port);
1269 if (g_settings->getBool("ipv6_server")) {
1270 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1274 bind_addr.Resolve(bind_str.c_str());
1275 } catch (ResolveError &e) {
1276 infostream << "Resolving bind address \"" << bind_str
1277 << "\" failed: " << e.what()
1278 << " -- Listening on all addresses." << std::endl;
1281 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1282 *error_message = "Unable to listen on " +
1283 bind_addr.serializeString() +
1284 " because IPv6 is disabled";
1285 errorstream << *error_message << std::endl;
1289 server = new Server(map_dir, gamespec, simple_singleplayer_mode, bind_addr, false);
1296 bool Game::createClient(const std::string &playername,
1297 const std::string &password, std::string *address, u16 port)
1299 showOverlayMessage(N_("Creating client..."), 0, 10);
1301 draw_control = new MapDrawControl;
1305 bool could_connect, connect_aborted;
1306 #ifdef HAVE_TOUCHSCREENGUI
1307 if (g_touchscreengui) {
1308 g_touchscreengui->init(texture_src);
1309 g_touchscreengui->hide();
1312 if (!connectToServer(playername, password, address, port,
1313 &could_connect, &connect_aborted))
1316 if (!could_connect) {
1317 if (error_message->empty() && !connect_aborted) {
1318 // Should not happen if error messages are set properly
1319 *error_message = "Connection failed for unknown reason";
1320 errorstream << *error_message << std::endl;
1325 if (!getServerContent(&connect_aborted)) {
1326 if (error_message->empty() && !connect_aborted) {
1327 // Should not happen if error messages are set properly
1328 *error_message = "Connection failed for unknown reason";
1329 errorstream << *error_message << std::endl;
1334 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1335 &m_flags.force_fog_off, &runData.fog_range, client);
1336 shader_src->addShaderConstantSetterFactory(scsf);
1338 // Update cached textures, meshes and materials
1339 client->afterContentReceived();
1343 camera = new Camera(*draw_control, client);
1344 if (!camera || !camera->successfullyCreated(*error_message))
1346 client->setCamera(camera);
1350 if (m_cache_enable_clouds) {
1351 clouds = new Clouds(smgr, -1, time(0));
1353 *error_message = "Memory allocation error (clouds)";
1354 errorstream << *error_message << std::endl;
1361 sky = new Sky(-1, texture_src);
1363 skybox = NULL; // This is used/set later on in the main run loop
1366 *error_message = "Memory allocation error sky";
1367 errorstream << *error_message << std::endl;
1371 /* Pre-calculated values
1373 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1375 v2u32 size = t->getOriginalSize();
1376 crack_animation_length = size.Y / size.X;
1378 crack_animation_length = 5;
1384 /* Set window caption
1386 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1388 str += utf8_to_wide(g_version_hash);
1390 str += driver->getName();
1392 device->setWindowCaption(str.c_str());
1394 LocalPlayer *player = client->getEnv().getLocalPlayer();
1395 player->hurt_tilt_timer = 0;
1396 player->hurt_tilt_strength = 0;
1398 hud = new Hud(guienv, client, player, &player->inventory);
1401 *error_message = "Memory error: could not create HUD";
1402 errorstream << *error_message << std::endl;
1406 mapper = client->getMinimap();
1408 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1413 bool Game::initGui()
1417 // Remove stale "recent" chat messages from previous connections
1418 chat_backend->clearRecentChat();
1420 // Make sure the size of the recent messages buffer is right
1421 chat_backend->applySettings();
1423 // Chat backend and console
1424 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
1425 -1, chat_backend, client, &g_menumgr);
1426 if (!gui_chat_console) {
1427 *error_message = "Could not allocate memory for chat console";
1428 errorstream << *error_message << std::endl;
1432 #ifdef HAVE_TOUCHSCREENGUI
1434 if (g_touchscreengui)
1435 g_touchscreengui->show();
1442 bool Game::connectToServer(const std::string &playername,
1443 const std::string &password, std::string *address, u16 port,
1444 bool *connect_ok, bool *connection_aborted)
1446 *connect_ok = false; // Let's not be overly optimistic
1447 *connection_aborted = false;
1448 bool local_server_mode = false;
1450 showOverlayMessage(N_("Resolving address..."), 0, 15);
1452 Address connect_address(0, 0, 0, 0, port);
1455 connect_address.Resolve(address->c_str());
1457 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1458 //connect_address.Resolve("localhost");
1459 if (connect_address.isIPv6()) {
1460 IPv6AddressBytes addr_bytes;
1461 addr_bytes.bytes[15] = 1;
1462 connect_address.setAddress(&addr_bytes);
1464 connect_address.setAddress(127, 0, 0, 1);
1466 local_server_mode = true;
1468 } catch (ResolveError &e) {
1469 *error_message = std::string("Couldn't resolve address: ") + e.what();
1470 errorstream << *error_message << std::endl;
1474 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1475 *error_message = "Unable to connect to " +
1476 connect_address.serializeString() +
1477 " because IPv6 is disabled";
1478 errorstream << *error_message << std::endl;
1482 client = new Client(playername.c_str(), password, *address,
1483 *draw_control, texture_src, shader_src,
1484 itemdef_manager, nodedef_manager, sound, eventmgr,
1485 connect_address.isIPv6(), m_game_ui.get());
1490 client->m_simple_singleplayer_mode = simple_singleplayer_mode;
1492 infostream << "Connecting to server at ";
1493 connect_address.print(&infostream);
1494 infostream << std::endl;
1496 client->connect(connect_address,
1497 simple_singleplayer_mode || local_server_mode);
1500 Wait for server to accept connection
1506 FpsControl fps_control = { 0 };
1508 f32 wait_time = 0; // in seconds
1510 fps_control.last_time = RenderingEngine::get_timer_time();
1512 while (RenderingEngine::run()) {
1514 limitFps(&fps_control, &dtime);
1516 // Update client and server
1517 client->step(dtime);
1520 server->step(dtime);
1523 if (client->getState() == LC_Init) {
1529 if (*connection_aborted)
1532 if (client->accessDenied()) {
1533 *error_message = "Access denied. Reason: "
1534 + client->accessDeniedReason();
1535 *reconnect_requested = client->reconnectRequested();
1536 errorstream << *error_message << std::endl;
1540 if (input->cancelPressed()) {
1541 *connection_aborted = true;
1542 infostream << "Connect aborted [Escape]" << std::endl;
1546 if (client->m_is_registration_confirmation_state) {
1547 if (registration_confirmation_shown) {
1548 // Keep drawing the GUI
1549 RenderingEngine::draw_menu_scene(guienv, dtime, true);
1551 registration_confirmation_shown = true;
1552 (new GUIConfirmRegistration(guienv, guienv->getRootGUIElement(), -1,
1553 &g_menumgr, client, playername, password, connection_aborted))->drop();
1557 // Only time out if we aren't waiting for the server we started
1558 if (!address->empty() && wait_time > 10) {
1559 *error_message = "Connection timed out.";
1560 errorstream << *error_message << std::endl;
1565 showOverlayMessage(N_("Connecting to server..."), dtime, 20);
1568 } catch (con::PeerNotFoundException &e) {
1569 // TODO: Should something be done here? At least an info/error
1577 bool Game::getServerContent(bool *aborted)
1581 FpsControl fps_control = { 0 };
1582 f32 dtime; // in seconds
1584 fps_control.last_time = RenderingEngine::get_timer_time();
1586 while (RenderingEngine::run()) {
1588 limitFps(&fps_control, &dtime);
1590 // Update client and server
1591 client->step(dtime);
1594 server->step(dtime);
1597 if (client->mediaReceived() && client->itemdefReceived() &&
1598 client->nodedefReceived()) {
1603 if (!checkConnection())
1606 if (client->getState() < LC_Init) {
1607 *error_message = "Client disconnected";
1608 errorstream << *error_message << std::endl;
1612 if (input->cancelPressed()) {
1614 infostream << "Connect aborted [Escape]" << std::endl;
1621 if (!client->itemdefReceived()) {
1622 const wchar_t *text = wgettext("Item definitions...");
1624 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1627 } else if (!client->nodedefReceived()) {
1628 const wchar_t *text = wgettext("Node definitions...");
1630 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1634 std::stringstream message;
1635 std::fixed(message);
1636 message.precision(0);
1637 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
1638 message.precision(2);
1640 if ((USE_CURL == 0) ||
1641 (!g_settings->getBool("enable_remote_media_server"))) {
1642 float cur = client->getCurRate();
1643 std::string cur_unit = gettext("KiB/s");
1647 cur_unit = gettext("MiB/s");
1650 message << " (" << cur << ' ' << cur_unit << ")";
1653 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
1654 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
1655 texture_src, dtime, progress);
1663 /****************************************************************************/
1664 /****************************************************************************
1666 ****************************************************************************/
1667 /****************************************************************************/
1669 inline void Game::updateInteractTimers(f32 dtime)
1671 if (runData.nodig_delay_timer >= 0)
1672 runData.nodig_delay_timer -= dtime;
1674 if (runData.object_hit_delay_timer >= 0)
1675 runData.object_hit_delay_timer -= dtime;
1677 runData.time_from_last_punch += dtime;
1681 /* returns false if game should exit, otherwise true
1683 inline bool Game::checkConnection()
1685 if (client->accessDenied()) {
1686 *error_message = "Access denied. Reason: "
1687 + client->accessDeniedReason();
1688 *reconnect_requested = client->reconnectRequested();
1689 errorstream << *error_message << std::endl;
1697 /* returns false if game should exit, otherwise true
1699 inline bool Game::handleCallbacks()
1701 if (g_gamecallback->disconnect_requested) {
1702 g_gamecallback->disconnect_requested = false;
1706 if (g_gamecallback->changepassword_requested) {
1707 (new GUIPasswordChange(guienv, guiroot, -1,
1708 &g_menumgr, client))->drop();
1709 g_gamecallback->changepassword_requested = false;
1712 if (g_gamecallback->changevolume_requested) {
1713 (new GUIVolumeChange(guienv, guiroot, -1,
1714 &g_menumgr))->drop();
1715 g_gamecallback->changevolume_requested = false;
1718 if (g_gamecallback->keyconfig_requested) {
1719 (new GUIKeyChangeMenu(guienv, guiroot, -1,
1720 &g_menumgr))->drop();
1721 g_gamecallback->keyconfig_requested = false;
1724 if (g_gamecallback->keyconfig_changed) {
1725 input->keycache.populate(); // update the cache with new settings
1726 g_gamecallback->keyconfig_changed = false;
1733 void Game::processQueues()
1735 texture_src->processQueue();
1736 itemdef_manager->processQueue(client);
1737 shader_src->processQueue();
1741 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times,
1744 float profiler_print_interval =
1745 g_settings->getFloat("profiler_print_interval");
1746 bool print_to_log = true;
1748 if (profiler_print_interval == 0) {
1749 print_to_log = false;
1750 profiler_print_interval = 3;
1753 if (profiler_interval.step(dtime, profiler_print_interval)) {
1755 infostream << "Profiler:" << std::endl;
1756 g_profiler->print(infostream);
1759 m_game_ui->updateProfiler();
1760 g_profiler->clear();
1763 // Update update graphs
1764 g_profiler->graphAdd("Time non-rendering [ms]",
1765 draw_times.busy_time - stats.drawtime);
1767 g_profiler->graphAdd("Sleep [ms]", draw_times.sleep_time);
1768 g_profiler->graphAdd("FPS", 1.0f / dtime);
1771 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
1778 /* Time average and jitter calculation
1780 jp = &stats->dtime_jitter;
1781 jp->avg = jp->avg * 0.96 + dtime * 0.04;
1783 jitter = dtime - jp->avg;
1785 if (jitter > jp->max)
1788 jp->counter += dtime;
1790 if (jp->counter > 0.0) {
1792 jp->max_sample = jp->max;
1793 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
1797 /* Busytime average and jitter calculation
1799 jp = &stats->busy_time_jitter;
1800 jp->avg = jp->avg + draw_times.busy_time * 0.02;
1802 jitter = draw_times.busy_time - jp->avg;
1804 if (jitter > jp->max)
1806 if (jitter < jp->min)
1809 jp->counter += dtime;
1811 if (jp->counter > 0.0) {
1813 jp->max_sample = jp->max;
1814 jp->min_sample = jp->min;
1822 /****************************************************************************
1824 ****************************************************************************/
1826 void Game::processUserInput(f32 dtime)
1828 // Reset input if window not active or some menu is active
1829 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
1831 #ifdef HAVE_TOUCHSCREENGUI
1832 g_touchscreengui->hide();
1835 #ifdef HAVE_TOUCHSCREENGUI
1836 else if (g_touchscreengui) {
1837 /* on touchscreengui step may generate own input events which ain't
1838 * what we want in case we just did clear them */
1839 g_touchscreengui->step(dtime);
1843 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
1844 gui_chat_console->closeConsoleAtOnce();
1847 // Input handler step() (used by the random input generator)
1851 auto formspec = m_game_ui->getFormspecGUI();
1853 formspec->getAndroidUIInput();
1855 handleAndroidChatInput();
1858 // Increase timer for double tap of "keymap_jump"
1859 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
1860 runData.jump_timer += dtime;
1863 processItemSelection(&runData.new_playeritem);
1867 void Game::processKeyInput()
1869 if (wasKeyDown(KeyType::DROP)) {
1870 dropSelectedItem(isKeyDown(KeyType::SNEAK));
1871 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
1872 toggleAutoforward();
1873 } else if (wasKeyDown(KeyType::BACKWARD)) {
1874 if (g_settings->getBool("continuous_forward"))
1875 toggleAutoforward();
1876 } else if (wasKeyDown(KeyType::INVENTORY)) {
1878 } else if (input->cancelPressed()) {
1880 m_android_chat_open = false;
1882 if (!gui_chat_console->isOpenInhibited()) {
1885 } else if (wasKeyDown(KeyType::CHAT)) {
1886 openConsole(0.2, L"");
1887 } else if (wasKeyDown(KeyType::CMD)) {
1888 openConsole(0.2, L"/");
1889 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
1890 if (client->modsLoaded())
1891 openConsole(0.2, L".");
1893 m_game_ui->showStatusText(wgettext("Client side scripting is disabled"));
1894 } else if (wasKeyDown(KeyType::CONSOLE)) {
1895 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
1896 } else if (wasKeyDown(KeyType::FREEMOVE)) {
1898 } else if (wasKeyDown(KeyType::JUMP)) {
1899 toggleFreeMoveAlt();
1900 } else if (wasKeyDown(KeyType::PITCHMOVE)) {
1902 } else if (wasKeyDown(KeyType::FASTMOVE)) {
1904 } else if (wasKeyDown(KeyType::NOCLIP)) {
1906 } else if (wasKeyDown(KeyType::MUTE)) {
1907 bool new_mute_sound = !g_settings->getBool("mute_sound");
1908 g_settings->setBool("mute_sound", new_mute_sound);
1910 m_game_ui->showTranslatedStatusText("Sound muted");
1912 m_game_ui->showTranslatedStatusText("Sound unmuted");
1913 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
1914 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
1916 g_settings->setFloat("sound_volume", new_volume);
1917 const wchar_t *str = wgettext("Volume changed to %d%%");
1918 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1920 m_game_ui->showStatusText(buf);
1921 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
1922 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
1924 g_settings->setFloat("sound_volume", new_volume);
1925 const wchar_t *str = wgettext("Volume changed to %d%%");
1926 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1928 m_game_ui->showStatusText(buf);
1929 } else if (wasKeyDown(KeyType::CINEMATIC)) {
1931 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
1932 client->makeScreenshot();
1933 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
1934 m_game_ui->toggleHud();
1935 } else if (wasKeyDown(KeyType::MINIMAP)) {
1936 toggleMinimap(isKeyDown(KeyType::SNEAK));
1937 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
1938 m_game_ui->toggleChat();
1939 } else if (wasKeyDown(KeyType::TOGGLE_FOG)) {
1941 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
1942 toggleUpdateCamera();
1943 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
1945 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
1946 m_game_ui->toggleProfiler();
1947 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
1948 increaseViewRange();
1949 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
1950 decreaseViewRange();
1951 } else if (wasKeyDown(KeyType::RANGESELECT)) {
1952 toggleFullViewRange();
1953 } else if (wasKeyDown(KeyType::ZOOM)) {
1955 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
1957 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
1959 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
1961 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
1965 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
1966 runData.reset_jump_timer = false;
1967 runData.jump_timer = 0.0f;
1970 if (quicktune->hasMessage()) {
1971 m_game_ui->showStatusText(utf8_to_wide(quicktune->getMessage()));
1975 void Game::processItemSelection(u16 *new_playeritem)
1977 LocalPlayer *player = client->getEnv().getLocalPlayer();
1979 /* Item selection using mouse wheel
1981 *new_playeritem = player->getWieldIndex();
1983 s32 wheel = input->getMouseWheel();
1984 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
1985 player->hud_hotbar_itemcount - 1);
1989 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
1990 wasKeyDown(KeyType::HOTBAR_NEXT)) {
1994 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
1995 wasKeyDown(KeyType::HOTBAR_PREV)) {
2000 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2002 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2005 /* Item selection using hotbar slot keys
2007 for (u16 i = 0; i <= max_item; i++) {
2008 if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
2009 *new_playeritem = i;
2010 infostream << "Selected item: " << new_playeritem << std::endl;
2017 void Game::dropSelectedItem(bool single_item)
2019 IDropAction *a = new IDropAction();
2020 a->count = single_item ? 1 : 0;
2021 a->from_inv.setCurrentPlayer();
2022 a->from_list = "main";
2023 a->from_i = client->getEnv().getLocalPlayer()->getWieldIndex();
2024 client->inventoryAction(a);
2028 void Game::openInventory()
2031 * Don't permit to open inventory is CAO or player doesn't exists.
2032 * This prevent showing an empty inventory at player load
2035 LocalPlayer *player = client->getEnv().getLocalPlayer();
2036 if (!player || !player->getCAO())
2039 infostream << "the_game: " << "Launching inventory" << std::endl;
2041 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2043 InventoryLocation inventoryloc;
2044 inventoryloc.setCurrentPlayer();
2046 if (!client->modsLoaded()
2047 || !client->getScript()->on_inventory_open(fs_src->m_client->getInventory(inventoryloc))) {
2048 TextDest *txt_dst = new TextDestPlayerInventory(client);
2049 auto *&formspec = m_game_ui->updateFormspec("");
2050 GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
2051 txt_dst, client->getFormspecPrepend());
2053 formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2058 void Game::openConsole(float scale, const wchar_t *line)
2060 assert(scale > 0.0f && scale <= 1.0f);
2063 porting::showInputDialog(gettext("ok"), "", "", 2);
2064 m_android_chat_open = true;
2066 if (gui_chat_console->isOpenInhibited())
2068 gui_chat_console->openConsole(scale);
2070 gui_chat_console->setCloseOnEnter(true);
2071 gui_chat_console->replaceAndAddToHistory(line);
2077 void Game::handleAndroidChatInput()
2079 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2080 std::string text = porting::getInputDialogValue();
2081 client->typeChatMessage(utf8_to_wide(text));
2082 m_android_chat_open = false;
2088 void Game::toggleFreeMove()
2090 bool free_move = !g_settings->getBool("free_move");
2091 g_settings->set("free_move", bool_to_cstr(free_move));
2094 if (client->checkPrivilege("fly")) {
2095 m_game_ui->showTranslatedStatusText("Fly mode enabled");
2097 m_game_ui->showTranslatedStatusText("Fly mode enabled (note: no 'fly' privilege)");
2100 m_game_ui->showTranslatedStatusText("Fly mode disabled");
2104 void Game::toggleFreeMoveAlt()
2106 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2109 runData.reset_jump_timer = true;
2113 void Game::togglePitchMove()
2115 bool pitch_move = !g_settings->getBool("pitch_move");
2116 g_settings->set("pitch_move", bool_to_cstr(pitch_move));
2119 m_game_ui->showTranslatedStatusText("Pitch move mode enabled");
2121 m_game_ui->showTranslatedStatusText("Pitch move mode disabled");
2126 void Game::toggleFast()
2128 bool fast_move = !g_settings->getBool("fast_move");
2129 bool has_fast_privs = client->checkPrivilege("fast");
2130 g_settings->set("fast_move", bool_to_cstr(fast_move));
2133 if (has_fast_privs) {
2134 m_game_ui->showTranslatedStatusText("Fast mode enabled");
2136 m_game_ui->showTranslatedStatusText("Fast mode enabled (note: no 'fast' privilege)");
2139 m_game_ui->showTranslatedStatusText("Fast mode disabled");
2143 m_cache_hold_aux1 = fast_move && has_fast_privs;
2148 void Game::toggleNoClip()
2150 bool noclip = !g_settings->getBool("noclip");
2151 g_settings->set("noclip", bool_to_cstr(noclip));
2154 if (client->checkPrivilege("noclip")) {
2155 m_game_ui->showTranslatedStatusText("Noclip mode enabled");
2157 m_game_ui->showTranslatedStatusText("Noclip mode enabled (note: no 'noclip' privilege)");
2160 m_game_ui->showTranslatedStatusText("Noclip mode disabled");
2164 void Game::toggleCinematic()
2166 bool cinematic = !g_settings->getBool("cinematic");
2167 g_settings->set("cinematic", bool_to_cstr(cinematic));
2170 m_game_ui->showTranslatedStatusText("Cinematic mode enabled");
2172 m_game_ui->showTranslatedStatusText("Cinematic mode disabled");
2175 // Autoforward by toggling continuous forward.
2176 void Game::toggleAutoforward()
2178 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2179 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2181 if (autorun_enabled)
2182 m_game_ui->showTranslatedStatusText("Automatic forward enabled");
2184 m_game_ui->showTranslatedStatusText("Automatic forward disabled");
2187 void Game::toggleMinimap(bool shift_pressed)
2189 if (!mapper || !m_game_ui->m_flags.show_hud || !g_settings->getBool("enable_minimap"))
2192 if (shift_pressed) {
2193 mapper->toggleMinimapShape();
2197 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2199 MinimapMode mode = MINIMAP_MODE_OFF;
2200 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2201 mode = mapper->getMinimapMode();
2202 mode = (MinimapMode)((int)mode + 1);
2203 // If radar is disabled and in, or switching to, radar mode
2204 if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE) && mode > 3)
2205 mode = MINIMAP_MODE_OFF;
2208 m_game_ui->m_flags.show_minimap = true;
2210 case MINIMAP_MODE_SURFACEx1:
2211 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1");
2213 case MINIMAP_MODE_SURFACEx2:
2214 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2");
2216 case MINIMAP_MODE_SURFACEx4:
2217 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4");
2219 case MINIMAP_MODE_RADARx1:
2220 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1");
2222 case MINIMAP_MODE_RADARx2:
2223 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2");
2225 case MINIMAP_MODE_RADARx4:
2226 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4");
2229 mode = MINIMAP_MODE_OFF;
2230 m_game_ui->m_flags.show_minimap = false;
2231 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE)
2232 m_game_ui->showTranslatedStatusText("Minimap hidden");
2234 m_game_ui->showTranslatedStatusText("Minimap currently disabled by game or mod");
2237 mapper->setMinimapMode(mode);
2240 void Game::toggleFog()
2242 bool fog_enabled = g_settings->getBool("enable_fog");
2243 g_settings->setBool("enable_fog", !fog_enabled);
2245 m_game_ui->showTranslatedStatusText("Fog disabled");
2247 m_game_ui->showTranslatedStatusText("Fog enabled");
2251 void Game::toggleDebug()
2253 // Initial / 4x toggle: Chat only
2254 // 1x toggle: Debug text with chat
2255 // 2x toggle: Debug text with profiler graph
2256 // 3x toggle: Debug text and wireframe
2257 if (!m_game_ui->m_flags.show_debug) {
2258 m_game_ui->m_flags.show_debug = true;
2259 m_game_ui->m_flags.show_profiler_graph = false;
2260 draw_control->show_wireframe = false;
2261 m_game_ui->showTranslatedStatusText("Debug info shown");
2262 } else if (!m_game_ui->m_flags.show_profiler_graph && !draw_control->show_wireframe) {
2263 m_game_ui->m_flags.show_profiler_graph = true;
2264 m_game_ui->showTranslatedStatusText("Profiler graph shown");
2265 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2266 m_game_ui->m_flags.show_profiler_graph = false;
2267 draw_control->show_wireframe = true;
2268 m_game_ui->showTranslatedStatusText("Wireframe shown");
2270 m_game_ui->m_flags.show_debug = false;
2271 m_game_ui->m_flags.show_profiler_graph = false;
2272 draw_control->show_wireframe = false;
2273 if (client->checkPrivilege("debug")) {
2274 m_game_ui->showTranslatedStatusText("Debug info, profiler graph, and wireframe hidden");
2276 m_game_ui->showTranslatedStatusText("Debug info and profiler graph hidden");
2282 void Game::toggleUpdateCamera()
2284 m_flags.disable_camera_update = !m_flags.disable_camera_update;
2285 if (m_flags.disable_camera_update)
2286 m_game_ui->showTranslatedStatusText("Camera update disabled");
2288 m_game_ui->showTranslatedStatusText("Camera update enabled");
2292 void Game::increaseViewRange()
2294 s16 range = g_settings->getS16("viewing_range");
2295 s16 range_new = range + 10;
2299 if (range_new > 4000) {
2301 str = wgettext("Viewing range is at maximum: %d");
2302 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2304 m_game_ui->showStatusText(buf);
2307 str = wgettext("Viewing range changed to %d");
2308 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2310 m_game_ui->showStatusText(buf);
2312 g_settings->set("viewing_range", itos(range_new));
2316 void Game::decreaseViewRange()
2318 s16 range = g_settings->getS16("viewing_range");
2319 s16 range_new = range - 10;
2323 if (range_new < 20) {
2325 str = wgettext("Viewing range is at minimum: %d");
2326 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2328 m_game_ui->showStatusText(buf);
2330 str = wgettext("Viewing range changed to %d");
2331 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2333 m_game_ui->showStatusText(buf);
2335 g_settings->set("viewing_range", itos(range_new));
2339 void Game::toggleFullViewRange()
2341 draw_control->range_all = !draw_control->range_all;
2342 if (draw_control->range_all)
2343 m_game_ui->showTranslatedStatusText("Enabled unlimited viewing range");
2345 m_game_ui->showTranslatedStatusText("Disabled unlimited viewing range");
2349 void Game::checkZoomEnabled()
2351 LocalPlayer *player = client->getEnv().getLocalPlayer();
2352 if (player->getZoomFOV() < 0.001f || player->getFov().fov > 0.0f)
2353 m_game_ui->showTranslatedStatusText("Zoom currently disabled by game or mod");
2357 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2359 if ((device->isWindowActive() && device->isWindowFocused()
2360 && !isMenuActive()) || random_input) {
2363 if (!random_input) {
2364 // Mac OSX gets upset if this is set every frame
2365 if (device->getCursorControl()->isVisible())
2366 device->getCursorControl()->setVisible(false);
2370 if (m_first_loop_after_window_activation) {
2371 m_first_loop_after_window_activation = false;
2373 input->setMousePos(driver->getScreenSize().Width / 2,
2374 driver->getScreenSize().Height / 2);
2376 updateCameraOrientation(cam, dtime);
2382 // Mac OSX gets upset if this is set every frame
2383 if (!device->getCursorControl()->isVisible())
2384 device->getCursorControl()->setVisible(true);
2387 m_first_loop_after_window_activation = true;
2392 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2394 #ifdef HAVE_TOUCHSCREENGUI
2395 if (g_touchscreengui) {
2396 cam->camera_yaw += g_touchscreengui->getYawChange();
2397 cam->camera_pitch = g_touchscreengui->getPitch();
2400 v2s32 center(driver->getScreenSize().Width / 2, driver->getScreenSize().Height / 2);
2401 v2s32 dist = input->getMousePos() - center;
2403 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2407 cam->camera_yaw -= dist.X * m_cache_mouse_sensitivity;
2408 cam->camera_pitch += dist.Y * m_cache_mouse_sensitivity;
2410 if (dist.X != 0 || dist.Y != 0)
2411 input->setMousePos(center.X, center.Y);
2412 #ifdef HAVE_TOUCHSCREENGUI
2416 if (m_cache_enable_joysticks) {
2417 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
2418 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
2419 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
2422 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2426 void Game::updatePlayerControl(const CameraOrientation &cam)
2428 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2430 // DO NOT use the isKeyDown method for the forward, backward, left, right
2431 // buttons, as the code that uses the controls needs to be able to
2432 // distinguish between the two in order to know when to use joysticks.
2434 PlayerControl control(
2435 input->isKeyDown(KeyType::FORWARD),
2436 input->isKeyDown(KeyType::BACKWARD),
2437 input->isKeyDown(KeyType::LEFT),
2438 input->isKeyDown(KeyType::RIGHT),
2439 isKeyDown(KeyType::JUMP),
2440 isKeyDown(KeyType::SPECIAL1),
2441 isKeyDown(KeyType::SNEAK),
2442 isKeyDown(KeyType::ZOOM),
2443 input->getLeftState(),
2444 input->getRightState(),
2447 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
2448 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
2452 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
2453 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
2454 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
2455 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
2456 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
2457 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
2458 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
2459 ( (u32)(input->getLeftState() & 0x1) << 7) |
2460 ( (u32)(input->getRightState() & 0x1) << 8
2464 /* For Android, simulate holding down AUX1 (fast move) if the user has
2465 * the fast_move setting toggled on. If there is an aux1 key defined for
2466 * Android then its meaning is inverted (i.e. holding aux1 means walk and
2469 if (m_cache_hold_aux1) {
2470 control.aux1 = control.aux1 ^ true;
2471 keypress_bits ^= ((u32)(1U << 5));
2475 LocalPlayer *player = client->getEnv().getLocalPlayer();
2477 // autojump if set: simulate "jump" key
2478 if (player->getAutojump()) {
2479 control.jump = true;
2480 keypress_bits |= 1U << 4;
2483 // autoforward if set: simulate "up" key
2484 if (player->getPlayerSettings().continuous_forward &&
2485 client->activeObjectsReceived() && !player->isDead()) {
2487 keypress_bits |= 1U << 0;
2490 client->setPlayerControl(control);
2491 player->keyPressed = keypress_bits;
2497 inline void Game::step(f32 *dtime)
2499 bool can_be_and_is_paused =
2500 (simple_singleplayer_mode && g_menumgr.pausesGame());
2502 if (can_be_and_is_paused) { // This is for a singleplayer server
2503 *dtime = 0; // No time passes
2506 server->step(*dtime);
2508 client->step(*dtime);
2512 const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = {
2513 {&Game::handleClientEvent_None},
2514 {&Game::handleClientEvent_PlayerDamage},
2515 {&Game::handleClientEvent_PlayerForceMove},
2516 {&Game::handleClientEvent_Deathscreen},
2517 {&Game::handleClientEvent_ShowFormSpec},
2518 {&Game::handleClientEvent_ShowLocalFormSpec},
2519 {&Game::handleClientEvent_HandleParticleEvent},
2520 {&Game::handleClientEvent_HandleParticleEvent},
2521 {&Game::handleClientEvent_HandleParticleEvent},
2522 {&Game::handleClientEvent_HudAdd},
2523 {&Game::handleClientEvent_HudRemove},
2524 {&Game::handleClientEvent_HudChange},
2525 {&Game::handleClientEvent_SetSky},
2526 {&Game::handleClientEvent_OverrideDayNigthRatio},
2527 {&Game::handleClientEvent_CloudParams},
2530 void Game::handleClientEvent_None(ClientEvent *event, CameraOrientation *cam)
2532 FATAL_ERROR("ClientEvent type None received");
2535 void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam)
2537 if (client->modsLoaded())
2538 client->getScript()->on_damage_taken(event->player_damage.amount);
2540 // Damage flash and hurt tilt are not used at death
2541 if (client->getHP() > 0) {
2542 runData.damage_flash += 95.0f + 3.2f * event->player_damage.amount;
2543 runData.damage_flash = MYMIN(runData.damage_flash, 127.0f);
2545 LocalPlayer *player = client->getEnv().getLocalPlayer();
2547 player->hurt_tilt_timer = 1.5f;
2548 player->hurt_tilt_strength =
2549 rangelim(event->player_damage.amount / 4.0f, 1.0f, 4.0f);
2552 // Play damage sound
2553 client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::PLAYER_DAMAGE));
2556 void Game::handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam)
2558 cam->camera_yaw = event->player_force_move.yaw;
2559 cam->camera_pitch = event->player_force_move.pitch;
2562 void Game::handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam)
2564 // If client scripting is enabled, deathscreen is handled by CSM code in
2565 // builtin/client/init.lua
2566 if (client->modsLoaded())
2567 client->getScript()->on_death();
2569 showDeathFormspec();
2571 /* Handle visualization */
2572 LocalPlayer *player = client->getEnv().getLocalPlayer();
2573 runData.damage_flash = 0;
2574 player->hurt_tilt_timer = 0;
2575 player->hurt_tilt_strength = 0;
2578 void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam)
2580 if (event->show_formspec.formspec->empty()) {
2581 auto formspec = m_game_ui->getFormspecGUI();
2582 if (formspec && (event->show_formspec.formname->empty()
2583 || *(event->show_formspec.formname) == m_game_ui->getFormspecName())) {
2584 formspec->quitMenu();
2587 FormspecFormSource *fs_src =
2588 new FormspecFormSource(*(event->show_formspec.formspec));
2589 TextDestPlayerInventory *txt_dst =
2590 new TextDestPlayerInventory(client, *(event->show_formspec.formname));
2592 auto *&formspec = m_game_ui->updateFormspec(*(event->show_formspec.formname));
2593 GUIFormSpecMenu::create(formspec, client, &input->joystick,
2594 fs_src, txt_dst, client->getFormspecPrepend());
2597 delete event->show_formspec.formspec;
2598 delete event->show_formspec.formname;
2601 void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam)
2603 FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec);
2604 LocalFormspecHandler *txt_dst =
2605 new LocalFormspecHandler(*event->show_formspec.formname, client);
2606 GUIFormSpecMenu::create(m_game_ui->getFormspecGUI(), client, &input->joystick,
2607 fs_src, txt_dst, client->getFormspecPrepend());
2609 delete event->show_formspec.formspec;
2610 delete event->show_formspec.formname;
2613 void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event,
2614 CameraOrientation *cam)
2616 LocalPlayer *player = client->getEnv().getLocalPlayer();
2617 client->getParticleManager()->handleParticleEvent(event, client, player);
2620 void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
2622 LocalPlayer *player = client->getEnv().getLocalPlayer();
2623 auto &hud_server_to_client = client->getHUDTranslationMap();
2625 u32 server_id = event->hudadd.server_id;
2626 // ignore if we already have a HUD with that ID
2627 auto i = hud_server_to_client.find(server_id);
2628 if (i != hud_server_to_client.end()) {
2629 delete event->hudadd.pos;
2630 delete event->hudadd.name;
2631 delete event->hudadd.scale;
2632 delete event->hudadd.text;
2633 delete event->hudadd.align;
2634 delete event->hudadd.offset;
2635 delete event->hudadd.world_pos;
2636 delete event->hudadd.size;
2640 HudElement *e = new HudElement;
2641 e->type = (HudElementType)event->hudadd.type;
2642 e->pos = *event->hudadd.pos;
2643 e->name = *event->hudadd.name;
2644 e->scale = *event->hudadd.scale;
2645 e->text = *event->hudadd.text;
2646 e->number = event->hudadd.number;
2647 e->item = event->hudadd.item;
2648 e->dir = event->hudadd.dir;
2649 e->align = *event->hudadd.align;
2650 e->offset = *event->hudadd.offset;
2651 e->world_pos = *event->hudadd.world_pos;
2652 e->size = *event->hudadd.size;
2653 hud_server_to_client[server_id] = player->addHud(e);
2655 delete event->hudadd.pos;
2656 delete event->hudadd.name;
2657 delete event->hudadd.scale;
2658 delete event->hudadd.text;
2659 delete event->hudadd.align;
2660 delete event->hudadd.offset;
2661 delete event->hudadd.world_pos;
2662 delete event->hudadd.size;
2665 void Game::handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam)
2667 LocalPlayer *player = client->getEnv().getLocalPlayer();
2668 HudElement *e = player->removeHud(event->hudrm.id);
2672 void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam)
2674 LocalPlayer *player = client->getEnv().getLocalPlayer();
2676 u32 id = event->hudchange.id;
2677 HudElement *e = player->getHud(id);
2680 delete event->hudchange.v3fdata;
2681 delete event->hudchange.v2fdata;
2682 delete event->hudchange.sdata;
2683 delete event->hudchange.v2s32data;
2687 switch (event->hudchange.stat) {
2689 e->pos = *event->hudchange.v2fdata;
2693 e->name = *event->hudchange.sdata;
2696 case HUD_STAT_SCALE:
2697 e->scale = *event->hudchange.v2fdata;
2701 e->text = *event->hudchange.sdata;
2704 case HUD_STAT_NUMBER:
2705 e->number = event->hudchange.data;
2709 e->item = event->hudchange.data;
2713 e->dir = event->hudchange.data;
2716 case HUD_STAT_ALIGN:
2717 e->align = *event->hudchange.v2fdata;
2720 case HUD_STAT_OFFSET:
2721 e->offset = *event->hudchange.v2fdata;
2724 case HUD_STAT_WORLD_POS:
2725 e->world_pos = *event->hudchange.v3fdata;
2729 e->size = *event->hudchange.v2s32data;
2733 delete event->hudchange.v3fdata;
2734 delete event->hudchange.v2fdata;
2735 delete event->hudchange.sdata;
2736 delete event->hudchange.v2s32data;
2739 void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
2741 sky->setVisible(false);
2742 // Whether clouds are visible in front of a custom skybox
2743 sky->setCloudsEnabled(event->set_sky.clouds);
2750 // Handle according to type
2751 if (*event->set_sky.type == "regular") {
2752 sky->setVisible(true);
2753 sky->setCloudsEnabled(true);
2754 } else if (*event->set_sky.type == "skybox" &&
2755 event->set_sky.params->size() == 6) {
2756 sky->setFallbackBgColor(*event->set_sky.bgcolor);
2757 skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
2758 texture_src->getTextureForMesh((*event->set_sky.params)[0]),
2759 texture_src->getTextureForMesh((*event->set_sky.params)[1]),
2760 texture_src->getTextureForMesh((*event->set_sky.params)[2]),
2761 texture_src->getTextureForMesh((*event->set_sky.params)[3]),
2762 texture_src->getTextureForMesh((*event->set_sky.params)[4]),
2763 texture_src->getTextureForMesh((*event->set_sky.params)[5]));
2765 // Handle everything else as plain color
2767 if (*event->set_sky.type != "plain")
2768 infostream << "Unknown sky type: "
2769 << (*event->set_sky.type) << std::endl;
2771 sky->setFallbackBgColor(*event->set_sky.bgcolor);
2774 delete event->set_sky.bgcolor;
2775 delete event->set_sky.type;
2776 delete event->set_sky.params;
2779 void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
2780 CameraOrientation *cam)
2782 client->getEnv().setDayNightRatioOverride(
2783 event->override_day_night_ratio.do_override,
2784 event->override_day_night_ratio.ratio_f * 1000.0f);
2787 void Game::handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam)
2792 clouds->setDensity(event->cloud_params.density);
2793 clouds->setColorBright(video::SColor(event->cloud_params.color_bright));
2794 clouds->setColorAmbient(video::SColor(event->cloud_params.color_ambient));
2795 clouds->setHeight(event->cloud_params.height);
2796 clouds->setThickness(event->cloud_params.thickness);
2797 clouds->setSpeed(v2f(event->cloud_params.speed_x, event->cloud_params.speed_y));
2800 void Game::processClientEvents(CameraOrientation *cam)
2802 while (client->hasClientEvents()) {
2803 std::unique_ptr<ClientEvent> event(client->getClientEvent());
2804 FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, "Invalid clientevent type");
2805 const ClientEventHandler& evHandler = clientEventHandler[event->type];
2806 (this->*evHandler.handler)(event.get(), cam);
2810 void Game::updateChat(f32 dtime, const v2u32 &screensize)
2812 // Add chat log output for errors to be shown in chat
2813 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
2815 // Get new messages from error log buffer
2816 while (!chat_log_error_buf.empty()) {
2817 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
2818 if (!g_settings->getBool("disable_escape_sequences")) {
2819 error_message.insert(0, L"\x1b(c@red)");
2820 error_message.append(L"\x1b(c@white)");
2822 chat_backend->addMessage(L"", error_message);
2825 // Get new messages from client
2826 std::wstring message;
2827 while (client->getChatMessage(message)) {
2828 chat_backend->addUnparsedMessage(message);
2831 // Remove old messages
2832 chat_backend->step(dtime);
2834 // Display all messages in a static text element
2835 m_game_ui->setChatText(chat_backend->getRecentChat(),
2836 chat_backend->getRecentBuffer().getLineCount());
2839 void Game::updateCamera(u32 busy_time, f32 dtime)
2841 LocalPlayer *player = client->getEnv().getLocalPlayer();
2844 For interaction purposes, get info about the held item
2846 - Is it a usable item?
2847 - Can it point to liquids?
2849 ItemStack playeritem;
2851 ItemStack selected, hand;
2852 playeritem = player->getWieldedItem(&selected, &hand);
2855 ToolCapabilities playeritem_toolcap =
2856 playeritem.getToolCapabilities(itemdef_manager);
2858 v3s16 old_camera_offset = camera->getOffset();
2860 if (wasKeyDown(KeyType::CAMERA_MODE)) {
2861 GenericCAO *playercao = player->getCAO();
2863 // If playercao not loaded, don't change camera
2867 camera->toggleCameraMode();
2869 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2870 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2873 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2874 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
2876 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2877 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio);
2878 camera->step(dtime);
2880 v3f camera_position = camera->getPosition();
2881 v3f camera_direction = camera->getDirection();
2882 f32 camera_fov = camera->getFovMax();
2883 v3s16 camera_offset = camera->getOffset();
2885 m_camera_offset_changed = (camera_offset != old_camera_offset);
2887 if (!m_flags.disable_camera_update) {
2888 client->getEnv().getClientMap().updateCamera(camera_position,
2889 camera_direction, camera_fov, camera_offset);
2891 if (m_camera_offset_changed) {
2892 client->updateCameraOffset(camera_offset);
2893 client->getEnv().updateCameraOffset(camera_offset);
2896 clouds->updateCameraOffset(camera_offset);
2902 void Game::updateSound(f32 dtime)
2904 // Update sound listener
2905 v3s16 camera_offset = camera->getOffset();
2906 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
2907 v3f(0, 0, 0), // velocity
2908 camera->getDirection(),
2909 camera->getCameraNode()->getUpVector());
2911 bool mute_sound = g_settings->getBool("mute_sound");
2913 sound->setListenerGain(0.0f);
2915 // Check if volume is in the proper range, else fix it.
2916 float old_volume = g_settings->getFloat("sound_volume");
2917 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
2918 sound->setListenerGain(new_volume);
2920 if (old_volume != new_volume) {
2921 g_settings->setFloat("sound_volume", new_volume);
2925 LocalPlayer *player = client->getEnv().getLocalPlayer();
2927 // Tell the sound maker whether to make footstep sounds
2928 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
2930 // Update sound maker
2931 if (player->makes_footstep_sound)
2932 soundmaker->step(dtime);
2934 ClientMap &map = client->getEnv().getClientMap();
2935 MapNode n = map.getNode(player->getFootstepNodePos());
2936 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
2940 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
2942 LocalPlayer *player = client->getEnv().getLocalPlayer();
2944 v3f player_position = player->getPosition();
2945 v3f player_eye_position = player->getEyePosition();
2946 v3f camera_position = camera->getPosition();
2947 v3f camera_direction = camera->getDirection();
2948 v3s16 camera_offset = camera->getOffset();
2950 if (camera->getCameraMode() == CAMERA_MODE_FIRST)
2951 player_eye_position += player->eye_offset_first;
2953 player_eye_position += player->eye_offset_third;
2956 Calculate what block is the crosshair pointing to
2959 ItemStack selected_item, hand_item;
2960 const ItemStack &tool_item = player->getWieldedItem(&selected_item, &hand_item);
2962 const ItemDefinition &selected_def = selected_item.getDefinition(itemdef_manager);
2963 f32 d = getToolRange(selected_def, hand_item.getDefinition(itemdef_manager));
2965 core::line3d<f32> shootline;
2967 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
2968 shootline = core::line3d<f32>(player_eye_position,
2969 player_eye_position + camera_direction * BS * d);
2971 // prevent player pointing anything in front-view
2972 shootline = core::line3d<f32>(camera_position, camera_position);
2975 #ifdef HAVE_TOUCHSCREENGUI
2977 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
2978 shootline = g_touchscreengui->getShootline();
2979 // Scale shootline to the acual distance the player can reach
2980 shootline.end = shootline.start
2981 + shootline.getVector().normalize() * BS * d;
2982 shootline.start += intToFloat(camera_offset, BS);
2983 shootline.end += intToFloat(camera_offset, BS);
2988 PointedThing pointed = updatePointedThing(shootline,
2989 selected_def.liquids_pointable,
2990 !runData.ldown_for_dig,
2993 if (pointed != runData.pointed_old) {
2994 infostream << "Pointing at " << pointed.dump() << std::endl;
2995 hud->updateSelectionMesh(camera_offset);
2998 if (runData.digging_blocked && !input->getLeftState()) {
2999 // allow digging again if button is not pressed
3000 runData.digging_blocked = false;
3005 - releasing left mouse button
3006 - pointing away from node
3008 if (runData.digging) {
3009 if (input->getLeftReleased()) {
3010 infostream << "Left button released"
3011 << " (stopped digging)" << std::endl;
3012 runData.digging = false;
3013 } else if (pointed != runData.pointed_old) {
3014 if (pointed.type == POINTEDTHING_NODE
3015 && runData.pointed_old.type == POINTEDTHING_NODE
3016 && pointed.node_undersurface
3017 == runData.pointed_old.node_undersurface) {
3018 // Still pointing to the same node, but a different face.
3021 infostream << "Pointing away from node"
3022 << " (stopped digging)" << std::endl;
3023 runData.digging = false;
3024 hud->updateSelectionMesh(camera_offset);
3028 if (!runData.digging) {
3029 client->interact(INTERACT_STOP_DIGGING, runData.pointed_old);
3030 client->setCrack(-1, v3s16(0, 0, 0));
3031 runData.dig_time = 0.0;
3033 } else if (runData.dig_instantly && input->getLeftReleased()) {
3034 // Remove e.g. torches faster when clicking instead of holding LMB
3035 runData.nodig_delay_timer = 0;
3036 runData.dig_instantly = false;
3039 if (!runData.digging && runData.ldown_for_dig && !input->getLeftState()) {
3040 runData.ldown_for_dig = false;
3043 runData.left_punch = false;
3045 soundmaker->m_player_leftpunch_sound.name = "";
3047 // Prepare for repeating, unless we're not supposed to
3048 if (input->getRightState() && !g_settings->getBool("safe_dig_and_place"))
3049 runData.repeat_rightclick_timer += dtime;
3051 runData.repeat_rightclick_timer = 0;
3053 if (selected_def.usable && input->getLeftState()) {
3054 if (input->getLeftClicked() && (!client->modsLoaded()
3055 || !client->getScript()->on_item_use(selected_item, pointed)))
3056 client->interact(INTERACT_USE, pointed);
3057 } else if (pointed.type == POINTEDTHING_NODE) {
3058 handlePointingAtNode(pointed, selected_item, hand_item, dtime);
3059 } else if (pointed.type == POINTEDTHING_OBJECT) {
3060 handlePointingAtObject(pointed, tool_item, player_position, show_debug);
3061 } else if (input->getLeftState()) {
3062 // When button is held down in air, show continuous animation
3063 runData.left_punch = true;
3064 // Run callback even though item is not usable
3065 if (input->getLeftClicked() && client->modsLoaded())
3066 client->getScript()->on_item_use(selected_item, pointed);
3067 } else if (input->getRightClicked()) {
3068 handlePointingAtNothing(selected_item);
3071 runData.pointed_old = pointed;
3073 if (runData.left_punch || input->getLeftClicked())
3074 camera->setDigging(0); // left click animation
3076 input->resetLeftClicked();
3077 input->resetRightClicked();
3079 input->resetLeftReleased();
3080 input->resetRightReleased();
3084 PointedThing Game::updatePointedThing(
3085 const core::line3d<f32> &shootline,
3086 bool liquids_pointable,
3087 bool look_for_object,
3088 const v3s16 &camera_offset)
3090 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3091 selectionboxes->clear();
3092 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3093 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3094 "show_entity_selectionbox");
3096 ClientEnvironment &env = client->getEnv();
3097 ClientMap &map = env.getClientMap();
3098 const NodeDefManager *nodedef = map.getNodeDefManager();
3100 runData.selected_object = NULL;
3102 RaycastState s(shootline, look_for_object, liquids_pointable);
3103 PointedThing result;
3104 env.continueRaycast(&s, &result);
3105 if (result.type == POINTEDTHING_OBJECT) {
3106 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3107 aabb3f selection_box;
3108 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3109 runData.selected_object->getSelectionBox(&selection_box)) {
3110 v3f pos = runData.selected_object->getPosition();
3111 selectionboxes->push_back(aabb3f(selection_box));
3112 hud->setSelectionPos(pos, camera_offset);
3114 } else if (result.type == POINTEDTHING_NODE) {
3115 // Update selection boxes
3116 MapNode n = map.getNode(result.node_undersurface);
3117 std::vector<aabb3f> boxes;
3118 n.getSelectionBoxes(nodedef, &boxes,
3119 n.getNeighbors(result.node_undersurface, &map));
3122 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3123 i != boxes.end(); ++i) {
3125 box.MinEdge -= v3f(d, d, d);
3126 box.MaxEdge += v3f(d, d, d);
3127 selectionboxes->push_back(box);
3129 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3131 hud->setSelectedFaceNormal(v3f(
3132 result.intersection_normal.X,
3133 result.intersection_normal.Y,
3134 result.intersection_normal.Z));
3137 // Update selection mesh light level and vertex colors
3138 if (!selectionboxes->empty()) {
3139 v3f pf = hud->getSelectionPos();
3140 v3s16 p = floatToInt(pf, BS);
3142 // Get selection mesh light level
3143 MapNode n = map.getNode(p);
3144 u16 node_light = getInteriorLight(n, -1, nodedef);
3145 u16 light_level = node_light;
3147 for (const v3s16 &dir : g_6dirs) {
3148 n = map.getNode(p + dir);
3149 node_light = getInteriorLight(n, -1, nodedef);
3150 if (node_light > light_level)
3151 light_level = node_light;
3154 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3156 final_color_blend(&c, light_level, daynight_ratio);
3158 // Modify final color a bit with time
3159 u32 timer = porting::getTimeMs() % 5000;
3160 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3161 float sin_r = 0.08f * std::sin(timerf);
3162 float sin_g = 0.08f * std::sin(timerf + irr::core::PI * 0.5f);
3163 float sin_b = 0.08f * std::sin(timerf + irr::core::PI);
3164 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3165 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3166 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3168 // Set mesh final color
3169 hud->setSelectionMeshColor(c);
3175 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3177 infostream << "Right Clicked in Air" << std::endl;
3178 PointedThing fauxPointed;
3179 fauxPointed.type = POINTEDTHING_NOTHING;
3180 client->interact(INTERACT_ACTIVATE, fauxPointed);
3184 void Game::handlePointingAtNode(const PointedThing &pointed,
3185 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
3187 v3s16 nodepos = pointed.node_undersurface;
3188 v3s16 neighbourpos = pointed.node_abovesurface;
3191 Check information text of node
3194 ClientMap &map = client->getEnv().getClientMap();
3196 if (runData.nodig_delay_timer <= 0.0 && input->getLeftState()
3197 && !runData.digging_blocked
3198 && client->checkPrivilege("interact")) {
3199 handleDigging(pointed, nodepos, selected_item, hand_item, dtime);
3202 // This should be done after digging handling
3203 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3206 m_game_ui->setInfoText(unescape_translate(utf8_to_wide(
3207 meta->getString("infotext"))));
3209 MapNode n = map.getNode(nodepos);
3211 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3212 m_game_ui->setInfoText(L"Unknown node: " +
3213 utf8_to_wide(nodedef_manager->get(n).name));
3217 if ((input->getRightClicked() ||
3218 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3219 client->checkPrivilege("interact")) {
3220 runData.repeat_rightclick_timer = 0;
3221 infostream << "Ground right-clicked" << std::endl;
3223 camera->setDigging(1); // right click animation (always shown for feedback)
3225 soundmaker->m_player_rightpunch_sound = SimpleSoundSpec();
3227 // If the wielded item has node placement prediction,
3229 // And also set the sound and send the interact
3230 // But first check for meta formspec and rightclickable
3231 auto &def = selected_item.getDefinition(itemdef_manager);
3232 bool placed = nodePlacement(def, selected_item, nodepos, neighbourpos,
3235 if (placed && client->modsLoaded())
3236 client->getScript()->on_placenode(pointed, def);
3240 bool Game::nodePlacement(const ItemDefinition &selected_def,
3241 const ItemStack &selected_item, const v3s16 &nodepos, const v3s16 &neighbourpos,
3242 const PointedThing &pointed, const NodeMetadata *meta)
3244 std::string prediction = selected_def.node_placement_prediction;
3245 const NodeDefManager *nodedef = client->ndef();
3246 ClientMap &map = client->getEnv().getClientMap();
3248 bool is_valid_position;
3250 node = map.getNode(nodepos, &is_valid_position);
3251 if (!is_valid_position) {
3252 soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
3257 if (meta && !meta->getString("formspec").empty() && !random_input
3258 && !isKeyDown(KeyType::SNEAK)) {
3259 // on_rightclick callbacks are called anyway
3260 if (nodedef_manager->get(map.getNode(nodepos)).rightclickable)
3261 client->interact(INTERACT_PLACE, pointed);
3263 infostream << "Launching custom inventory view" << std::endl;
3265 InventoryLocation inventoryloc;
3266 inventoryloc.setNodeMeta(nodepos);
3268 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3269 &client->getEnv().getClientMap(), nodepos);
3270 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3272 auto *&formspec = m_game_ui->updateFormspec("");
3273 GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
3274 txt_dst, client->getFormspecPrepend());
3276 formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3280 // on_rightclick callback
3281 if (prediction.empty() || (nodedef->get(node).rightclickable &&
3282 !isKeyDown(KeyType::SNEAK))) {
3284 client->interact(INTERACT_PLACE, pointed);
3288 verbosestream << "Node placement prediction for "
3289 << selected_def.name << " is "
3290 << prediction << std::endl;
3291 v3s16 p = neighbourpos;
3293 // Place inside node itself if buildable_to
3294 MapNode n_under = map.getNode(nodepos, &is_valid_position);
3295 if (is_valid_position) {
3296 if (nodedef->get(n_under).buildable_to) {
3299 node = map.getNode(p, &is_valid_position);
3300 if (is_valid_position && !nodedef->get(node).buildable_to) {
3302 client->interact(INTERACT_PLACE, pointed);
3308 // Find id of predicted node
3310 bool found = nodedef->getId(prediction, id);
3313 errorstream << "Node placement prediction failed for "
3314 << selected_def.name << " (places "
3316 << ") - Name not known" << std::endl;
3317 // Handle this as if prediction was empty
3319 client->interact(INTERACT_PLACE, pointed);
3323 const ContentFeatures &predicted_f = nodedef->get(id);
3325 // Predict param2 for facedir and wallmounted nodes
3328 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3329 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
3330 v3s16 dir = nodepos - neighbourpos;
3332 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
3333 param2 = dir.Y < 0 ? 1 : 0;
3334 } else if (abs(dir.X) > abs(dir.Z)) {
3335 param2 = dir.X < 0 ? 3 : 2;
3337 param2 = dir.Z < 0 ? 5 : 4;
3341 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
3342 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
3343 v3s16 dir = nodepos - floatToInt(client->getEnv().getLocalPlayer()->getPosition(), BS);
3345 if (abs(dir.X) > abs(dir.Z)) {
3346 param2 = dir.X < 0 ? 3 : 1;
3348 param2 = dir.Z < 0 ? 2 : 0;
3352 assert(param2 <= 5);
3354 //Check attachment if node is in group attached_node
3355 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
3356 static v3s16 wallmounted_dirs[8] = {
3366 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3367 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
3368 pp = p + wallmounted_dirs[param2];
3370 pp = p + v3s16(0, -1, 0);
3372 if (!nodedef->get(map.getNode(pp)).walkable) {
3374 client->interact(INTERACT_PLACE, pointed);
3380 if ((predicted_f.param_type_2 == CPT2_COLOR
3381 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
3382 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
3383 const std::string &indexstr = selected_item.metadata.getString(
3384 "palette_index", 0);
3385 if (!indexstr.empty()) {
3386 s32 index = mystoi(indexstr);
3387 if (predicted_f.param_type_2 == CPT2_COLOR) {
3389 } else if (predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
3390 // param2 = pure palette index + other
3391 param2 = (index & 0xf8) | (param2 & 0x07);
3392 } else if (predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
3393 // param2 = pure palette index + other
3394 param2 = (index & 0xe0) | (param2 & 0x1f);
3399 // Add node to client map
3400 MapNode n(id, 0, param2);
3403 LocalPlayer *player = client->getEnv().getLocalPlayer();
3405 // Dont place node when player would be inside new node
3406 // NOTE: This is to be eventually implemented by a mod as client-side Lua
3407 if (!nodedef->get(n).walkable ||
3408 g_settings->getBool("enable_build_where_you_stand") ||
3409 (client->checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
3410 (nodedef->get(n).walkable &&
3411 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
3412 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
3413 // This triggers the required mesh update too
3414 client->addNode(p, n);
3416 client->interact(INTERACT_PLACE, pointed);
3417 // A node is predicted, also play a sound
3418 soundmaker->m_player_rightpunch_sound = selected_def.sound_place;
3421 soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
3424 } catch (InvalidPositionException &e) {
3425 errorstream << "Node placement prediction failed for "
3426 << selected_def.name << " (places "
3428 << ") - Position not loaded" << std::endl;
3429 soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
3434 void Game::handlePointingAtObject(const PointedThing &pointed,
3435 const ItemStack &tool_item, const v3f &player_position, bool show_debug)
3437 std::wstring infotext = unescape_translate(
3438 utf8_to_wide(runData.selected_object->infoText()));
3441 if (!infotext.empty()) {
3444 infotext += utf8_to_wide(runData.selected_object->debugInfoText());
3447 m_game_ui->setInfoText(infotext);
3449 if (input->getLeftState()) {
3450 bool do_punch = false;
3451 bool do_punch_damage = false;
3453 if (runData.object_hit_delay_timer <= 0.0) {
3455 do_punch_damage = true;
3456 runData.object_hit_delay_timer = object_hit_delay;
3459 if (input->getLeftClicked())
3463 infostream << "Left-clicked object" << std::endl;
3464 runData.left_punch = true;
3467 if (do_punch_damage) {
3468 // Report direct punch
3469 v3f objpos = runData.selected_object->getPosition();
3470 v3f dir = (objpos - player_position).normalize();
3472 bool disable_send = runData.selected_object->directReportPunch(
3473 dir, &tool_item, runData.time_from_last_punch);
3474 runData.time_from_last_punch = 0;
3477 client->interact(INTERACT_START_DIGGING, pointed);
3479 } else if (input->getRightClicked()) {
3480 infostream << "Right-clicked object" << std::endl;
3481 client->interact(INTERACT_PLACE, pointed); // place
3486 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3487 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
3489 // See also: serverpackethandle.cpp, action == 2
3490 LocalPlayer *player = client->getEnv().getLocalPlayer();
3491 ClientMap &map = client->getEnv().getClientMap();
3492 MapNode n = client->getEnv().getClientMap().getNode(nodepos);
3494 // NOTE: Similar piece of code exists on the server side for
3496 // Get digging parameters
3497 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3498 &selected_item.getToolCapabilities(itemdef_manager));
3500 // If can't dig, try hand
3501 if (!params.diggable) {
3502 params = getDigParams(nodedef_manager->get(n).groups,
3503 &hand_item.getToolCapabilities(itemdef_manager));
3506 if (!params.diggable) {
3507 // I guess nobody will wait for this long
3508 runData.dig_time_complete = 10000000.0;
3510 runData.dig_time_complete = params.time;
3512 if (m_cache_enable_particles) {
3513 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3514 client->getParticleManager()->addNodeParticle(client,
3515 player, nodepos, n, features);
3519 if (!runData.digging) {
3520 infostream << "Started digging" << std::endl;
3521 runData.dig_instantly = runData.dig_time_complete == 0;
3522 if (client->modsLoaded() && client->getScript()->on_punchnode(nodepos, n))
3524 client->interact(INTERACT_START_DIGGING, pointed);
3525 runData.digging = true;
3526 runData.ldown_for_dig = true;
3529 if (!runData.dig_instantly) {
3530 runData.dig_index = (float)crack_animation_length
3532 / runData.dig_time_complete;
3534 // This is for e.g. torches
3535 runData.dig_index = crack_animation_length;
3538 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3540 if (sound_dig.exists() && params.diggable) {
3541 if (sound_dig.name == "__group") {
3542 if (!params.main_group.empty()) {
3543 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3544 soundmaker->m_player_leftpunch_sound.name =
3545 std::string("default_dig_") +
3549 soundmaker->m_player_leftpunch_sound = sound_dig;
3553 // Don't show cracks if not diggable
3554 if (runData.dig_time_complete >= 100000.0) {
3555 } else if (runData.dig_index < crack_animation_length) {
3556 //TimeTaker timer("client.setTempMod");
3557 //infostream<<"dig_index="<<dig_index<<std::endl;
3558 client->setCrack(runData.dig_index, nodepos);
3560 infostream << "Digging completed" << std::endl;
3561 client->setCrack(-1, v3s16(0, 0, 0));
3563 runData.dig_time = 0;
3564 runData.digging = false;
3565 // we successfully dug, now block it from repeating if we want to be safe
3566 if (g_settings->getBool("safe_dig_and_place"))
3567 runData.digging_blocked = true;
3569 runData.nodig_delay_timer =
3570 runData.dig_time_complete / (float)crack_animation_length;
3572 // We don't want a corresponding delay to very time consuming nodes
3573 // and nodes without digging time (e.g. torches) get a fixed delay.
3574 if (runData.nodig_delay_timer > 0.3)
3575 runData.nodig_delay_timer = 0.3;
3576 else if (runData.dig_instantly)
3577 runData.nodig_delay_timer = 0.15;
3579 bool is_valid_position;
3580 MapNode wasnode = map.getNode(nodepos, &is_valid_position);
3581 if (is_valid_position) {
3582 if (client->modsLoaded() &&
3583 client->getScript()->on_dignode(nodepos, wasnode)) {
3587 const ContentFeatures &f = client->ndef()->get(wasnode);
3588 if (f.node_dig_prediction == "air") {
3589 client->removeNode(nodepos);
3590 } else if (!f.node_dig_prediction.empty()) {
3592 bool found = client->ndef()->getId(f.node_dig_prediction, id);
3594 client->addNode(nodepos, id, true);
3596 // implicit else: no prediction
3599 client->interact(INTERACT_DIGGING_COMPLETED, pointed);
3601 if (m_cache_enable_particles) {
3602 const ContentFeatures &features =
3603 client->getNodeDefManager()->get(wasnode);
3604 client->getParticleManager()->addDiggingParticles(client,
3605 player, nodepos, wasnode, features);
3609 // Send event to trigger sound
3610 client->getEventManager()->put(new NodeDugEvent(nodepos, wasnode));
3613 if (runData.dig_time_complete < 100000.0) {
3614 runData.dig_time += dtime;
3616 runData.dig_time = 0;
3617 client->setCrack(-1, nodepos);
3620 camera->setDigging(0); // left click animation
3624 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
3625 const CameraOrientation &cam)
3627 TimeTaker tt_update("Game::updateFrame()");
3628 LocalPlayer *player = client->getEnv().getLocalPlayer();
3634 if (draw_control->range_all) {
3635 runData.fog_range = 100000 * BS;
3637 runData.fog_range = draw_control->wanted_range * BS;
3641 Calculate general brightness
3643 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3644 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3645 float direct_brightness;
3648 if (m_cache_enable_noclip && m_cache_enable_free_move) {
3649 direct_brightness = time_brightness;
3650 sunlight_seen = true;
3652 float old_brightness = sky->getBrightness();
3653 direct_brightness = client->getEnv().getClientMap()
3654 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
3655 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3659 float time_of_day_smooth = runData.time_of_day_smooth;
3660 float time_of_day = client->getEnv().getTimeOfDayF();
3662 static const float maxsm = 0.05f;
3663 static const float todsm = 0.05f;
3665 if (std::fabs(time_of_day - time_of_day_smooth) > maxsm &&
3666 std::fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3667 std::fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3668 time_of_day_smooth = time_of_day;
3670 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3671 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3672 + (time_of_day + 1.0) * todsm;
3674 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3675 + time_of_day * todsm;
3677 runData.time_of_day_smooth = time_of_day_smooth;
3679 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3680 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3681 player->getPitch());
3687 if (sky->getCloudsVisible()) {
3688 clouds->setVisible(true);
3689 clouds->step(dtime);
3690 // camera->getPosition is not enough for 3rd person views
3691 v3f camera_node_position = camera->getCameraNode()->getPosition();
3692 v3s16 camera_offset = camera->getOffset();
3693 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
3694 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
3695 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
3696 clouds->update(camera_node_position,
3697 sky->getCloudColor());
3698 if (clouds->isCameraInsideCloud() && m_cache_enable_fog) {
3699 // if inside clouds, and fog enabled, use that as sky
3701 video::SColor clouds_dark = clouds->getColor()
3702 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
3703 sky->overrideColors(clouds_dark, clouds->getColor());
3704 sky->setBodiesVisible(false);
3705 runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
3706 // do not draw clouds after all
3707 clouds->setVisible(false);
3710 clouds->setVisible(false);
3717 client->getParticleManager()->step(dtime);
3723 if (m_cache_enable_fog) {
3726 video::EFT_FOG_LINEAR,
3727 runData.fog_range * m_cache_fog_start,
3728 runData.fog_range * 1.0,
3736 video::EFT_FOG_LINEAR,
3746 Get chat messages from client
3749 v2u32 screensize = driver->getScreenSize();
3751 updateChat(dtime, screensize);
3757 if (player->getWieldIndex() != runData.new_playeritem)
3758 client->setPlayerItem(runData.new_playeritem);
3760 if (client->updateWieldedItem()) {
3761 // Update wielded tool
3762 ItemStack selected_item, hand_item;
3763 ItemStack &tool_item = player->getWieldedItem(&selected_item, &hand_item);
3764 camera->wield(tool_item);
3768 Update block draw list every 200ms or when camera direction has
3771 runData.update_draw_list_timer += dtime;
3773 v3f camera_direction = camera->getDirection();
3774 if (runData.update_draw_list_timer >= 0.2
3775 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3776 || m_camera_offset_changed) {
3777 runData.update_draw_list_timer = 0;
3778 client->getEnv().getClientMap().updateDrawList();
3779 runData.update_draw_list_last_cam_dir = camera_direction;
3782 m_game_ui->update(*stats, client, draw_control, cam, runData.pointed_old, gui_chat_console, dtime);
3785 make sure menu is on top
3786 1. Delete formspec menu reference if menu was removed
3787 2. Else, make sure formspec menu is on top
3789 auto formspec = m_game_ui->getFormspecGUI();
3790 do { // breakable. only runs for one iteration
3794 if (formspec->getReferenceCount() == 1) {
3795 m_game_ui->deleteFormspec();
3799 auto &loc = formspec->getFormspecLocation();
3800 if (loc.type == InventoryLocation::NODEMETA) {
3801 NodeMetadata *meta = client->getEnv().getClientMap().getNodeMetadata(loc.p);
3802 if (!meta || meta->getString("formspec").empty()) {
3803 formspec->quitMenu();
3809 guiroot->bringToFront(formspec);
3815 const video::SColor &skycolor = sky->getSkyColor();
3817 TimeTaker tt_draw("Draw scene");
3818 driver->beginScene(true, true, skycolor);
3820 bool draw_wield_tool = (m_game_ui->m_flags.show_hud &&
3821 (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
3822 (camera->getCameraMode() == CAMERA_MODE_FIRST));
3823 bool draw_crosshair = (
3824 (player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) &&
3825 (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT));
3826 #ifdef HAVE_TOUCHSCREENGUI
3828 draw_crosshair = !g_settings->getBool("touchtarget");
3829 } catch (SettingNotFoundException) {
3832 RenderingEngine::draw_scene(skycolor, m_game_ui->m_flags.show_hud,
3833 m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair);
3838 if (m_game_ui->m_flags.show_profiler_graph)
3839 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3844 if (runData.damage_flash > 0.0f) {
3845 video::SColor color(runData.damage_flash, 180, 0, 0);
3846 driver->draw2DRectangle(color,
3847 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3850 runData.damage_flash -= 384.0f * dtime;
3856 if (player->hurt_tilt_timer > 0.0f) {
3857 player->hurt_tilt_timer -= dtime * 6.0f;
3859 if (player->hurt_tilt_timer < 0.0f)
3860 player->hurt_tilt_strength = 0.0f;
3864 Update minimap pos and rotation
3866 if (mapper && m_game_ui->m_flags.show_minimap && m_game_ui->m_flags.show_hud) {
3867 mapper->setPos(floatToInt(player->getPosition(), BS));
3868 mapper->setAngle(player->getYaw());
3876 stats->drawtime = tt_draw.stop(true);
3877 g_profiler->avg("Game::updateFrame(): draw scene [ms]", stats->drawtime);
3878 g_profiler->graphAdd("Update frame [ms]", tt_update.stop(true));
3881 /* Log times and stuff for visualization */
3882 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
3884 Profiler::GraphValues values;
3885 g_profiler->graphGet(values);
3891 /****************************************************************************
3893 ****************************************************************************/
3895 /* On some computers framerate doesn't seem to be automatically limited
3897 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
3899 // not using getRealTime is necessary for wine
3900 device->getTimer()->tick(); // Maker sure device time is up-to-date
3901 u32 time = device->getTimer()->getTime();
3902 u32 last_time = fps_timings->last_time;
3904 if (time > last_time) // Make sure time hasn't overflowed
3905 fps_timings->busy_time = time - last_time;
3907 fps_timings->busy_time = 0;
3909 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
3910 ? g_settings->getFloat("pause_fps_max")
3911 : g_settings->getFloat("fps_max"));
3913 if (fps_timings->busy_time < frametime_min) {
3914 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
3915 device->sleep(fps_timings->sleep_time);
3917 fps_timings->sleep_time = 0;
3920 /* Get the new value of the device timer. Note that device->sleep() may
3921 * not sleep for the entire requested time as sleep may be interrupted and
3922 * therefore it is arguably more accurate to get the new time from the
3923 * device rather than calculating it by adding sleep_time to time.
3926 device->getTimer()->tick(); // Update device timer
3927 time = device->getTimer()->getTime();
3929 if (time > last_time) // Make sure last_time hasn't overflowed
3930 *dtime = (time - last_time) / 1000.0;
3934 fps_timings->last_time = time;
3937 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
3939 const wchar_t *wmsg = wgettext(msg);
3940 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
3945 void Game::settingChangedCallback(const std::string &setting_name, void *data)
3947 ((Game *)data)->readSettings();
3950 void Game::readSettings()
3952 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
3953 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
3954 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
3955 m_cache_enable_particles = g_settings->getBool("enable_particles");
3956 m_cache_enable_fog = g_settings->getBool("enable_fog");
3957 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
3958 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
3959 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
3961 m_cache_enable_noclip = g_settings->getBool("noclip");
3962 m_cache_enable_free_move = g_settings->getBool("free_move");
3964 m_cache_fog_start = g_settings->getFloat("fog_start");
3966 m_cache_cam_smoothing = 0;
3967 if (g_settings->getBool("cinematic"))
3968 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
3970 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
3972 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
3973 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
3974 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
3976 m_does_lost_focus_pause_game = g_settings->getBool("pause_on_lost_focus");
3979 /****************************************************************************/
3980 /****************************************************************************
3982 ****************************************************************************/
3983 /****************************************************************************/
3985 void Game::extendedResourceCleanup()
3987 // Extended resource accounting
3988 infostream << "Irrlicht resources after cleanup:" << std::endl;
3989 infostream << "\tRemaining meshes : "
3990 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
3991 infostream << "\tRemaining textures : "
3992 << driver->getTextureCount() << std::endl;
3994 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
3995 irr::video::ITexture *texture = driver->getTextureByIndex(i);
3996 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4000 clearTextureNameCache();
4001 infostream << "\tRemaining materials: "
4002 << driver-> getMaterialRendererCount()
4003 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4006 void Game::showDeathFormspec()
4008 static std::string formspec_str =
4009 std::string("formspec_version[1]") +
4011 "bgcolor[#320000b4;true]"
4012 "label[4.85,1.35;" + gettext("You died") + "]"
4013 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
4017 /* Note: FormspecFormSource and LocalFormspecHandler *
4018 * are deleted by guiFormSpecMenu */
4019 FormspecFormSource *fs_src = new FormspecFormSource(formspec_str);
4020 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
4022 auto *&formspec = m_game_ui->getFormspecGUI();
4023 GUIFormSpecMenu::create(formspec, client, &input->joystick,
4024 fs_src, txt_dst, client->getFormspecPrepend());
4025 formspec->setFocus("btn_respawn");
4028 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4029 void Game::showPauseMenu()
4032 static const std::string control_text = strgettext("Default Controls:\n"
4033 "No menu visible:\n"
4034 "- single tap: button activate\n"
4035 "- double tap: place/use\n"
4036 "- slide finger: look around\n"
4037 "Menu/Inventory visible:\n"
4038 "- double tap (outside):\n"
4040 "- touch stack, touch slot:\n"
4042 "- touch&drag, tap 2nd finger\n"
4043 " --> place single item to slot\n"
4046 static const std::string control_text_template = strgettext("Controls:\n"
4047 "- %s: move forwards\n"
4048 "- %s: move backwards\n"
4050 "- %s: move right\n"
4051 "- %s: jump/climb\n"
4052 "- %s: sneak/go down\n"
4055 "- Mouse: turn/look\n"
4056 "- Mouse left: dig/punch\n"
4057 "- Mouse right: place/use\n"
4058 "- Mouse wheel: select item\n"
4062 char control_text_buf[600];
4064 porting::mt_snprintf(control_text_buf, sizeof(control_text_buf), control_text_template.c_str(),
4065 GET_KEY_NAME(keymap_forward),
4066 GET_KEY_NAME(keymap_backward),
4067 GET_KEY_NAME(keymap_left),
4068 GET_KEY_NAME(keymap_right),
4069 GET_KEY_NAME(keymap_jump),
4070 GET_KEY_NAME(keymap_sneak),
4071 GET_KEY_NAME(keymap_drop),
4072 GET_KEY_NAME(keymap_inventory),
4073 GET_KEY_NAME(keymap_chat)
4076 std::string control_text = std::string(control_text_buf);
4077 str_formspec_escape(control_text);
4080 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4081 std::ostringstream os;
4083 os << "formspec_version[1]" << SIZE_TAG
4084 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4085 << strgettext("Continue") << "]";
4087 if (!simple_singleplayer_mode) {
4088 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4089 << strgettext("Change Password") << "]";
4091 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4095 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4096 << strgettext("Sound Volume") << "]";
4097 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4098 << strgettext("Change Keys") << "]";
4100 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4101 << strgettext("Exit to Menu") << "]";
4102 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4103 << strgettext("Exit to OS") << "]"
4104 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4105 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4107 << strgettext("Game info:") << "\n";
4108 const std::string &address = client->getAddressName();
4109 static const std::string mode = strgettext("- Mode: ");
4110 if (!simple_singleplayer_mode) {
4111 Address serverAddress = client->getServerAddress();
4112 if (!address.empty()) {
4113 os << mode << strgettext("Remote server") << "\n"
4114 << strgettext("- Address: ") << address;
4116 os << mode << strgettext("Hosting server");
4118 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4120 os << mode << strgettext("Singleplayer") << "\n";
4122 if (simple_singleplayer_mode || address.empty()) {
4123 static const std::string on = strgettext("On");
4124 static const std::string off = strgettext("Off");
4125 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4126 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4127 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4128 os << strgettext("- Damage: ") << damage << "\n"
4129 << strgettext("- Creative Mode: ") << creative << "\n";
4130 if (!simple_singleplayer_mode) {
4131 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4132 os << strgettext("- PvP: ") << pvp << "\n"
4133 << strgettext("- Public: ") << announced << "\n";
4134 std::string server_name = g_settings->get("server_name");
4135 str_formspec_escape(server_name);
4136 if (announced == on && !server_name.empty())
4137 os << strgettext("- Server Name: ") << server_name;
4144 /* Note: FormspecFormSource and LocalFormspecHandler *
4145 * are deleted by guiFormSpecMenu */
4146 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4147 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4149 auto *&formspec = m_game_ui->getFormspecGUI();
4150 GUIFormSpecMenu::create(formspec, client, &input->joystick,
4151 fs_src, txt_dst, client->getFormspecPrepend());
4152 formspec->setFocus("btn_continue");
4153 formspec->doPause = true;
4156 /****************************************************************************/
4157 /****************************************************************************
4158 extern function for launching the game
4159 ****************************************************************************/
4160 /****************************************************************************/
4162 void the_game(bool *kill,
4164 InputHandler *input,
4165 const std::string &map_dir,
4166 const std::string &playername,
4167 const std::string &password,
4168 const std::string &address, // If empty local server is created
4171 std::string &error_message,
4172 ChatBackend &chat_backend,
4173 bool *reconnect_requested,
4174 const SubgameSpec &gamespec, // Used for local game
4175 bool simple_singleplayer_mode)
4179 /* Make a copy of the server address because if a local singleplayer server
4180 * is created then this is updated and we don't want to change the value
4181 * passed to us by the calling function
4183 std::string server_address = address;
4187 if (game.startup(kill, random_input, input, map_dir,
4188 playername, password, &server_address, port, error_message,
4189 reconnect_requested, &chat_backend, gamespec,
4190 simple_singleplayer_mode)) {
4195 } catch (SerializationError &e) {
4196 error_message = std::string("A serialization error occurred:\n")
4197 + e.what() + "\n\nThe server is probably "
4198 " running a different version of " PROJECT_NAME_C ".";
4199 errorstream << error_message << std::endl;
4200 } catch (ServerError &e) {
4201 error_message = e.what();
4202 errorstream << "ServerError: " << error_message << std::endl;
4203 } catch (ModError &e) {
4204 error_message = std::string("ModError: ") + e.what() +
4205 strgettext("\nCheck debug.txt for details.");
4206 errorstream << error_message << std::endl;