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"
58 #include "quicktune_shortcutter.h"
64 #include "translation.h"
65 #include "util/basic_macros.h"
66 #include "util/directiontables.h"
67 #include "util/pointedthing.h"
68 #include "irrlicht_changes/static_text.h"
70 #include "script/scripting_client.h"
73 #include "client/sound_openal.h"
75 #include "client/sound.h"
81 struct TextDestNodeMetadata : public TextDest
83 TextDestNodeMetadata(v3s16 p, Client *client)
88 // This is deprecated I guess? -celeron55
89 void gotText(const std::wstring &text)
91 std::string ntext = wide_to_utf8(text);
92 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
93 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
95 fields["text"] = ntext;
96 m_client->sendNodemetaFields(m_p, "", fields);
98 void gotText(const StringMap &fields)
100 m_client->sendNodemetaFields(m_p, "", fields);
107 struct TextDestPlayerInventory : public TextDest
109 TextDestPlayerInventory(Client *client)
114 TextDestPlayerInventory(Client *client, const std::string &formname)
117 m_formname = formname;
119 void gotText(const StringMap &fields)
121 m_client->sendInventoryFields(m_formname, fields);
127 struct LocalFormspecHandler : public TextDest
129 LocalFormspecHandler(const std::string &formname)
131 m_formname = formname;
134 LocalFormspecHandler(const std::string &formname, Client *client):
137 m_formname = formname;
140 void gotText(const StringMap &fields)
142 if (m_formname == "MT_PAUSE_MENU") {
143 if (fields.find("btn_sound") != fields.end()) {
144 g_gamecallback->changeVolume();
148 if (fields.find("btn_key_config") != fields.end()) {
149 g_gamecallback->keyConfig();
153 if (fields.find("btn_exit_menu") != fields.end()) {
154 g_gamecallback->disconnect();
158 if (fields.find("btn_exit_os") != fields.end()) {
159 g_gamecallback->exitToOS();
161 RenderingEngine::get_raw_device()->closeDevice();
166 if (fields.find("btn_change_password") != fields.end()) {
167 g_gamecallback->changePassword();
171 if (fields.find("quit") != fields.end()) {
175 if (fields.find("btn_continue") != fields.end()) {
180 if (m_formname == "MT_DEATH_SCREEN") {
181 assert(m_client != 0);
182 m_client->sendRespawn();
186 if (m_client && m_client->moddingEnabled())
187 m_client->getScript()->on_formspec_input(m_formname, fields);
190 Client *m_client = nullptr;
193 /* Form update callback */
195 class NodeMetadataFormSource: public IFormSource
198 NodeMetadataFormSource(ClientMap *map, v3s16 p):
203 const std::string &getForm() const
205 static const std::string empty_string = "";
206 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
211 return meta->getString("formspec");
214 virtual std::string resolveText(const std::string &str)
216 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
221 return meta->resolveString(str);
228 class PlayerInventoryFormSource: public IFormSource
231 PlayerInventoryFormSource(Client *client):
236 const std::string &getForm() const
238 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
239 return player->inventory_formspec;
245 class NodeDugEvent: public MtEvent
251 NodeDugEvent(v3s16 p, MapNode n):
255 MtEvent::Type getType() const
257 return MtEvent::NODE_DUG;
263 ISoundManager *m_sound;
264 const NodeDefManager *m_ndef;
266 bool makes_footstep_sound;
267 float m_player_step_timer;
269 SimpleSoundSpec m_player_step_sound;
270 SimpleSoundSpec m_player_leftpunch_sound;
271 SimpleSoundSpec m_player_rightpunch_sound;
273 SoundMaker(ISoundManager *sound, const NodeDefManager *ndef):
276 makes_footstep_sound(true),
277 m_player_step_timer(0)
281 void playPlayerStep()
283 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
284 m_player_step_timer = 0.03;
285 if (makes_footstep_sound)
286 m_sound->playSound(m_player_step_sound, false);
290 static void viewBobbingStep(MtEvent *e, void *data)
292 SoundMaker *sm = (SoundMaker *)data;
293 sm->playPlayerStep();
296 static void playerRegainGround(MtEvent *e, void *data)
298 SoundMaker *sm = (SoundMaker *)data;
299 sm->playPlayerStep();
302 static void playerJump(MtEvent *e, void *data)
304 //SoundMaker *sm = (SoundMaker*)data;
307 static void cameraPunchLeft(MtEvent *e, void *data)
309 SoundMaker *sm = (SoundMaker *)data;
310 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
313 static void cameraPunchRight(MtEvent *e, void *data)
315 SoundMaker *sm = (SoundMaker *)data;
316 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
319 static void nodeDug(MtEvent *e, void *data)
321 SoundMaker *sm = (SoundMaker *)data;
322 NodeDugEvent *nde = (NodeDugEvent *)e;
323 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
326 static void playerDamage(MtEvent *e, void *data)
328 SoundMaker *sm = (SoundMaker *)data;
329 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
332 static void playerFallingDamage(MtEvent *e, void *data)
334 SoundMaker *sm = (SoundMaker *)data;
335 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
338 void registerReceiver(MtEventManager *mgr)
340 mgr->reg(MtEvent::VIEW_BOBBING_STEP, SoundMaker::viewBobbingStep, this);
341 mgr->reg(MtEvent::PLAYER_REGAIN_GROUND, SoundMaker::playerRegainGround, this);
342 mgr->reg(MtEvent::PLAYER_JUMP, SoundMaker::playerJump, this);
343 mgr->reg(MtEvent::CAMERA_PUNCH_LEFT, SoundMaker::cameraPunchLeft, this);
344 mgr->reg(MtEvent::CAMERA_PUNCH_RIGHT, SoundMaker::cameraPunchRight, this);
345 mgr->reg(MtEvent::NODE_DUG, SoundMaker::nodeDug, this);
346 mgr->reg(MtEvent::PLAYER_DAMAGE, SoundMaker::playerDamage, this);
347 mgr->reg(MtEvent::PLAYER_FALLING_DAMAGE, SoundMaker::playerFallingDamage, this);
350 void step(float dtime)
352 m_player_step_timer -= dtime;
356 // Locally stored sounds don't need to be preloaded because of this
357 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
359 std::set<std::string> m_fetched;
361 void paths_insert(std::set<std::string> &dst_paths,
362 const std::string &base,
363 const std::string &name)
365 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
366 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
367 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
368 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
369 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
370 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
371 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
372 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
373 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
374 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
375 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
378 void fetchSounds(const std::string &name,
379 std::set<std::string> &dst_paths,
380 std::set<std::string> &dst_datas)
382 if (m_fetched.count(name))
385 m_fetched.insert(name);
387 paths_insert(dst_paths, porting::path_share, name);
388 paths_insert(dst_paths, porting::path_user, name);
393 // before 1.8 there isn't a "integer interface", only float
394 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
395 typedef f32 SamplerLayer_t;
397 typedef s32 SamplerLayer_t;
401 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
404 bool *m_force_fog_off;
407 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
408 CachedPixelShaderSetting<float> m_fog_distance;
409 CachedVertexShaderSetting<float> m_animation_timer_vertex;
410 CachedPixelShaderSetting<float> m_animation_timer_pixel;
411 CachedPixelShaderSetting<float, 3> m_day_light;
412 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
413 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
414 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
415 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
416 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
417 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
421 void onSettingsChange(const std::string &name)
423 if (name == "enable_fog")
424 m_fog_enabled = g_settings->getBool("enable_fog");
427 static void settingsCallback(const std::string &name, void *userdata)
429 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
432 void setSky(Sky *sky) { m_sky = sky; }
434 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
435 f32 *fog_range, Client *client) :
437 m_force_fog_off(force_fog_off),
438 m_fog_range(fog_range),
439 m_sky_bg_color("skyBgColor"),
440 m_fog_distance("fogDistance"),
441 m_animation_timer_vertex("animationTimer"),
442 m_animation_timer_pixel("animationTimer"),
443 m_day_light("dayLight"),
444 m_eye_position_pixel("eyePosition"),
445 m_eye_position_vertex("eyePosition"),
446 m_minimap_yaw("yawVec"),
447 m_base_texture("baseTexture"),
448 m_normal_texture("normalTexture"),
449 m_texture_flags("textureFlags"),
452 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
453 m_fog_enabled = g_settings->getBool("enable_fog");
456 ~GameGlobalShaderConstantSetter()
458 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
461 virtual void onSetConstants(video::IMaterialRendererServices *services,
468 video::SColor bgcolor = m_sky->getBgColor();
469 video::SColorf bgcolorf(bgcolor);
470 float bgcolorfa[4] = {
476 m_sky_bg_color.set(bgcolorfa, services);
479 float fog_distance = 10000 * BS;
481 if (m_fog_enabled && !*m_force_fog_off)
482 fog_distance = *m_fog_range;
484 m_fog_distance.set(&fog_distance, services);
486 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
487 video::SColorf sunlight;
488 get_sunlight_color(&sunlight, daynight_ratio);
493 m_day_light.set(dnc, services);
495 u32 animation_timer = porting::getTimeMs() % 100000;
496 float animation_timer_f = (float)animation_timer / 100000.f;
497 m_animation_timer_vertex.set(&animation_timer_f, services);
498 m_animation_timer_pixel.set(&animation_timer_f, services);
500 float eye_position_array[3];
501 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
502 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
503 eye_position_array[0] = epos.X;
504 eye_position_array[1] = epos.Y;
505 eye_position_array[2] = epos.Z;
507 epos.getAs3Values(eye_position_array);
509 m_eye_position_pixel.set(eye_position_array, services);
510 m_eye_position_vertex.set(eye_position_array, services);
512 if (m_client->getMinimap()) {
513 float minimap_yaw_array[3];
514 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
515 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
516 minimap_yaw_array[0] = minimap_yaw.X;
517 minimap_yaw_array[1] = minimap_yaw.Y;
518 minimap_yaw_array[2] = minimap_yaw.Z;
520 minimap_yaw.getAs3Values(minimap_yaw_array);
522 m_minimap_yaw.set(minimap_yaw_array, services);
525 SamplerLayer_t base_tex = 0,
528 m_base_texture.set(&base_tex, services);
529 m_normal_texture.set(&normal_tex, services);
530 m_texture_flags.set(&flags_tex, services);
535 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
538 bool *m_force_fog_off;
541 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
543 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
544 f32 *fog_range, Client *client) :
546 m_force_fog_off(force_fog_off),
547 m_fog_range(fog_range),
551 void setSky(Sky *sky) {
553 for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
554 ggscs->setSky(m_sky);
556 created_nosky.clear();
559 virtual IShaderConstantSetter* create()
561 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
562 m_sky, m_force_fog_off, m_fog_range, m_client);
564 created_nosky.push_back(scs);
570 #define SIZE_TAG "size[11,5.5]"
572 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
575 /****************************************************************************
577 ****************************************************************************/
579 const float object_hit_delay = 0.2;
582 u32 last_time, busy_time, sleep_time;
586 /* The reason the following structs are not anonymous structs within the
587 * class is that they are not used by the majority of member functions and
588 * many functions that do require objects of thse types do not modify them
589 * (so they can be passed as a const qualified parameter)
595 PointedThing pointed_old;
599 bool digging_blocked;
601 bool update_wielded_item_trigger;
602 bool reset_jump_timer;
603 float nodig_delay_timer;
605 float dig_time_complete;
606 float repeat_rightclick_timer;
607 float object_hit_delay_timer;
608 float time_from_last_punch;
609 ClientActiveObject *selected_object;
613 float update_draw_list_timer;
617 v3f update_draw_list_last_cam_dir;
619 float time_of_day_smooth;
624 struct ClientEventHandler
626 void (Game::*handler)(ClientEvent *, CameraOrientation *);
629 /****************************************************************************
631 ****************************************************************************/
633 /* This is not intended to be a public class. If a public class becomes
634 * desirable then it may be better to create another 'wrapper' class that
635 * hides most of the stuff in this class (nothing in this class is required
636 * by any other file) but exposes the public methods/data only.
643 bool startup(bool *kill,
646 const std::string &map_dir,
647 const std::string &playername,
648 const std::string &password,
649 // If address is "", local server is used and address is updated
650 std::string *address,
652 std::string &error_message,
654 ChatBackend *chat_backend,
655 const SubgameSpec &gamespec, // Used for local game
656 bool simple_singleplayer_mode);
663 void extendedResourceCleanup();
665 // Basic initialisation
666 bool init(const std::string &map_dir, std::string *address,
668 const SubgameSpec &gamespec);
670 bool createSingleplayerServer(const std::string &map_dir,
671 const SubgameSpec &gamespec, u16 port, std::string *address);
674 bool createClient(const std::string &playername,
675 const std::string &password, std::string *address, u16 port);
679 bool connectToServer(const std::string &playername,
680 const std::string &password, std::string *address, u16 port,
681 bool *connect_ok, bool *aborted);
682 bool getServerContent(bool *aborted);
686 void updateInteractTimers(f32 dtime);
687 bool checkConnection();
688 bool handleCallbacks();
689 void processQueues();
690 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
691 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
692 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
695 void processUserInput(f32 dtime);
696 void processKeyInput();
697 void processItemSelection(u16 *new_playeritem);
699 void dropSelectedItem(bool single_item = false);
700 void openInventory();
701 void openConsole(float scale, const wchar_t *line=NULL);
702 void toggleFreeMove();
703 void toggleFreeMoveAlt();
706 void toggleCinematic();
707 void toggleAutoforward();
709 void toggleMinimap(bool shift_pressed);
712 void toggleUpdateCamera();
714 void increaseViewRange();
715 void decreaseViewRange();
716 void toggleFullViewRange();
717 void checkZoomEnabled();
719 void updateCameraDirection(CameraOrientation *cam, float dtime);
720 void updateCameraOrientation(CameraOrientation *cam, float dtime);
721 void updatePlayerControl(const CameraOrientation &cam);
722 void step(f32 *dtime);
723 void processClientEvents(CameraOrientation *cam);
724 void updateCamera(u32 busy_time, f32 dtime);
725 void updateSound(f32 dtime);
726 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
728 * Returns the object or node the player is pointing at.
729 * Also updates the selected thing in the Hud.
731 * @param[in] shootline the shootline, starting from
732 * the camera position. This also gives the maximal distance
734 * @param[in] liquids_pointable if false, liquids are ignored
735 * @param[in] look_for_object if false, objects are ignored
736 * @param[in] camera_offset offset of the camera
737 * @param[out] selected_object the selected object or
740 PointedThing updatePointedThing(
741 const core::line3d<f32> &shootline, bool liquids_pointable,
742 bool look_for_object, const v3s16 &camera_offset);
743 void handlePointingAtNothing(const ItemStack &playerItem);
744 void handlePointingAtNode(const PointedThing &pointed,
745 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
746 const ToolCapabilities &playeritem_toolcap, f32 dtime);
747 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
748 const v3f &player_position, bool show_debug);
749 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
750 const ToolCapabilities &playeritem_toolcap, f32 dtime);
751 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
752 const CameraOrientation &cam);
753 void updateProfilerGraphs(ProfilerGraph *graph);
756 void limitFps(FpsControl *fps_timings, f32 *dtime);
758 void showOverlayMessage(const char *msg, float dtime, int percent,
759 bool draw_clouds = true);
761 static void settingChangedCallback(const std::string &setting_name, void *data);
764 inline bool isKeyDown(GameKeyType k)
766 return input->isKeyDown(k);
768 inline bool wasKeyDown(GameKeyType k)
770 return input->wasKeyDown(k);
774 void handleAndroidChatInput();
779 bool force_fog_off = false;
780 bool disable_camera_update = false;
783 void showDeathFormspec();
784 void showPauseMenu();
786 // ClientEvent handlers
787 void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam);
788 void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam);
789 void handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam);
790 void handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam);
791 void handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam);
792 void handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam);
793 void handleClientEvent_HandleParticleEvent(ClientEvent *event,
794 CameraOrientation *cam);
795 void handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam);
796 void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam);
797 void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam);
798 void handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam);
799 void handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
800 CameraOrientation *cam);
801 void handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam);
803 void updateChat(f32 dtime, const v2u32 &screensize);
805 bool nodePlacementPrediction(const ItemDefinition &playeritem_def,
806 const ItemStack &playeritem, const v3s16 &nodepos, const v3s16 &neighbourpos);
807 static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX];
809 InputHandler *input = nullptr;
811 Client *client = nullptr;
812 Server *server = nullptr;
814 IWritableTextureSource *texture_src = nullptr;
815 IWritableShaderSource *shader_src = nullptr;
817 // When created, these will be filled with data received from the server
818 IWritableItemDefManager *itemdef_manager = nullptr;
819 NodeDefManager *nodedef_manager = nullptr;
821 GameOnDemandSoundFetcher soundfetcher; // useful when testing
822 ISoundManager *sound = nullptr;
823 bool sound_is_dummy = false;
824 SoundMaker *soundmaker = nullptr;
826 ChatBackend *chat_backend = nullptr;
828 GUIFormSpecMenu *current_formspec = nullptr;
829 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
830 std::string cur_formname;
832 EventManager *eventmgr = nullptr;
833 QuicktuneShortcutter *quicktune = nullptr;
834 bool registration_confirmation_shown = false;
836 std::unique_ptr<GameUI> m_game_ui;
837 GUIChatConsole *gui_chat_console = nullptr; // Free using ->Drop()
838 MapDrawControl *draw_control = nullptr;
839 Camera *camera = nullptr;
840 Clouds *clouds = nullptr; // Free using ->Drop()
841 Sky *sky = nullptr; // Free using ->Drop()
842 Inventory *local_inventory = nullptr;
844 Minimap *mapper = nullptr;
850 This class does take ownership/responsibily for cleaning up etc of any of
851 these items (e.g. device)
853 IrrlichtDevice *device;
854 video::IVideoDriver *driver;
855 scene::ISceneManager *smgr;
857 std::string *error_message;
858 bool *reconnect_requested;
859 scene::ISceneNode *skybox;
862 bool simple_singleplayer_mode;
865 /* Pre-calculated values
867 int crack_animation_length;
869 IntervalLimiter profiler_interval;
872 * TODO: Local caching of settings is not optimal and should at some stage
873 * be updated to use a global settings object for getting thse values
874 * (as opposed to the this local caching). This can be addressed in
877 bool m_cache_doubletap_jump;
878 bool m_cache_enable_clouds;
879 bool m_cache_enable_joysticks;
880 bool m_cache_enable_particles;
881 bool m_cache_enable_fog;
882 bool m_cache_enable_noclip;
883 bool m_cache_enable_free_move;
884 f32 m_cache_mouse_sensitivity;
885 f32 m_cache_joystick_frustum_sensitivity;
886 f32 m_repeat_right_click_time;
887 f32 m_cache_cam_smoothing;
888 f32 m_cache_fog_start;
890 bool m_invert_mouse = false;
891 bool m_first_loop_after_window_activation = false;
892 bool m_camera_offset_changed = false;
894 bool m_does_lost_focus_pause_game = false;
897 bool m_cache_hold_aux1;
898 bool m_android_chat_open;
903 m_game_ui(new GameUI())
905 g_settings->registerChangedCallback("doubletap_jump",
906 &settingChangedCallback, this);
907 g_settings->registerChangedCallback("enable_clouds",
908 &settingChangedCallback, this);
909 g_settings->registerChangedCallback("doubletap_joysticks",
910 &settingChangedCallback, this);
911 g_settings->registerChangedCallback("enable_particles",
912 &settingChangedCallback, this);
913 g_settings->registerChangedCallback("enable_fog",
914 &settingChangedCallback, this);
915 g_settings->registerChangedCallback("mouse_sensitivity",
916 &settingChangedCallback, this);
917 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
918 &settingChangedCallback, this);
919 g_settings->registerChangedCallback("repeat_rightclick_time",
920 &settingChangedCallback, this);
921 g_settings->registerChangedCallback("noclip",
922 &settingChangedCallback, this);
923 g_settings->registerChangedCallback("free_move",
924 &settingChangedCallback, this);
925 g_settings->registerChangedCallback("cinematic",
926 &settingChangedCallback, this);
927 g_settings->registerChangedCallback("cinematic_camera_smoothing",
928 &settingChangedCallback, this);
929 g_settings->registerChangedCallback("camera_smoothing",
930 &settingChangedCallback, this);
935 m_cache_hold_aux1 = false; // This is initialised properly later
942 /****************************************************************************
944 ****************************************************************************/
953 delete server; // deleted first to stop all server threads
956 delete local_inventory;
962 delete nodedef_manager;
963 delete itemdef_manager;
966 extendedResourceCleanup();
968 g_settings->deregisterChangedCallback("doubletap_jump",
969 &settingChangedCallback, this);
970 g_settings->deregisterChangedCallback("enable_clouds",
971 &settingChangedCallback, this);
972 g_settings->deregisterChangedCallback("enable_particles",
973 &settingChangedCallback, this);
974 g_settings->deregisterChangedCallback("enable_fog",
975 &settingChangedCallback, this);
976 g_settings->deregisterChangedCallback("mouse_sensitivity",
977 &settingChangedCallback, this);
978 g_settings->deregisterChangedCallback("repeat_rightclick_time",
979 &settingChangedCallback, this);
980 g_settings->deregisterChangedCallback("noclip",
981 &settingChangedCallback, this);
982 g_settings->deregisterChangedCallback("free_move",
983 &settingChangedCallback, this);
984 g_settings->deregisterChangedCallback("cinematic",
985 &settingChangedCallback, this);
986 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
987 &settingChangedCallback, this);
988 g_settings->deregisterChangedCallback("camera_smoothing",
989 &settingChangedCallback, this);
992 bool Game::startup(bool *kill,
995 const std::string &map_dir,
996 const std::string &playername,
997 const std::string &password,
998 std::string *address, // can change if simple_singleplayer_mode
1000 std::string &error_message,
1002 ChatBackend *chat_backend,
1003 const SubgameSpec &gamespec,
1004 bool simple_singleplayer_mode)
1007 this->device = RenderingEngine::get_raw_device();
1009 this->error_message = &error_message;
1010 this->reconnect_requested = reconnect;
1011 this->random_input = random_input;
1012 this->input = input;
1013 this->chat_backend = chat_backend;
1014 this->simple_singleplayer_mode = simple_singleplayer_mode;
1016 input->keycache.populate();
1018 driver = device->getVideoDriver();
1019 smgr = RenderingEngine::get_scene_manager();
1021 RenderingEngine::get_scene_manager()->getParameters()->
1022 setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1025 runData = GameRunData();
1026 runData.time_from_last_punch = 10.0;
1027 runData.update_wielded_item_trigger = true;
1029 m_game_ui->initFlags();
1031 m_invert_mouse = g_settings->getBool("invert_mouse");
1032 m_first_loop_after_window_activation = true;
1034 g_translations->clear();
1036 if (!init(map_dir, address, port, gamespec))
1039 if (!createClient(playername, password, address, port))
1042 RenderingEngine::initialize(client, hud);
1050 ProfilerGraph graph;
1051 RunStats stats = { 0 };
1052 CameraOrientation cam_view_target = { 0 };
1053 CameraOrientation cam_view = { 0 };
1054 FpsControl draw_times = { 0 };
1055 f32 dtime; // in seconds
1057 /* Clear the profiler */
1058 Profiler::GraphValues dummyvalues;
1059 g_profiler->graphGet(dummyvalues);
1061 draw_times.last_time = RenderingEngine::get_timer_time();
1063 set_light_table(g_settings->getFloat("display_gamma"));
1066 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1067 && client->checkPrivilege("fast");
1070 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1071 g_settings->getU16("screen_h"));
1073 while (RenderingEngine::run()
1074 && !(*kill || g_gamecallback->shutdown_requested
1075 || (server && server->isShutdownRequested()))) {
1077 const irr::core::dimension2d<u32> ¤t_screen_size =
1078 RenderingEngine::get_video_driver()->getScreenSize();
1079 // Verify if window size has changed and save it if it's the case
1080 // Ensure evaluating settings->getBool after verifying screensize
1081 // First condition is cheaper
1082 if (previous_screen_size != current_screen_size &&
1083 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1084 g_settings->getBool("autosave_screensize")) {
1085 g_settings->setU16("screen_w", current_screen_size.Width);
1086 g_settings->setU16("screen_h", current_screen_size.Height);
1087 previous_screen_size = current_screen_size;
1090 /* Must be called immediately after a device->run() call because it
1091 * uses device->getTimer()->getTime()
1093 limitFps(&draw_times, &dtime);
1095 updateStats(&stats, draw_times, dtime);
1096 updateInteractTimers(dtime);
1098 if (!checkConnection())
1100 if (!handleCallbacks())
1105 m_game_ui->clearInfoText();
1106 hud->resizeHotbar();
1108 updateProfilers(stats, draw_times, dtime);
1109 processUserInput(dtime);
1110 // Update camera before player movement to avoid camera lag of one frame
1111 updateCameraDirection(&cam_view_target, dtime);
1112 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1113 cam_view.camera_yaw) * m_cache_cam_smoothing;
1114 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1115 cam_view.camera_pitch) * m_cache_cam_smoothing;
1116 updatePlayerControl(cam_view);
1118 processClientEvents(&cam_view_target);
1119 updateCamera(draw_times.busy_time, dtime);
1121 processPlayerInteraction(dtime, m_game_ui->m_flags.show_hud,
1122 m_game_ui->m_flags.show_debug);
1123 updateFrame(&graph, &stats, dtime, cam_view);
1124 updateProfilerGraphs(&graph);
1126 // Update if minimap has been disabled by the server
1127 m_game_ui->m_flags.show_minimap &= client->shouldShowMinimap();
1129 if (m_does_lost_focus_pause_game && !device->isWindowFocused() && !isMenuActive()) {
1136 void Game::shutdown()
1138 RenderingEngine::finalize();
1139 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1140 if (g_settings->get("3d_mode") == "pageflip") {
1141 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1144 if (current_formspec)
1145 current_formspec->quitMenu();
1147 showOverlayMessage("Shutting down...", 0, 0, false);
1152 if (gui_chat_console)
1153 gui_chat_console->drop();
1159 while (g_menumgr.menuCount() > 0) {
1160 g_menumgr.m_stack.front()->setVisible(false);
1161 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1164 if (current_formspec) {
1165 current_formspec->drop();
1166 current_formspec = NULL;
1169 chat_backend->addMessage(L"", L"# Disconnected.");
1170 chat_backend->addMessage(L"", L"");
1174 while (!client->isShutdown()) {
1175 assert(texture_src != NULL);
1176 assert(shader_src != NULL);
1177 texture_src->processQueue();
1178 shader_src->processQueue();
1185 /****************************************************************************/
1186 /****************************************************************************
1188 ****************************************************************************/
1189 /****************************************************************************/
1192 const std::string &map_dir,
1193 std::string *address,
1195 const SubgameSpec &gamespec)
1197 texture_src = createTextureSource();
1199 showOverlayMessage("Loading...", 0, 0);
1201 shader_src = createShaderSource();
1203 itemdef_manager = createItemDefManager();
1204 nodedef_manager = createNodeDefManager();
1206 eventmgr = new EventManager();
1207 quicktune = new QuicktuneShortcutter();
1209 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1210 && eventmgr && quicktune))
1216 // Create a server if not connecting to an existing one
1217 if (address->empty()) {
1218 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1225 bool Game::initSound()
1228 if (g_settings->getBool("enable_sound")) {
1229 infostream << "Attempting to use OpenAL audio" << std::endl;
1230 sound = createOpenALSoundManager(g_sound_manager_singleton.get(), &soundfetcher);
1232 infostream << "Failed to initialize OpenAL audio" << std::endl;
1234 infostream << "Sound disabled." << std::endl;
1238 infostream << "Using dummy audio." << std::endl;
1239 sound = &dummySoundManager;
1240 sound_is_dummy = true;
1243 soundmaker = new SoundMaker(sound, nodedef_manager);
1247 soundmaker->registerReceiver(eventmgr);
1252 bool Game::createSingleplayerServer(const std::string &map_dir,
1253 const SubgameSpec &gamespec, u16 port, std::string *address)
1255 showOverlayMessage("Creating server...", 0, 5);
1257 std::string bind_str = g_settings->get("bind_address");
1258 Address bind_addr(0, 0, 0, 0, port);
1260 if (g_settings->getBool("ipv6_server")) {
1261 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1265 bind_addr.Resolve(bind_str.c_str());
1266 } catch (ResolveError &e) {
1267 infostream << "Resolving bind address \"" << bind_str
1268 << "\" failed: " << e.what()
1269 << " -- Listening on all addresses." << std::endl;
1272 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1273 *error_message = "Unable to listen on " +
1274 bind_addr.serializeString() +
1275 " because IPv6 is disabled";
1276 errorstream << *error_message << std::endl;
1280 server = new Server(map_dir, gamespec, simple_singleplayer_mode, bind_addr, false);
1287 bool Game::createClient(const std::string &playername,
1288 const std::string &password, std::string *address, u16 port)
1290 showOverlayMessage("Creating client...", 0, 10);
1292 draw_control = new MapDrawControl;
1296 bool could_connect, connect_aborted;
1297 #ifdef HAVE_TOUCHSCREENGUI
1298 if (g_touchscreengui) {
1299 g_touchscreengui->init(texture_src);
1300 g_touchscreengui->hide();
1303 if (!connectToServer(playername, password, address, port,
1304 &could_connect, &connect_aborted))
1307 if (!could_connect) {
1308 if (error_message->empty() && !connect_aborted) {
1309 // Should not happen if error messages are set properly
1310 *error_message = "Connection failed for unknown reason";
1311 errorstream << *error_message << std::endl;
1316 if (!getServerContent(&connect_aborted)) {
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 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1326 &m_flags.force_fog_off, &runData.fog_range, client);
1327 shader_src->addShaderConstantSetterFactory(scsf);
1329 // Update cached textures, meshes and materials
1330 client->afterContentReceived();
1334 camera = new Camera(*draw_control, client);
1335 if (!camera || !camera->successfullyCreated(*error_message))
1337 client->setCamera(camera);
1341 if (m_cache_enable_clouds) {
1342 clouds = new Clouds(smgr, -1, time(0));
1344 *error_message = "Memory allocation error (clouds)";
1345 errorstream << *error_message << std::endl;
1352 sky = new Sky(-1, texture_src);
1354 skybox = NULL; // This is used/set later on in the main run loop
1356 local_inventory = new Inventory(itemdef_manager);
1358 if (!(sky && local_inventory)) {
1359 *error_message = "Memory allocation error (sky or local inventory)";
1360 errorstream << *error_message << std::endl;
1364 /* Pre-calculated values
1366 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1368 v2u32 size = t->getOriginalSize();
1369 crack_animation_length = size.Y / size.X;
1371 crack_animation_length = 5;
1377 /* Set window caption
1379 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1381 str += utf8_to_wide(g_version_hash);
1383 str += driver->getName();
1385 device->setWindowCaption(str.c_str());
1387 LocalPlayer *player = client->getEnv().getLocalPlayer();
1388 player->hurt_tilt_timer = 0;
1389 player->hurt_tilt_strength = 0;
1391 hud = new Hud(guienv, client, player, local_inventory);
1394 *error_message = "Memory error: could not create HUD";
1395 errorstream << *error_message << std::endl;
1399 mapper = client->getMinimap();
1401 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1406 bool Game::initGui()
1410 // Remove stale "recent" chat messages from previous connections
1411 chat_backend->clearRecentChat();
1413 // Make sure the size of the recent messages buffer is right
1414 chat_backend->applySettings();
1416 // Chat backend and console
1417 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
1418 -1, chat_backend, client, &g_menumgr);
1419 if (!gui_chat_console) {
1420 *error_message = "Could not allocate memory for chat console";
1421 errorstream << *error_message << std::endl;
1425 #ifdef HAVE_TOUCHSCREENGUI
1427 if (g_touchscreengui)
1428 g_touchscreengui->show();
1435 bool Game::connectToServer(const std::string &playername,
1436 const std::string &password, std::string *address, u16 port,
1437 bool *connect_ok, bool *connection_aborted)
1439 *connect_ok = false; // Let's not be overly optimistic
1440 *connection_aborted = false;
1441 bool local_server_mode = false;
1443 showOverlayMessage("Resolving address...", 0, 15);
1445 Address connect_address(0, 0, 0, 0, port);
1448 connect_address.Resolve(address->c_str());
1450 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1451 //connect_address.Resolve("localhost");
1452 if (connect_address.isIPv6()) {
1453 IPv6AddressBytes addr_bytes;
1454 addr_bytes.bytes[15] = 1;
1455 connect_address.setAddress(&addr_bytes);
1457 connect_address.setAddress(127, 0, 0, 1);
1459 local_server_mode = true;
1461 } catch (ResolveError &e) {
1462 *error_message = std::string("Couldn't resolve address: ") + e.what();
1463 errorstream << *error_message << std::endl;
1467 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1468 *error_message = "Unable to connect to " +
1469 connect_address.serializeString() +
1470 " because IPv6 is disabled";
1471 errorstream << *error_message << std::endl;
1475 client = new Client(playername.c_str(), password, *address,
1476 *draw_control, texture_src, shader_src,
1477 itemdef_manager, nodedef_manager, sound, eventmgr,
1478 connect_address.isIPv6(), m_game_ui.get());
1483 client->m_simple_singleplayer_mode = simple_singleplayer_mode;
1485 infostream << "Connecting to server at ";
1486 connect_address.print(&infostream);
1487 infostream << std::endl;
1489 client->connect(connect_address,
1490 simple_singleplayer_mode || local_server_mode);
1493 Wait for server to accept connection
1499 FpsControl fps_control = { 0 };
1501 f32 wait_time = 0; // in seconds
1503 fps_control.last_time = RenderingEngine::get_timer_time();
1505 while (RenderingEngine::run()) {
1507 limitFps(&fps_control, &dtime);
1509 // Update client and server
1510 client->step(dtime);
1513 server->step(dtime);
1516 if (client->getState() == LC_Init) {
1522 if (*connection_aborted)
1525 if (client->accessDenied()) {
1526 *error_message = "Access denied. Reason: "
1527 + client->accessDeniedReason();
1528 *reconnect_requested = client->reconnectRequested();
1529 errorstream << *error_message << std::endl;
1533 if (input->cancelPressed()) {
1534 *connection_aborted = true;
1535 infostream << "Connect aborted [Escape]" << std::endl;
1539 if (client->m_is_registration_confirmation_state) {
1540 if (registration_confirmation_shown) {
1541 // Keep drawing the GUI
1542 RenderingEngine::draw_menu_scene(guienv, dtime, true);
1544 registration_confirmation_shown = true;
1545 (new GUIConfirmRegistration(guienv, guienv->getRootGUIElement(), -1,
1546 &g_menumgr, client, playername, password, *address, connection_aborted))->drop();
1550 // Only time out if we aren't waiting for the server we started
1551 if (!address->empty() && wait_time > 10) {
1552 *error_message = "Connection timed out.";
1553 errorstream << *error_message << std::endl;
1558 showOverlayMessage("Connecting to server...", dtime, 20);
1561 } catch (con::PeerNotFoundException &e) {
1562 // TODO: Should something be done here? At least an info/error
1570 bool Game::getServerContent(bool *aborted)
1574 FpsControl fps_control = { 0 };
1575 f32 dtime; // in seconds
1577 fps_control.last_time = RenderingEngine::get_timer_time();
1579 while (RenderingEngine::run()) {
1581 limitFps(&fps_control, &dtime);
1583 // Update client and server
1584 client->step(dtime);
1587 server->step(dtime);
1590 if (client->mediaReceived() && client->itemdefReceived() &&
1591 client->nodedefReceived()) {
1596 if (!checkConnection())
1599 if (client->getState() < LC_Init) {
1600 *error_message = "Client disconnected";
1601 errorstream << *error_message << std::endl;
1605 if (input->cancelPressed()) {
1607 infostream << "Connect aborted [Escape]" << std::endl;
1614 if (!client->itemdefReceived()) {
1615 const wchar_t *text = wgettext("Item definitions...");
1617 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1620 } else if (!client->nodedefReceived()) {
1621 const wchar_t *text = wgettext("Node definitions...");
1623 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1627 std::stringstream message;
1628 std::fixed(message);
1629 message.precision(0);
1630 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
1631 message.precision(2);
1633 if ((USE_CURL == 0) ||
1634 (!g_settings->getBool("enable_remote_media_server"))) {
1635 float cur = client->getCurRate();
1636 std::string cur_unit = gettext("KiB/s");
1640 cur_unit = gettext("MiB/s");
1643 message << " (" << cur << ' ' << cur_unit << ")";
1646 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
1647 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
1648 texture_src, dtime, progress);
1656 /****************************************************************************/
1657 /****************************************************************************
1659 ****************************************************************************/
1660 /****************************************************************************/
1662 inline void Game::updateInteractTimers(f32 dtime)
1664 if (runData.nodig_delay_timer >= 0)
1665 runData.nodig_delay_timer -= dtime;
1667 if (runData.object_hit_delay_timer >= 0)
1668 runData.object_hit_delay_timer -= dtime;
1670 runData.time_from_last_punch += dtime;
1674 /* returns false if game should exit, otherwise true
1676 inline bool Game::checkConnection()
1678 if (client->accessDenied()) {
1679 *error_message = "Access denied. Reason: "
1680 + client->accessDeniedReason();
1681 *reconnect_requested = client->reconnectRequested();
1682 errorstream << *error_message << std::endl;
1690 /* returns false if game should exit, otherwise true
1692 inline bool Game::handleCallbacks()
1694 if (g_gamecallback->disconnect_requested) {
1695 g_gamecallback->disconnect_requested = false;
1699 if (g_gamecallback->changepassword_requested) {
1700 (new GUIPasswordChange(guienv, guiroot, -1,
1701 &g_menumgr, client))->drop();
1702 g_gamecallback->changepassword_requested = false;
1705 if (g_gamecallback->changevolume_requested) {
1706 (new GUIVolumeChange(guienv, guiroot, -1,
1707 &g_menumgr))->drop();
1708 g_gamecallback->changevolume_requested = false;
1711 if (g_gamecallback->keyconfig_requested) {
1712 (new GUIKeyChangeMenu(guienv, guiroot, -1,
1713 &g_menumgr))->drop();
1714 g_gamecallback->keyconfig_requested = false;
1717 if (g_gamecallback->keyconfig_changed) {
1718 input->keycache.populate(); // update the cache with new settings
1719 g_gamecallback->keyconfig_changed = false;
1726 void Game::processQueues()
1728 texture_src->processQueue();
1729 itemdef_manager->processQueue(client);
1730 shader_src->processQueue();
1734 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
1736 float profiler_print_interval =
1737 g_settings->getFloat("profiler_print_interval");
1738 bool print_to_log = true;
1740 if (profiler_print_interval == 0) {
1741 print_to_log = false;
1742 profiler_print_interval = 5;
1745 if (profiler_interval.step(dtime, profiler_print_interval)) {
1747 infostream << "Profiler:" << std::endl;
1748 g_profiler->print(infostream);
1751 m_game_ui->updateProfiler();
1752 g_profiler->clear();
1755 addProfilerGraphs(stats, draw_times, dtime);
1759 void Game::addProfilerGraphs(const RunStats &stats,
1760 const FpsControl &draw_times, f32 dtime)
1762 g_profiler->graphAdd("mainloop_other",
1763 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
1765 if (draw_times.sleep_time != 0)
1766 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
1767 g_profiler->graphAdd("mainloop_dtime", dtime);
1769 g_profiler->add("Elapsed time", dtime);
1770 g_profiler->avg("FPS", 1. / dtime);
1774 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
1781 /* Time average and jitter calculation
1783 jp = &stats->dtime_jitter;
1784 jp->avg = jp->avg * 0.96 + dtime * 0.04;
1786 jitter = dtime - jp->avg;
1788 if (jitter > jp->max)
1791 jp->counter += dtime;
1793 if (jp->counter > 0.0) {
1795 jp->max_sample = jp->max;
1796 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
1800 /* Busytime average and jitter calculation
1802 jp = &stats->busy_time_jitter;
1803 jp->avg = jp->avg + draw_times.busy_time * 0.02;
1805 jitter = draw_times.busy_time - jp->avg;
1807 if (jitter > jp->max)
1809 if (jitter < jp->min)
1812 jp->counter += dtime;
1814 if (jp->counter > 0.0) {
1816 jp->max_sample = jp->max;
1817 jp->min_sample = jp->min;
1825 /****************************************************************************
1827 ****************************************************************************/
1829 void Game::processUserInput(f32 dtime)
1831 // Reset input if window not active or some menu is active
1832 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
1834 #ifdef HAVE_TOUCHSCREENGUI
1835 g_touchscreengui->hide();
1838 #ifdef HAVE_TOUCHSCREENGUI
1839 else if (g_touchscreengui) {
1840 /* on touchscreengui step may generate own input events which ain't
1841 * what we want in case we just did clear them */
1842 g_touchscreengui->step(dtime);
1846 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
1847 gui_chat_console->closeConsoleAtOnce();
1850 // Input handler step() (used by the random input generator)
1854 if (current_formspec != NULL)
1855 current_formspec->getAndroidUIInput();
1857 handleAndroidChatInput();
1860 // Increase timer for double tap of "keymap_jump"
1861 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
1862 runData.jump_timer += dtime;
1865 processItemSelection(&runData.new_playeritem);
1869 void Game::processKeyInput()
1871 if (wasKeyDown(KeyType::DROP)) {
1872 dropSelectedItem(isKeyDown(KeyType::SNEAK));
1873 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
1874 toggleAutoforward();
1875 } else if (wasKeyDown(KeyType::BACKWARD)) {
1876 if (g_settings->getBool("continuous_forward"))
1877 toggleAutoforward();
1878 } else if (wasKeyDown(KeyType::INVENTORY)) {
1880 } else if (input->cancelPressed()) {
1881 if (!gui_chat_console->isOpenInhibited()) {
1884 } else if (wasKeyDown(KeyType::CHAT)) {
1885 openConsole(0.2, L"");
1886 } else if (wasKeyDown(KeyType::CMD)) {
1887 openConsole(0.2, L"/");
1888 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
1889 if (client->moddingEnabled())
1890 openConsole(0.2, L".");
1892 m_game_ui->showStatusText(wgettext("CSM is disabled"));
1893 } else if (wasKeyDown(KeyType::CONSOLE)) {
1894 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
1895 } else if (wasKeyDown(KeyType::FREEMOVE)) {
1897 } else if (wasKeyDown(KeyType::JUMP)) {
1898 toggleFreeMoveAlt();
1899 } else if (wasKeyDown(KeyType::FASTMOVE)) {
1901 } else if (wasKeyDown(KeyType::NOCLIP)) {
1903 } else if (wasKeyDown(KeyType::MUTE)) {
1904 bool new_mute_sound = !g_settings->getBool("mute_sound");
1905 g_settings->setBool("mute_sound", new_mute_sound);
1907 m_game_ui->showTranslatedStatusText("Sound muted");
1909 m_game_ui->showTranslatedStatusText("Sound unmuted");
1910 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
1911 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
1913 g_settings->setFloat("sound_volume", new_volume);
1914 const wchar_t *str = wgettext("Volume changed to %d%%");
1915 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1917 m_game_ui->showStatusText(buf);
1918 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
1919 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
1921 g_settings->setFloat("sound_volume", new_volume);
1922 const wchar_t *str = wgettext("Volume changed to %d%%");
1923 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1925 m_game_ui->showStatusText(buf);
1926 } else if (wasKeyDown(KeyType::CINEMATIC)) {
1928 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
1929 client->makeScreenshot();
1930 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
1931 m_game_ui->toggleHud();
1932 } else if (wasKeyDown(KeyType::MINIMAP)) {
1933 toggleMinimap(isKeyDown(KeyType::SNEAK));
1934 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
1935 m_game_ui->toggleChat();
1936 } else if (wasKeyDown(KeyType::TOGGLE_FOG)) {
1938 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
1939 toggleUpdateCamera();
1940 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
1942 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
1943 m_game_ui->toggleProfiler();
1944 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
1945 increaseViewRange();
1946 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
1947 decreaseViewRange();
1948 } else if (wasKeyDown(KeyType::RANGESELECT)) {
1949 toggleFullViewRange();
1950 } else if (wasKeyDown(KeyType::ZOOM)) {
1952 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
1954 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
1956 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
1958 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
1962 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
1963 runData.reset_jump_timer = false;
1964 runData.jump_timer = 0.0f;
1967 if (quicktune->hasMessage()) {
1968 m_game_ui->showStatusText(utf8_to_wide(quicktune->getMessage()));
1972 void Game::processItemSelection(u16 *new_playeritem)
1974 LocalPlayer *player = client->getEnv().getLocalPlayer();
1976 /* Item selection using mouse wheel
1978 *new_playeritem = client->getPlayerItem();
1980 s32 wheel = input->getMouseWheel();
1981 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
1982 player->hud_hotbar_itemcount - 1);
1986 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
1987 wasKeyDown(KeyType::HOTBAR_NEXT)) {
1991 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
1992 wasKeyDown(KeyType::HOTBAR_PREV)) {
1997 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
1999 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2002 /* Item selection using hotbar slot keys
2004 for (u16 i = 0; i < 23; i++) {
2005 if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
2006 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2007 *new_playeritem = i;
2008 infostream << "Selected item: " << new_playeritem << std::endl;
2016 void Game::dropSelectedItem(bool single_item)
2018 IDropAction *a = new IDropAction();
2019 a->count = single_item ? 1 : 0;
2020 a->from_inv.setCurrentPlayer();
2021 a->from_list = "main";
2022 a->from_i = client->getPlayerItem();
2023 client->inventoryAction(a);
2027 void Game::openInventory()
2030 * Don't permit to open inventory is CAO or player doesn't exists.
2031 * This prevent showing an empty inventory at player load
2034 LocalPlayer *player = client->getEnv().getLocalPlayer();
2035 if (!player || !player->getCAO())
2038 infostream << "the_game: " << "Launching inventory" << std::endl;
2040 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2042 InventoryLocation inventoryloc;
2043 inventoryloc.setCurrentPlayer();
2045 if (!client->moddingEnabled()
2046 || !client->getScript()->on_inventory_open(fs_src->m_client->getInventory(inventoryloc))) {
2047 TextDest *txt_dst = new TextDestPlayerInventory(client);
2048 GUIFormSpecMenu::create(current_formspec, client, &input->joystick, fs_src,
2049 txt_dst, client->getFormspecPrepend());
2051 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2056 void Game::openConsole(float scale, const wchar_t *line)
2058 assert(scale > 0.0f && scale <= 1.0f);
2061 porting::showInputDialog(gettext("ok"), "", "", 2);
2062 m_android_chat_open = true;
2064 if (gui_chat_console->isOpenInhibited())
2066 gui_chat_console->openConsole(scale);
2068 gui_chat_console->setCloseOnEnter(true);
2069 gui_chat_console->replaceAndAddToHistory(line);
2075 void Game::handleAndroidChatInput()
2077 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2078 std::string text = porting::getInputDialogValue();
2079 client->typeChatMessage(utf8_to_wide(text));
2085 void Game::toggleFreeMove()
2087 bool free_move = !g_settings->getBool("free_move");
2088 g_settings->set("free_move", bool_to_cstr(free_move));
2091 if (client->checkPrivilege("fly")) {
2092 m_game_ui->showTranslatedStatusText("Fly mode enabled");
2094 m_game_ui->showTranslatedStatusText("Fly mode enabled (note: no 'fly' privilege)");
2097 m_game_ui->showTranslatedStatusText("Fly mode disabled");
2101 void Game::toggleFreeMoveAlt()
2103 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2106 runData.reset_jump_timer = true;
2110 void Game::toggleFast()
2112 bool fast_move = !g_settings->getBool("fast_move");
2113 bool has_fast_privs = client->checkPrivilege("fast");
2114 g_settings->set("fast_move", bool_to_cstr(fast_move));
2117 if (has_fast_privs) {
2118 m_game_ui->showTranslatedStatusText("Fast mode enabled");
2120 m_game_ui->showTranslatedStatusText("Fast mode enabled (note: no 'fast' privilege)");
2123 m_game_ui->showTranslatedStatusText("Fast mode disabled");
2127 m_cache_hold_aux1 = fast_move && has_fast_privs;
2132 void Game::toggleNoClip()
2134 bool noclip = !g_settings->getBool("noclip");
2135 g_settings->set("noclip", bool_to_cstr(noclip));
2138 if (client->checkPrivilege("noclip")) {
2139 m_game_ui->showTranslatedStatusText("Noclip mode enabled");
2141 m_game_ui->showTranslatedStatusText("Noclip mode enabled (note: no 'noclip' privilege)");
2144 m_game_ui->showTranslatedStatusText("Noclip mode disabled");
2148 void Game::toggleCinematic()
2150 bool cinematic = !g_settings->getBool("cinematic");
2151 g_settings->set("cinematic", bool_to_cstr(cinematic));
2154 m_game_ui->showTranslatedStatusText("Cinematic mode enabled");
2156 m_game_ui->showTranslatedStatusText("Cinematic mode disabled");
2159 // Autoforward by toggling continuous forward.
2160 void Game::toggleAutoforward()
2162 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2163 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2165 if (autorun_enabled)
2166 m_game_ui->showTranslatedStatusText("Automatic forwards enabled");
2168 m_game_ui->showTranslatedStatusText("Automatic forwards disabled");
2171 void Game::toggleMinimap(bool shift_pressed)
2173 if (!mapper || !m_game_ui->m_flags.show_hud || !g_settings->getBool("enable_minimap"))
2176 if (shift_pressed) {
2177 mapper->toggleMinimapShape();
2181 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2183 MinimapMode mode = MINIMAP_MODE_OFF;
2184 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2185 mode = mapper->getMinimapMode();
2186 mode = (MinimapMode)((int)mode + 1);
2187 // If radar is disabled and in, or switching to, radar mode
2188 if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE) && mode > 3)
2189 mode = MINIMAP_MODE_OFF;
2192 m_game_ui->m_flags.show_minimap = true;
2194 case MINIMAP_MODE_SURFACEx1:
2195 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1");
2197 case MINIMAP_MODE_SURFACEx2:
2198 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2");
2200 case MINIMAP_MODE_SURFACEx4:
2201 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4");
2203 case MINIMAP_MODE_RADARx1:
2204 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1");
2206 case MINIMAP_MODE_RADARx2:
2207 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2");
2209 case MINIMAP_MODE_RADARx4:
2210 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4");
2213 mode = MINIMAP_MODE_OFF;
2214 m_game_ui->m_flags.show_minimap = false;
2215 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE)
2216 m_game_ui->showTranslatedStatusText("Minimap hidden");
2218 m_game_ui->showTranslatedStatusText("Minimap currently disabled by game or mod");
2221 mapper->setMinimapMode(mode);
2224 void Game::toggleFog()
2226 bool fog_enabled = g_settings->getBool("enable_fog");
2227 g_settings->setBool("enable_fog", !fog_enabled);
2229 m_game_ui->showTranslatedStatusText("Fog disabled");
2231 m_game_ui->showTranslatedStatusText("Fog enabled");
2235 void Game::toggleDebug()
2237 // Initial / 4x toggle: Chat only
2238 // 1x toggle: Debug text with chat
2239 // 2x toggle: Debug text with profiler graph
2240 // 3x toggle: Debug text and wireframe
2241 if (!m_game_ui->m_flags.show_debug) {
2242 m_game_ui->m_flags.show_debug = true;
2243 m_game_ui->m_flags.show_profiler_graph = false;
2244 draw_control->show_wireframe = false;
2245 m_game_ui->showTranslatedStatusText("Debug info shown");
2246 } else if (!m_game_ui->m_flags.show_profiler_graph && !draw_control->show_wireframe) {
2247 m_game_ui->m_flags.show_profiler_graph = true;
2248 m_game_ui->showTranslatedStatusText("Profiler graph shown");
2249 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2250 m_game_ui->m_flags.show_profiler_graph = false;
2251 draw_control->show_wireframe = true;
2252 m_game_ui->showTranslatedStatusText("Wireframe shown");
2254 m_game_ui->m_flags.show_debug = false;
2255 m_game_ui->m_flags.show_profiler_graph = false;
2256 draw_control->show_wireframe = false;
2257 if (client->checkPrivilege("debug")) {
2258 m_game_ui->showTranslatedStatusText("Debug info, profiler graph, and wireframe hidden");
2260 m_game_ui->showTranslatedStatusText("Debug info and profiler graph hidden");
2266 void Game::toggleUpdateCamera()
2268 m_flags.disable_camera_update = !m_flags.disable_camera_update;
2269 if (m_flags.disable_camera_update)
2270 m_game_ui->showTranslatedStatusText("Camera update disabled");
2272 m_game_ui->showTranslatedStatusText("Camera update enabled");
2276 void Game::increaseViewRange()
2278 s16 range = g_settings->getS16("viewing_range");
2279 s16 range_new = range + 10;
2283 if (range_new > 4000) {
2285 str = wgettext("Viewing range is at maximum: %d");
2286 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2288 m_game_ui->showStatusText(buf);
2291 str = wgettext("Viewing range changed to %d");
2292 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2294 m_game_ui->showStatusText(buf);
2296 g_settings->set("viewing_range", itos(range_new));
2300 void Game::decreaseViewRange()
2302 s16 range = g_settings->getS16("viewing_range");
2303 s16 range_new = range - 10;
2307 if (range_new < 20) {
2309 str = wgettext("Viewing range is at minimum: %d");
2310 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2312 m_game_ui->showStatusText(buf);
2314 str = wgettext("Viewing range changed to %d");
2315 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2317 m_game_ui->showStatusText(buf);
2319 g_settings->set("viewing_range", itos(range_new));
2323 void Game::toggleFullViewRange()
2325 draw_control->range_all = !draw_control->range_all;
2326 if (draw_control->range_all)
2327 m_game_ui->showTranslatedStatusText("Enabled unlimited viewing range");
2329 m_game_ui->showTranslatedStatusText("Disabled unlimited viewing range");
2333 void Game::checkZoomEnabled()
2335 LocalPlayer *player = client->getEnv().getLocalPlayer();
2336 if (player->getZoomFOV() < 0.001f)
2337 m_game_ui->showTranslatedStatusText("Zoom currently disabled by game or mod");
2341 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2343 if ((device->isWindowActive() && device->isWindowFocused()
2344 && !isMenuActive()) || random_input) {
2347 if (!random_input) {
2348 // Mac OSX gets upset if this is set every frame
2349 if (device->getCursorControl()->isVisible())
2350 device->getCursorControl()->setVisible(false);
2354 if (m_first_loop_after_window_activation) {
2355 m_first_loop_after_window_activation = false;
2357 input->setMousePos(driver->getScreenSize().Width / 2,
2358 driver->getScreenSize().Height / 2);
2360 updateCameraOrientation(cam, dtime);
2366 // Mac OSX gets upset if this is set every frame
2367 if (!device->getCursorControl()->isVisible())
2368 device->getCursorControl()->setVisible(true);
2371 m_first_loop_after_window_activation = true;
2376 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2378 #ifdef HAVE_TOUCHSCREENGUI
2379 if (g_touchscreengui) {
2380 cam->camera_yaw += g_touchscreengui->getYawChange();
2381 cam->camera_pitch = g_touchscreengui->getPitch();
2384 v2s32 center(driver->getScreenSize().Width / 2, driver->getScreenSize().Height / 2);
2385 v2s32 dist = input->getMousePos() - center;
2387 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2391 cam->camera_yaw -= dist.X * m_cache_mouse_sensitivity;
2392 cam->camera_pitch += dist.Y * m_cache_mouse_sensitivity;
2394 if (dist.X != 0 || dist.Y != 0)
2395 input->setMousePos(center.X, center.Y);
2396 #ifdef HAVE_TOUCHSCREENGUI
2400 if (m_cache_enable_joysticks) {
2401 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
2402 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
2403 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
2406 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2410 void Game::updatePlayerControl(const CameraOrientation &cam)
2412 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2414 // DO NOT use the isKeyDown method for the forward, backward, left, right
2415 // buttons, as the code that uses the controls needs to be able to
2416 // distinguish between the two in order to know when to use joysticks.
2418 PlayerControl control(
2419 input->isKeyDown(KeyType::FORWARD),
2420 input->isKeyDown(KeyType::BACKWARD),
2421 input->isKeyDown(KeyType::LEFT),
2422 input->isKeyDown(KeyType::RIGHT),
2423 isKeyDown(KeyType::JUMP),
2424 isKeyDown(KeyType::SPECIAL1),
2425 isKeyDown(KeyType::SNEAK),
2426 isKeyDown(KeyType::ZOOM),
2427 input->getLeftState(),
2428 input->getRightState(),
2431 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
2432 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
2436 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
2437 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
2438 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
2439 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
2440 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
2441 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
2442 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
2443 ( (u32)(input->getLeftState() & 0x1) << 7) |
2444 ( (u32)(input->getRightState() & 0x1) << 8
2448 /* For Android, simulate holding down AUX1 (fast move) if the user has
2449 * the fast_move setting toggled on. If there is an aux1 key defined for
2450 * Android then its meaning is inverted (i.e. holding aux1 means walk and
2453 if (m_cache_hold_aux1) {
2454 control.aux1 = control.aux1 ^ true;
2455 keypress_bits ^= ((u32)(1U << 5));
2459 LocalPlayer *player = client->getEnv().getLocalPlayer();
2461 // autojump if set: simulate "jump" key
2462 if (player->getAutojump()) {
2463 control.jump = true;
2464 keypress_bits |= 1U << 4;
2467 client->setPlayerControl(control);
2468 player->keyPressed = keypress_bits;
2474 inline void Game::step(f32 *dtime)
2476 bool can_be_and_is_paused =
2477 (simple_singleplayer_mode && g_menumgr.pausesGame());
2479 if (can_be_and_is_paused) { // This is for a singleplayer server
2480 *dtime = 0; // No time passes
2483 server->step(*dtime);
2485 client->step(*dtime);
2489 const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = {
2490 {&Game::handleClientEvent_None},
2491 {&Game::handleClientEvent_PlayerDamage},
2492 {&Game::handleClientEvent_PlayerForceMove},
2493 {&Game::handleClientEvent_Deathscreen},
2494 {&Game::handleClientEvent_ShowFormSpec},
2495 {&Game::handleClientEvent_ShowLocalFormSpec},
2496 {&Game::handleClientEvent_HandleParticleEvent},
2497 {&Game::handleClientEvent_HandleParticleEvent},
2498 {&Game::handleClientEvent_HandleParticleEvent},
2499 {&Game::handleClientEvent_HudAdd},
2500 {&Game::handleClientEvent_HudRemove},
2501 {&Game::handleClientEvent_HudChange},
2502 {&Game::handleClientEvent_SetSky},
2503 {&Game::handleClientEvent_OverrideDayNigthRatio},
2504 {&Game::handleClientEvent_CloudParams},
2507 void Game::handleClientEvent_None(ClientEvent *event, CameraOrientation *cam)
2509 FATAL_ERROR("ClientEvent type None received");
2512 void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam)
2514 if (client->moddingEnabled()) {
2515 client->getScript()->on_damage_taken(event->player_damage.amount);
2518 // Damage flash and hurt tilt are not used at death
2519 if (client->getHP() > 0) {
2520 runData.damage_flash += 95.0f + 3.2f * event->player_damage.amount;
2521 runData.damage_flash = MYMIN(runData.damage_flash, 127.0f);
2523 LocalPlayer *player = client->getEnv().getLocalPlayer();
2525 player->hurt_tilt_timer = 1.5f;
2526 player->hurt_tilt_strength =
2527 rangelim(event->player_damage.amount / 4.0f, 1.0f, 4.0f);
2530 // Play damage sound
2531 client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::PLAYER_DAMAGE));
2534 void Game::handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam)
2536 cam->camera_yaw = event->player_force_move.yaw;
2537 cam->camera_pitch = event->player_force_move.pitch;
2540 void Game::handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam)
2542 // If CSM enabled, deathscreen is handled by CSM code in
2543 // builtin/client/init.lua
2544 if (client->moddingEnabled())
2545 client->getScript()->on_death();
2547 showDeathFormspec();
2549 /* Handle visualization */
2550 LocalPlayer *player = client->getEnv().getLocalPlayer();
2551 runData.damage_flash = 0;
2552 player->hurt_tilt_timer = 0;
2553 player->hurt_tilt_strength = 0;
2556 void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam)
2558 if (event->show_formspec.formspec->empty()) {
2559 if (current_formspec && (event->show_formspec.formname->empty()
2560 || *(event->show_formspec.formname) == cur_formname)) {
2561 current_formspec->quitMenu();
2564 FormspecFormSource *fs_src =
2565 new FormspecFormSource(*(event->show_formspec.formspec));
2566 TextDestPlayerInventory *txt_dst =
2567 new TextDestPlayerInventory(client, *(event->show_formspec.formname));
2569 GUIFormSpecMenu::create(current_formspec, client, &input->joystick,
2570 fs_src, txt_dst, client->getFormspecPrepend());
2571 cur_formname = *(event->show_formspec.formname);
2574 delete event->show_formspec.formspec;
2575 delete event->show_formspec.formname;
2578 void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam)
2580 FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec);
2581 LocalFormspecHandler *txt_dst =
2582 new LocalFormspecHandler(*event->show_formspec.formname, client);
2583 GUIFormSpecMenu::create(current_formspec, client, &input->joystick,
2584 fs_src, txt_dst, client->getFormspecPrepend());
2586 delete event->show_formspec.formspec;
2587 delete event->show_formspec.formname;
2590 void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event,
2591 CameraOrientation *cam)
2593 LocalPlayer *player = client->getEnv().getLocalPlayer();
2594 client->getParticleManager()->handleParticleEvent(event, client, player);
2597 void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
2599 LocalPlayer *player = client->getEnv().getLocalPlayer();
2600 auto &hud_server_to_client = client->getHUDTranslationMap();
2602 u32 server_id = event->hudadd.server_id;
2603 // ignore if we already have a HUD with that ID
2604 auto i = hud_server_to_client.find(server_id);
2605 if (i != hud_server_to_client.end()) {
2606 delete event->hudadd.pos;
2607 delete event->hudadd.name;
2608 delete event->hudadd.scale;
2609 delete event->hudadd.text;
2610 delete event->hudadd.align;
2611 delete event->hudadd.offset;
2612 delete event->hudadd.world_pos;
2613 delete event->hudadd.size;
2617 HudElement *e = new HudElement;
2618 e->type = (HudElementType)event->hudadd.type;
2619 e->pos = *event->hudadd.pos;
2620 e->name = *event->hudadd.name;
2621 e->scale = *event->hudadd.scale;
2622 e->text = *event->hudadd.text;
2623 e->number = event->hudadd.number;
2624 e->item = event->hudadd.item;
2625 e->dir = event->hudadd.dir;
2626 e->align = *event->hudadd.align;
2627 e->offset = *event->hudadd.offset;
2628 e->world_pos = *event->hudadd.world_pos;
2629 e->size = *event->hudadd.size;
2630 hud_server_to_client[server_id] = player->addHud(e);
2632 delete event->hudadd.pos;
2633 delete event->hudadd.name;
2634 delete event->hudadd.scale;
2635 delete event->hudadd.text;
2636 delete event->hudadd.align;
2637 delete event->hudadd.offset;
2638 delete event->hudadd.world_pos;
2639 delete event->hudadd.size;
2642 void Game::handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam)
2644 LocalPlayer *player = client->getEnv().getLocalPlayer();
2645 HudElement *e = player->removeHud(event->hudrm.id);
2649 void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam)
2651 LocalPlayer *player = client->getEnv().getLocalPlayer();
2653 u32 id = event->hudchange.id;
2654 HudElement *e = player->getHud(id);
2657 delete event->hudchange.v3fdata;
2658 delete event->hudchange.v2fdata;
2659 delete event->hudchange.sdata;
2660 delete event->hudchange.v2s32data;
2664 switch (event->hudchange.stat) {
2666 e->pos = *event->hudchange.v2fdata;
2670 e->name = *event->hudchange.sdata;
2673 case HUD_STAT_SCALE:
2674 e->scale = *event->hudchange.v2fdata;
2678 e->text = *event->hudchange.sdata;
2681 case HUD_STAT_NUMBER:
2682 e->number = event->hudchange.data;
2686 e->item = event->hudchange.data;
2690 e->dir = event->hudchange.data;
2693 case HUD_STAT_ALIGN:
2694 e->align = *event->hudchange.v2fdata;
2697 case HUD_STAT_OFFSET:
2698 e->offset = *event->hudchange.v2fdata;
2701 case HUD_STAT_WORLD_POS:
2702 e->world_pos = *event->hudchange.v3fdata;
2706 e->size = *event->hudchange.v2s32data;
2710 delete event->hudchange.v3fdata;
2711 delete event->hudchange.v2fdata;
2712 delete event->hudchange.sdata;
2713 delete event->hudchange.v2s32data;
2716 void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
2718 sky->setVisible(false);
2719 // Whether clouds are visible in front of a custom skybox
2720 sky->setCloudsEnabled(event->set_sky.clouds);
2727 // Handle according to type
2728 if (*event->set_sky.type == "regular") {
2729 sky->setVisible(true);
2730 sky->setCloudsEnabled(true);
2731 } else if (*event->set_sky.type == "skybox" &&
2732 event->set_sky.params->size() == 6) {
2733 sky->setFallbackBgColor(*event->set_sky.bgcolor);
2734 skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
2735 texture_src->getTextureForMesh((*event->set_sky.params)[0]),
2736 texture_src->getTextureForMesh((*event->set_sky.params)[1]),
2737 texture_src->getTextureForMesh((*event->set_sky.params)[2]),
2738 texture_src->getTextureForMesh((*event->set_sky.params)[3]),
2739 texture_src->getTextureForMesh((*event->set_sky.params)[4]),
2740 texture_src->getTextureForMesh((*event->set_sky.params)[5]));
2742 // Handle everything else as plain color
2744 if (*event->set_sky.type != "plain")
2745 infostream << "Unknown sky type: "
2746 << (*event->set_sky.type) << std::endl;
2748 sky->setFallbackBgColor(*event->set_sky.bgcolor);
2751 delete event->set_sky.bgcolor;
2752 delete event->set_sky.type;
2753 delete event->set_sky.params;
2756 void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
2757 CameraOrientation *cam)
2759 client->getEnv().setDayNightRatioOverride(
2760 event->override_day_night_ratio.do_override,
2761 event->override_day_night_ratio.ratio_f * 1000.0f);
2764 void Game::handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam)
2769 clouds->setDensity(event->cloud_params.density);
2770 clouds->setColorBright(video::SColor(event->cloud_params.color_bright));
2771 clouds->setColorAmbient(video::SColor(event->cloud_params.color_ambient));
2772 clouds->setHeight(event->cloud_params.height);
2773 clouds->setThickness(event->cloud_params.thickness);
2774 clouds->setSpeed(v2f(event->cloud_params.speed_x, event->cloud_params.speed_y));
2777 void Game::processClientEvents(CameraOrientation *cam)
2779 while (client->hasClientEvents()) {
2780 std::unique_ptr<ClientEvent> event(client->getClientEvent());
2781 FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, "Invalid clientevent type");
2782 const ClientEventHandler& evHandler = clientEventHandler[event->type];
2783 (this->*evHandler.handler)(event.get(), cam);
2787 void Game::updateChat(f32 dtime, const v2u32 &screensize)
2789 // Add chat log output for errors to be shown in chat
2790 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
2792 // Get new messages from error log buffer
2793 while (!chat_log_error_buf.empty()) {
2794 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
2795 if (!g_settings->getBool("disable_escape_sequences")) {
2796 error_message.insert(0, L"\x1b(c@red)");
2797 error_message.append(L"\x1b(c@white)");
2799 chat_backend->addMessage(L"", error_message);
2802 // Get new messages from client
2803 std::wstring message;
2804 while (client->getChatMessage(message)) {
2805 chat_backend->addUnparsedMessage(message);
2808 // Remove old messages
2809 chat_backend->step(dtime);
2811 // Display all messages in a static text element
2812 m_game_ui->setChatText(chat_backend->getRecentChat(),
2813 chat_backend->getRecentBuffer().getLineCount());
2816 void Game::updateCamera(u32 busy_time, f32 dtime)
2818 LocalPlayer *player = client->getEnv().getLocalPlayer();
2821 For interaction purposes, get info about the held item
2823 - Is it a usable item?
2824 - Can it point to liquids?
2826 ItemStack playeritem;
2828 InventoryList *mlist = local_inventory->getList("main");
2830 if (mlist && client->getPlayerItem() < mlist->getSize())
2831 playeritem = mlist->getItem(client->getPlayerItem());
2834 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
2835 InventoryList *hlist = local_inventory->getList("hand");
2837 playeritem = hlist->getItem(0);
2841 ToolCapabilities playeritem_toolcap =
2842 playeritem.getToolCapabilities(itemdef_manager);
2844 v3s16 old_camera_offset = camera->getOffset();
2846 if (wasKeyDown(KeyType::CAMERA_MODE)) {
2847 GenericCAO *playercao = player->getCAO();
2849 // If playercao not loaded, don't change camera
2853 camera->toggleCameraMode();
2855 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2856 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2859 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2860 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
2862 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2863 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio);
2864 camera->step(dtime);
2866 v3f camera_position = camera->getPosition();
2867 v3f camera_direction = camera->getDirection();
2868 f32 camera_fov = camera->getFovMax();
2869 v3s16 camera_offset = camera->getOffset();
2871 m_camera_offset_changed = (camera_offset != old_camera_offset);
2873 if (!m_flags.disable_camera_update) {
2874 client->getEnv().getClientMap().updateCamera(camera_position,
2875 camera_direction, camera_fov, camera_offset);
2877 if (m_camera_offset_changed) {
2878 client->updateCameraOffset(camera_offset);
2879 client->getEnv().updateCameraOffset(camera_offset);
2882 clouds->updateCameraOffset(camera_offset);
2888 void Game::updateSound(f32 dtime)
2890 // Update sound listener
2891 v3s16 camera_offset = camera->getOffset();
2892 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
2893 v3f(0, 0, 0), // velocity
2894 camera->getDirection(),
2895 camera->getCameraNode()->getUpVector());
2897 bool mute_sound = g_settings->getBool("mute_sound");
2899 sound->setListenerGain(0.0f);
2901 // Check if volume is in the proper range, else fix it.
2902 float old_volume = g_settings->getFloat("sound_volume");
2903 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
2904 sound->setListenerGain(new_volume);
2906 if (old_volume != new_volume) {
2907 g_settings->setFloat("sound_volume", new_volume);
2911 LocalPlayer *player = client->getEnv().getLocalPlayer();
2913 // Tell the sound maker whether to make footstep sounds
2914 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
2916 // Update sound maker
2917 if (player->makes_footstep_sound)
2918 soundmaker->step(dtime);
2920 ClientMap &map = client->getEnv().getClientMap();
2921 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
2922 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
2926 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
2928 LocalPlayer *player = client->getEnv().getLocalPlayer();
2930 ItemStack playeritem;
2932 InventoryList *mlist = local_inventory->getList("main");
2934 if (mlist && client->getPlayerItem() < mlist->getSize())
2935 playeritem = mlist->getItem(client->getPlayerItem());
2938 const ItemDefinition &playeritem_def =
2939 playeritem.getDefinition(itemdef_manager);
2940 InventoryList *hlist = local_inventory->getList("hand");
2941 const ItemDefinition &hand_def =
2942 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
2944 v3f player_position = player->getPosition();
2945 v3f camera_position = camera->getPosition();
2946 v3f camera_direction = camera->getDirection();
2947 v3s16 camera_offset = camera->getOffset();
2951 Calculate what block is the crosshair pointing to
2954 f32 d = playeritem_def.range; // max. distance
2955 f32 d_hand = hand_def.range;
2957 if (d < 0 && d_hand >= 0)
2962 core::line3d<f32> shootline;
2964 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
2965 shootline = core::line3d<f32>(camera_position,
2966 camera_position + camera_direction * BS * d);
2968 // prevent player pointing anything in front-view
2969 shootline = core::line3d<f32>(camera_position,camera_position);
2972 #ifdef HAVE_TOUCHSCREENGUI
2974 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
2975 shootline = g_touchscreengui->getShootline();
2976 // Scale shootline to the acual distance the player can reach
2977 shootline.end = shootline.start
2978 + shootline.getVector().normalize() * BS * d;
2979 shootline.start += intToFloat(camera_offset, BS);
2980 shootline.end += intToFloat(camera_offset, BS);
2985 PointedThing pointed = updatePointedThing(shootline,
2986 playeritem_def.liquids_pointable,
2987 !runData.ldown_for_dig,
2990 if (pointed != runData.pointed_old) {
2991 infostream << "Pointing at " << pointed.dump() << std::endl;
2992 hud->updateSelectionMesh(camera_offset);
2995 if (runData.digging_blocked && !input->getLeftState()) {
2996 // allow digging again if button is not pressed
2997 runData.digging_blocked = false;
3002 - releasing left mouse button
3003 - pointing away from node
3005 if (runData.digging) {
3006 if (input->getLeftReleased()) {
3007 infostream << "Left button released"
3008 << " (stopped digging)" << std::endl;
3009 runData.digging = false;
3010 } else if (pointed != runData.pointed_old) {
3011 if (pointed.type == POINTEDTHING_NODE
3012 && runData.pointed_old.type == POINTEDTHING_NODE
3013 && pointed.node_undersurface
3014 == runData.pointed_old.node_undersurface) {
3015 // Still pointing to the same node, but a different face.
3018 infostream << "Pointing away from node"
3019 << " (stopped digging)" << std::endl;
3020 runData.digging = false;
3021 hud->updateSelectionMesh(camera_offset);
3025 if (!runData.digging) {
3026 client->interact(1, runData.pointed_old);
3027 client->setCrack(-1, v3s16(0, 0, 0));
3028 runData.dig_time = 0.0;
3030 } else if (runData.dig_instantly && input->getLeftReleased()) {
3031 // Remove e.g. torches faster when clicking instead of holding LMB
3032 runData.nodig_delay_timer = 0;
3033 runData.dig_instantly = false;
3036 if (!runData.digging && runData.ldown_for_dig && !input->getLeftState()) {
3037 runData.ldown_for_dig = false;
3040 runData.left_punch = false;
3042 soundmaker->m_player_leftpunch_sound.name = "";
3044 // Prepare for repeating, unless we're not supposed to
3045 if (input->getRightState() && !g_settings->getBool("safe_dig_and_place"))
3046 runData.repeat_rightclick_timer += dtime;
3048 runData.repeat_rightclick_timer = 0;
3050 if (playeritem_def.usable && input->getLeftState()) {
3051 if (input->getLeftClicked() && (!client->moddingEnabled()
3052 || !client->getScript()->on_item_use(playeritem, pointed)))
3053 client->interact(4, pointed);
3054 } else if (pointed.type == POINTEDTHING_NODE) {
3055 ToolCapabilities playeritem_toolcap =
3056 playeritem.getToolCapabilities(itemdef_manager);
3057 if (playeritem.name.empty()) {
3058 const ToolCapabilities *handToolcap = hlist
3059 ? &hlist->getItem(0).getToolCapabilities(itemdef_manager)
3060 : itemdef_manager->get("").tool_capabilities;
3062 if (handToolcap != nullptr)
3063 playeritem_toolcap = *handToolcap;
3065 handlePointingAtNode(pointed, playeritem_def, playeritem,
3066 playeritem_toolcap, dtime);
3067 } else if (pointed.type == POINTEDTHING_OBJECT) {
3068 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3069 } else if (input->getLeftState()) {
3070 // When button is held down in air, show continuous animation
3071 runData.left_punch = true;
3072 } else if (input->getRightClicked()) {
3073 handlePointingAtNothing(playeritem);
3076 runData.pointed_old = pointed;
3078 if (runData.left_punch || input->getLeftClicked())
3079 camera->setDigging(0); // left click animation
3081 input->resetLeftClicked();
3082 input->resetRightClicked();
3084 input->resetLeftReleased();
3085 input->resetRightReleased();
3089 PointedThing Game::updatePointedThing(
3090 const core::line3d<f32> &shootline,
3091 bool liquids_pointable,
3092 bool look_for_object,
3093 const v3s16 &camera_offset)
3095 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3096 selectionboxes->clear();
3097 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3098 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3099 "show_entity_selectionbox");
3101 ClientEnvironment &env = client->getEnv();
3102 ClientMap &map = env.getClientMap();
3103 const NodeDefManager *nodedef = map.getNodeDefManager();
3105 runData.selected_object = NULL;
3107 RaycastState s(shootline, look_for_object, liquids_pointable);
3108 PointedThing result;
3109 env.continueRaycast(&s, &result);
3110 if (result.type == POINTEDTHING_OBJECT) {
3111 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3112 aabb3f selection_box;
3113 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3114 runData.selected_object->getSelectionBox(&selection_box)) {
3115 v3f pos = runData.selected_object->getPosition();
3116 selectionboxes->push_back(aabb3f(selection_box));
3117 hud->setSelectionPos(pos, camera_offset);
3119 } else if (result.type == POINTEDTHING_NODE) {
3120 // Update selection boxes
3121 MapNode n = map.getNodeNoEx(result.node_undersurface);
3122 std::vector<aabb3f> boxes;
3123 n.getSelectionBoxes(nodedef, &boxes,
3124 n.getNeighbors(result.node_undersurface, &map));
3127 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3128 i != boxes.end(); ++i) {
3130 box.MinEdge -= v3f(d, d, d);
3131 box.MaxEdge += v3f(d, d, d);
3132 selectionboxes->push_back(box);
3134 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3136 hud->setSelectedFaceNormal(v3f(
3137 result.intersection_normal.X,
3138 result.intersection_normal.Y,
3139 result.intersection_normal.Z));
3142 // Update selection mesh light level and vertex colors
3143 if (!selectionboxes->empty()) {
3144 v3f pf = hud->getSelectionPos();
3145 v3s16 p = floatToInt(pf, BS);
3147 // Get selection mesh light level
3148 MapNode n = map.getNodeNoEx(p);
3149 u16 node_light = getInteriorLight(n, -1, nodedef);
3150 u16 light_level = node_light;
3152 for (const v3s16 &dir : g_6dirs) {
3153 n = map.getNodeNoEx(p + dir);
3154 node_light = getInteriorLight(n, -1, nodedef);
3155 if (node_light > light_level)
3156 light_level = node_light;
3159 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3161 final_color_blend(&c, light_level, daynight_ratio);
3163 // Modify final color a bit with time
3164 u32 timer = porting::getTimeMs() % 5000;
3165 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3166 float sin_r = 0.08f * std::sin(timerf);
3167 float sin_g = 0.08f * std::sin(timerf + irr::core::PI * 0.5f);
3168 float sin_b = 0.08f * std::sin(timerf + irr::core::PI);
3169 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3170 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3171 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3173 // Set mesh final color
3174 hud->setSelectionMeshColor(c);
3180 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3182 infostream << "Right Clicked in Air" << std::endl;
3183 PointedThing fauxPointed;
3184 fauxPointed.type = POINTEDTHING_NOTHING;
3185 client->interact(5, fauxPointed);
3189 void Game::handlePointingAtNode(const PointedThing &pointed,
3190 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
3191 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3193 v3s16 nodepos = pointed.node_undersurface;
3194 v3s16 neighbourpos = pointed.node_abovesurface;
3197 Check information text of node
3200 ClientMap &map = client->getEnv().getClientMap();
3202 if (runData.nodig_delay_timer <= 0.0 && input->getLeftState()
3203 && !runData.digging_blocked
3204 && client->checkPrivilege("interact")) {
3205 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3208 // This should be done after digging handling
3209 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3212 m_game_ui->setInfoText(unescape_translate(utf8_to_wide(
3213 meta->getString("infotext"))));
3215 MapNode n = map.getNodeNoEx(nodepos);
3217 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3218 m_game_ui->setInfoText(L"Unknown node: " +
3219 utf8_to_wide(nodedef_manager->get(n).name));
3223 if ((input->getRightClicked() ||
3224 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3225 client->checkPrivilege("interact")) {
3226 runData.repeat_rightclick_timer = 0;
3227 infostream << "Ground right-clicked" << std::endl;
3229 if (meta && !meta->getString("formspec").empty() && !random_input
3230 && !isKeyDown(KeyType::SNEAK)) {
3231 // Report right click to server
3232 if (nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3233 client->interact(3, pointed);
3236 infostream << "Launching custom inventory view" << std::endl;
3238 InventoryLocation inventoryloc;
3239 inventoryloc.setNodeMeta(nodepos);
3241 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3242 &client->getEnv().getClientMap(), nodepos);
3243 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3245 GUIFormSpecMenu::create(current_formspec, client, &input->joystick, fs_src,
3246 txt_dst, client->getFormspecPrepend());
3247 cur_formname.clear();
3249 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3251 // Report right click to server
3253 camera->setDigging(1); // right click animation (always shown for feedback)
3255 // If the wielded item has node placement prediction,
3257 bool placed = nodePlacementPrediction(playeritem_def, playeritem, nodepos,
3262 client->interact(3, pointed);
3264 soundmaker->m_player_rightpunch_sound =
3265 playeritem_def.sound_place;
3267 if (client->moddingEnabled())
3268 client->getScript()->on_placenode(pointed, playeritem_def);
3270 soundmaker->m_player_rightpunch_sound =
3273 if (playeritem_def.node_placement_prediction.empty() ||
3274 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3275 client->interact(3, pointed); // Report to server
3277 soundmaker->m_player_rightpunch_sound =
3278 playeritem_def.sound_place_failed;
3285 bool Game::nodePlacementPrediction(const ItemDefinition &playeritem_def,
3286 const ItemStack &playeritem, const v3s16 &nodepos, const v3s16 &neighbourpos)
3288 std::string prediction = playeritem_def.node_placement_prediction;
3289 const NodeDefManager *nodedef = client->ndef();
3290 ClientMap &map = client->getEnv().getClientMap();
3292 bool is_valid_position;
3294 node = map.getNodeNoEx(nodepos, &is_valid_position);
3295 if (!is_valid_position)
3298 if (!prediction.empty() && !nodedef->get(node).rightclickable) {
3299 verbosestream << "Node placement prediction for "
3300 << playeritem_def.name << " is "
3301 << prediction << std::endl;
3302 v3s16 p = neighbourpos;
3304 // Place inside node itself if buildable_to
3305 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
3306 if (is_valid_position)
3308 if (nodedef->get(n_under).buildable_to)
3311 node = map.getNodeNoEx(p, &is_valid_position);
3312 if (is_valid_position &&!nodedef->get(node).buildable_to)
3317 // Find id of predicted node
3319 bool found = nodedef->getId(prediction, id);
3322 errorstream << "Node placement prediction failed for "
3323 << playeritem_def.name << " (places "
3325 << ") - Name not known" << std::endl;
3329 const ContentFeatures &predicted_f = nodedef->get(id);
3331 // Predict param2 for facedir and wallmounted nodes
3334 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3335 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
3336 v3s16 dir = nodepos - neighbourpos;
3338 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
3339 param2 = dir.Y < 0 ? 1 : 0;
3340 } else if (abs(dir.X) > abs(dir.Z)) {
3341 param2 = dir.X < 0 ? 3 : 2;
3343 param2 = dir.Z < 0 ? 5 : 4;
3347 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
3348 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
3349 v3s16 dir = nodepos - floatToInt(client->getEnv().getLocalPlayer()->getPosition(), BS);
3351 if (abs(dir.X) > abs(dir.Z)) {
3352 param2 = dir.X < 0 ? 3 : 1;
3354 param2 = dir.Z < 0 ? 2 : 0;
3358 assert(param2 <= 5);
3360 //Check attachment if node is in group attached_node
3361 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
3362 static v3s16 wallmounted_dirs[8] = {
3372 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3373 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
3374 pp = p + wallmounted_dirs[param2];
3376 pp = p + v3s16(0, -1, 0);
3378 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
3383 if ((predicted_f.param_type_2 == CPT2_COLOR
3384 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
3385 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
3386 const std::string &indexstr = playeritem.metadata.getString(
3387 "palette_index", 0);
3388 if (!indexstr.empty()) {
3389 s32 index = mystoi(indexstr);
3390 if (predicted_f.param_type_2 == CPT2_COLOR) {
3392 } else if (predicted_f.param_type_2
3393 == CPT2_COLORED_WALLMOUNTED) {
3394 // param2 = pure palette index + other
3395 param2 = (index & 0xf8) | (param2 & 0x07);
3396 } else if (predicted_f.param_type_2
3397 == CPT2_COLORED_FACEDIR) {
3398 // param2 = pure palette index + other
3399 param2 = (index & 0xe0) | (param2 & 0x1f);
3404 // Add node to client map
3405 MapNode n(id, 0, param2);
3408 LocalPlayer *player = client->getEnv().getLocalPlayer();
3410 // Dont place node when player would be inside new node
3411 // NOTE: This is to be eventually implemented by a mod as client-side Lua
3412 if (!nodedef->get(n).walkable ||
3413 g_settings->getBool("enable_build_where_you_stand") ||
3414 (client->checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
3415 (nodedef->get(n).walkable &&
3416 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
3417 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
3419 // This triggers the required mesh update too
3420 client->addNode(p, n);
3423 } catch (InvalidPositionException &e) {
3424 errorstream << "Node placement prediction failed for "
3425 << playeritem_def.name << " (places "
3427 << ") - Position not loaded" << std::endl;
3434 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3435 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();
3471 ItemStack item = playeritem;
3472 if (playeritem.name.empty()) {
3473 InventoryList *hlist = local_inventory->getList("hand");
3475 item = hlist->getItem(0);
3479 bool disable_send = runData.selected_object->directReportPunch(
3480 dir, &item, runData.time_from_last_punch);
3481 runData.time_from_last_punch = 0;
3484 client->interact(0, pointed);
3486 } else if (input->getRightClicked()) {
3487 infostream << "Right-clicked object" << std::endl;
3488 client->interact(3, pointed); // place
3493 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3494 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3496 LocalPlayer *player = client->getEnv().getLocalPlayer();
3497 ClientMap &map = client->getEnv().getClientMap();
3498 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3500 // NOTE: Similar piece of code exists on the server side for
3502 // Get digging parameters
3503 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3504 &playeritem_toolcap);
3506 // If can't dig, try hand
3507 if (!params.diggable) {
3508 InventoryList *hlist = local_inventory->getList("hand");
3509 const ToolCapabilities *tp = hlist
3510 ? &hlist->getItem(0).getToolCapabilities(itemdef_manager)
3511 : itemdef_manager->get("").tool_capabilities;
3514 params = getDigParams(nodedef_manager->get(n).groups, tp);
3517 if (!params.diggable) {
3518 // I guess nobody will wait for this long
3519 runData.dig_time_complete = 10000000.0;
3521 runData.dig_time_complete = params.time;
3523 if (m_cache_enable_particles) {
3524 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3525 client->getParticleManager()->addNodeParticle(client,
3526 player, nodepos, n, features);
3530 if (!runData.digging) {
3531 infostream << "Started digging" << std::endl;
3532 runData.dig_instantly = runData.dig_time_complete == 0;
3533 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3535 client->interact(0, pointed);
3536 runData.digging = true;
3537 runData.ldown_for_dig = true;
3540 if (!runData.dig_instantly) {
3541 runData.dig_index = (float)crack_animation_length
3543 / runData.dig_time_complete;
3545 // This is for e.g. torches
3546 runData.dig_index = crack_animation_length;
3549 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3551 if (sound_dig.exists() && params.diggable) {
3552 if (sound_dig.name == "__group") {
3553 if (!params.main_group.empty()) {
3554 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3555 soundmaker->m_player_leftpunch_sound.name =
3556 std::string("default_dig_") +
3560 soundmaker->m_player_leftpunch_sound = sound_dig;
3564 // Don't show cracks if not diggable
3565 if (runData.dig_time_complete >= 100000.0) {
3566 } else if (runData.dig_index < crack_animation_length) {
3567 //TimeTaker timer("client.setTempMod");
3568 //infostream<<"dig_index="<<dig_index<<std::endl;
3569 client->setCrack(runData.dig_index, nodepos);
3571 infostream << "Digging completed" << std::endl;
3572 client->setCrack(-1, v3s16(0, 0, 0));
3574 runData.dig_time = 0;
3575 runData.digging = false;
3576 // we successfully dug, now block it from repeating if we want to be safe
3577 if (g_settings->getBool("safe_dig_and_place"))
3578 runData.digging_blocked = true;
3580 runData.nodig_delay_timer =
3581 runData.dig_time_complete / (float)crack_animation_length;
3583 // We don't want a corresponding delay to very time consuming nodes
3584 // and nodes without digging time (e.g. torches) get a fixed delay.
3585 if (runData.nodig_delay_timer > 0.3)
3586 runData.nodig_delay_timer = 0.3;
3587 else if (runData.dig_instantly)
3588 runData.nodig_delay_timer = 0.15;
3590 bool is_valid_position;
3591 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3592 if (is_valid_position) {
3593 if (client->moddingEnabled() &&
3594 client->getScript()->on_dignode(nodepos, wasnode)) {
3598 const ContentFeatures &f = client->ndef()->get(wasnode);
3599 if (f.node_dig_prediction == "air") {
3600 client->removeNode(nodepos);
3601 } else if (!f.node_dig_prediction.empty()) {
3603 bool found = client->ndef()->getId(f.node_dig_prediction, id);
3605 client->addNode(nodepos, id, true);
3607 // implicit else: no prediction
3610 client->interact(2, pointed);
3612 if (m_cache_enable_particles) {
3613 const ContentFeatures &features =
3614 client->getNodeDefManager()->get(wasnode);
3615 client->getParticleManager()->addDiggingParticles(client,
3616 player, nodepos, wasnode, features);
3620 // Send event to trigger sound
3621 client->getEventManager()->put(new NodeDugEvent(nodepos, wasnode));
3624 if (runData.dig_time_complete < 100000.0) {
3625 runData.dig_time += dtime;
3627 runData.dig_time = 0;
3628 client->setCrack(-1, nodepos);
3631 camera->setDigging(0); // left click animation
3635 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
3636 const CameraOrientation &cam)
3638 LocalPlayer *player = client->getEnv().getLocalPlayer();
3644 if (draw_control->range_all) {
3645 runData.fog_range = 100000 * BS;
3647 runData.fog_range = draw_control->wanted_range * BS;
3651 Calculate general brightness
3653 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3654 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3655 float direct_brightness;
3658 if (m_cache_enable_noclip && m_cache_enable_free_move) {
3659 direct_brightness = time_brightness;
3660 sunlight_seen = true;
3662 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3663 float old_brightness = sky->getBrightness();
3664 direct_brightness = client->getEnv().getClientMap()
3665 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
3666 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3670 float time_of_day_smooth = runData.time_of_day_smooth;
3671 float time_of_day = client->getEnv().getTimeOfDayF();
3673 static const float maxsm = 0.05f;
3674 static const float todsm = 0.05f;
3676 if (std::fabs(time_of_day - time_of_day_smooth) > maxsm &&
3677 std::fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3678 std::fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3679 time_of_day_smooth = time_of_day;
3681 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3682 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3683 + (time_of_day + 1.0) * todsm;
3685 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3686 + time_of_day * todsm;
3688 runData.time_of_day_smooth = time_of_day_smooth;
3690 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3691 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3692 player->getPitch());
3698 if (sky->getCloudsVisible()) {
3699 clouds->setVisible(true);
3700 clouds->step(dtime);
3701 // camera->getPosition is not enough for 3rd person views
3702 v3f camera_node_position = camera->getCameraNode()->getPosition();
3703 v3s16 camera_offset = camera->getOffset();
3704 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
3705 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
3706 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
3707 clouds->update(camera_node_position,
3708 sky->getCloudColor());
3709 if (clouds->isCameraInsideCloud() && m_cache_enable_fog) {
3710 // if inside clouds, and fog enabled, use that as sky
3712 video::SColor clouds_dark = clouds->getColor()
3713 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
3714 sky->overrideColors(clouds_dark, clouds->getColor());
3715 sky->setBodiesVisible(false);
3716 runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
3717 // do not draw clouds after all
3718 clouds->setVisible(false);
3721 clouds->setVisible(false);
3728 client->getParticleManager()->step(dtime);
3734 if (m_cache_enable_fog) {
3737 video::EFT_FOG_LINEAR,
3738 runData.fog_range * m_cache_fog_start,
3739 runData.fog_range * 1.0,
3747 video::EFT_FOG_LINEAR,
3757 Get chat messages from client
3760 v2u32 screensize = driver->getScreenSize();
3762 updateChat(dtime, screensize);
3768 if (client->getPlayerItem() != runData.new_playeritem)
3769 client->selectPlayerItem(runData.new_playeritem);
3771 // Update local inventory if it has changed
3772 if (client->getLocalInventoryUpdated()) {
3773 //infostream<<"Updating local inventory"<<std::endl;
3774 client->getLocalInventory(*local_inventory);
3775 runData.update_wielded_item_trigger = true;
3778 if (runData.update_wielded_item_trigger) {
3779 // Update wielded tool
3780 InventoryList *mlist = local_inventory->getList("main");
3782 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
3783 ItemStack item = mlist->getItem(client->getPlayerItem());
3784 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
3785 InventoryList *hlist = local_inventory->getList("hand");
3787 item = hlist->getItem(0);
3789 camera->wield(item);
3792 runData.update_wielded_item_trigger = false;
3796 Update block draw list every 200ms or when camera direction has
3799 runData.update_draw_list_timer += dtime;
3801 v3f camera_direction = camera->getDirection();
3802 if (runData.update_draw_list_timer >= 0.2
3803 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3804 || m_camera_offset_changed) {
3805 runData.update_draw_list_timer = 0;
3806 client->getEnv().getClientMap().updateDrawList();
3807 runData.update_draw_list_last_cam_dir = camera_direction;
3810 m_game_ui->update(*stats, client, draw_control, cam, runData.pointed_old, dtime);
3813 make sure menu is on top
3814 1. Delete formspec menu reference if menu was removed
3815 2. Else, make sure formspec menu is on top
3817 if (current_formspec) {
3818 if (current_formspec->getReferenceCount() == 1) {
3819 current_formspec->drop();
3820 current_formspec = NULL;
3821 } else if (isMenuActive()) {
3822 guiroot->bringToFront(current_formspec);
3829 const video::SColor &skycolor = sky->getSkyColor();
3831 TimeTaker tt_draw("mainloop: draw");
3832 driver->beginScene(true, true, skycolor);
3834 bool draw_wield_tool = (m_game_ui->m_flags.show_hud &&
3835 (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
3836 (camera->getCameraMode() == CAMERA_MODE_FIRST));
3837 bool draw_crosshair = (
3838 (player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) &&
3839 (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT));
3840 #ifdef HAVE_TOUCHSCREENGUI
3842 draw_crosshair = !g_settings->getBool("touchtarget");
3843 } catch (SettingNotFoundException) {
3846 RenderingEngine::draw_scene(skycolor, m_game_ui->m_flags.show_hud,
3847 m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair);
3852 if (m_game_ui->m_flags.show_profiler_graph)
3853 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3858 if (runData.damage_flash > 0.0f) {
3859 video::SColor color(runData.damage_flash, 180, 0, 0);
3860 driver->draw2DRectangle(color,
3861 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3864 runData.damage_flash -= 384.0f * dtime;
3870 if (player->hurt_tilt_timer > 0.0f) {
3871 player->hurt_tilt_timer -= dtime * 6.0f;
3873 if (player->hurt_tilt_timer < 0.0f)
3874 player->hurt_tilt_strength = 0.0f;
3878 Update minimap pos and rotation
3880 if (mapper && m_game_ui->m_flags.show_minimap && m_game_ui->m_flags.show_hud) {
3881 mapper->setPos(floatToInt(player->getPosition(), BS));
3882 mapper->setAngle(player->getYaw());
3890 stats->drawtime = tt_draw.stop(true);
3891 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
3894 /* Log times and stuff for visualization */
3895 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
3897 Profiler::GraphValues values;
3898 g_profiler->graphGet(values);
3904 /****************************************************************************
3906 ****************************************************************************/
3908 /* On some computers framerate doesn't seem to be automatically limited
3910 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
3912 // not using getRealTime is necessary for wine
3913 device->getTimer()->tick(); // Maker sure device time is up-to-date
3914 u32 time = device->getTimer()->getTime();
3915 u32 last_time = fps_timings->last_time;
3917 if (time > last_time) // Make sure time hasn't overflowed
3918 fps_timings->busy_time = time - last_time;
3920 fps_timings->busy_time = 0;
3922 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
3923 ? g_settings->getFloat("pause_fps_max")
3924 : g_settings->getFloat("fps_max"));
3926 if (fps_timings->busy_time < frametime_min) {
3927 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
3928 device->sleep(fps_timings->sleep_time);
3930 fps_timings->sleep_time = 0;
3933 /* Get the new value of the device timer. Note that device->sleep() may
3934 * not sleep for the entire requested time as sleep may be interrupted and
3935 * therefore it is arguably more accurate to get the new time from the
3936 * device rather than calculating it by adding sleep_time to time.
3939 device->getTimer()->tick(); // Update device timer
3940 time = device->getTimer()->getTime();
3942 if (time > last_time) // Make sure last_time hasn't overflowed
3943 *dtime = (time - last_time) / 1000.0;
3947 fps_timings->last_time = time;
3950 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
3952 const wchar_t *wmsg = wgettext(msg);
3953 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
3958 void Game::settingChangedCallback(const std::string &setting_name, void *data)
3960 ((Game *)data)->readSettings();
3963 void Game::readSettings()
3965 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
3966 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
3967 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
3968 m_cache_enable_particles = g_settings->getBool("enable_particles");
3969 m_cache_enable_fog = g_settings->getBool("enable_fog");
3970 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
3971 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
3972 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
3974 m_cache_enable_noclip = g_settings->getBool("noclip");
3975 m_cache_enable_free_move = g_settings->getBool("free_move");
3977 m_cache_fog_start = g_settings->getFloat("fog_start");
3979 m_cache_cam_smoothing = 0;
3980 if (g_settings->getBool("cinematic"))
3981 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
3983 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
3985 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
3986 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
3987 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
3989 m_does_lost_focus_pause_game = g_settings->getBool("pause_on_lost_focus");
3992 /****************************************************************************/
3993 /****************************************************************************
3995 ****************************************************************************/
3996 /****************************************************************************/
3998 void Game::extendedResourceCleanup()
4000 // Extended resource accounting
4001 infostream << "Irrlicht resources after cleanup:" << std::endl;
4002 infostream << "\tRemaining meshes : "
4003 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
4004 infostream << "\tRemaining textures : "
4005 << driver->getTextureCount() << std::endl;
4007 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4008 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4009 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4013 clearTextureNameCache();
4014 infostream << "\tRemaining materials: "
4015 << driver-> getMaterialRendererCount()
4016 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4019 void Game::showDeathFormspec()
4021 static std::string formspec =
4022 std::string(FORMSPEC_VERSION_STRING) +
4024 "bgcolor[#320000b4;true]"
4025 "label[4.85,1.35;" + gettext("You died") + "]"
4026 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
4030 /* Note: FormspecFormSource and LocalFormspecHandler *
4031 * are deleted by guiFormSpecMenu */
4032 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
4033 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
4035 GUIFormSpecMenu::create(current_formspec, client, &input->joystick, fs_src,
4036 txt_dst, client->getFormspecPrepend());
4037 current_formspec->setFocus("btn_respawn");
4040 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4041 void Game::showPauseMenu()
4044 static const std::string control_text = strgettext("Default Controls:\n"
4045 "No menu visible:\n"
4046 "- single tap: button activate\n"
4047 "- double tap: place/use\n"
4048 "- slide finger: look around\n"
4049 "Menu/Inventory visible:\n"
4050 "- double tap (outside):\n"
4052 "- touch stack, touch slot:\n"
4054 "- touch&drag, tap 2nd finger\n"
4055 " --> place single item to slot\n"
4058 static const std::string control_text_template = strgettext("Controls:\n"
4059 "- %s: move forwards\n"
4060 "- %s: move backwards\n"
4062 "- %s: move right\n"
4063 "- %s: jump/climb\n"
4064 "- %s: sneak/go down\n"
4067 "- Mouse: turn/look\n"
4068 "- Mouse left: dig/punch\n"
4069 "- Mouse right: place/use\n"
4070 "- Mouse wheel: select item\n"
4074 char control_text_buf[600];
4076 porting::mt_snprintf(control_text_buf, sizeof(control_text_buf), control_text_template.c_str(),
4077 GET_KEY_NAME(keymap_forward),
4078 GET_KEY_NAME(keymap_backward),
4079 GET_KEY_NAME(keymap_left),
4080 GET_KEY_NAME(keymap_right),
4081 GET_KEY_NAME(keymap_jump),
4082 GET_KEY_NAME(keymap_sneak),
4083 GET_KEY_NAME(keymap_drop),
4084 GET_KEY_NAME(keymap_inventory),
4085 GET_KEY_NAME(keymap_chat)
4088 std::string control_text = std::string(control_text_buf);
4089 str_formspec_escape(control_text);
4092 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4093 std::ostringstream os;
4095 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4096 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4097 << strgettext("Continue") << "]";
4099 if (!simple_singleplayer_mode) {
4100 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4101 << strgettext("Change Password") << "]";
4103 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4107 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4108 << strgettext("Sound Volume") << "]";
4109 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4110 << strgettext("Change Keys") << "]";
4112 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4113 << strgettext("Exit to Menu") << "]";
4114 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4115 << strgettext("Exit to OS") << "]"
4116 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4117 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4119 << strgettext("Game info:") << "\n";
4120 const std::string &address = client->getAddressName();
4121 static const std::string mode = strgettext("- Mode: ");
4122 if (!simple_singleplayer_mode) {
4123 Address serverAddress = client->getServerAddress();
4124 if (!address.empty()) {
4125 os << mode << strgettext("Remote server") << "\n"
4126 << strgettext("- Address: ") << address;
4128 os << mode << strgettext("Hosting server");
4130 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4132 os << mode << strgettext("Singleplayer") << "\n";
4134 if (simple_singleplayer_mode || address.empty()) {
4135 static const std::string on = strgettext("On");
4136 static const std::string off = strgettext("Off");
4137 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4138 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4139 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4140 os << strgettext("- Damage: ") << damage << "\n"
4141 << strgettext("- Creative Mode: ") << creative << "\n";
4142 if (!simple_singleplayer_mode) {
4143 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4144 os << strgettext("- PvP: ") << pvp << "\n"
4145 << strgettext("- Public: ") << announced << "\n";
4146 std::string server_name = g_settings->get("server_name");
4147 str_formspec_escape(server_name);
4148 if (announced == on && !server_name.empty())
4149 os << strgettext("- Server Name: ") << server_name;
4156 /* Note: FormspecFormSource and LocalFormspecHandler *
4157 * are deleted by guiFormSpecMenu */
4158 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4159 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4161 GUIFormSpecMenu::create(current_formspec, client, &input->joystick,
4162 fs_src, txt_dst, client->getFormspecPrepend());
4163 current_formspec->setFocus("btn_continue");
4164 current_formspec->doPause = true;
4167 /****************************************************************************/
4168 /****************************************************************************
4169 extern function for launching the game
4170 ****************************************************************************/
4171 /****************************************************************************/
4173 void the_game(bool *kill,
4175 InputHandler *input,
4176 const std::string &map_dir,
4177 const std::string &playername,
4178 const std::string &password,
4179 const std::string &address, // If empty local server is created
4182 std::string &error_message,
4183 ChatBackend &chat_backend,
4184 bool *reconnect_requested,
4185 const SubgameSpec &gamespec, // Used for local game
4186 bool simple_singleplayer_mode)
4190 /* Make a copy of the server address because if a local singleplayer server
4191 * is created then this is updated and we don't want to change the value
4192 * passed to us by the calling function
4194 std::string server_address = address;
4198 if (game.startup(kill, random_input, input, map_dir,
4199 playername, password, &server_address, port, error_message,
4200 reconnect_requested, &chat_backend, gamespec,
4201 simple_singleplayer_mode)) {
4206 } catch (SerializationError &e) {
4207 error_message = std::string("A serialization error occurred:\n")
4208 + e.what() + "\n\nThe server is probably "
4209 " running a different version of " PROJECT_NAME_C ".";
4210 errorstream << error_message << std::endl;
4211 } catch (ServerError &e) {
4212 error_message = e.what();
4213 errorstream << "ServerError: " << error_message << std::endl;
4214 } catch (ModError &e) {
4215 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4216 errorstream << "ModError: " << error_message << std::endl;