3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include "client/tile.h" // For TextureSource
26 #include "client/keys.h"
27 #include "client/joystick_controller.h"
28 #include "clientmap.h"
31 #include "content_cao.h"
32 #include "drawscene.h"
33 #include "event_manager.h"
34 #include "fontengine.h"
39 #include "guiChatConsole.h"
40 #include "guiFormSpecMenu.h"
41 #include "guiKeyChangeMenu.h"
42 #include "guiPasswordChange.h"
43 #include "guiVolumeChange.h"
45 #include "mainmenumanager.h"
47 #include "nodedef.h" // Needed for determining pointing to nodes
48 #include "nodemetadata.h"
49 #include "particles.h"
51 #include "quicktune_shortcutter.h"
54 #include "shader.h" // For ShaderSource
58 #include "util/directiontables.h"
59 #include "util/pointedthing.h"
60 #include "irrlicht_changes/static_text.h"
63 #include "mapblock_mesh.h"
68 #include "sound_openal.h"
71 #ifdef HAVE_TOUCHSCREENGUI
72 #include "touchscreengui.h"
75 extern Settings *g_settings;
76 extern Profiler *g_profiler;
82 struct TextDestNodeMetadata : public TextDest {
83 TextDestNodeMetadata(v3s16 p, Client *client)
88 // This is deprecated I guess? -celeron55
89 void gotText(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 {
108 TextDestPlayerInventory(Client *client)
113 TextDestPlayerInventory(Client *client, std::string formname)
116 m_formname = formname;
118 void gotText(const StringMap &fields)
120 m_client->sendInventoryFields(m_formname, fields);
126 struct LocalFormspecHandler : public TextDest {
127 LocalFormspecHandler();
128 LocalFormspecHandler(std::string formname) :
131 m_formname = formname;
134 LocalFormspecHandler(std::string formname, Client *client) :
137 m_formname = formname;
140 void gotText(std::wstring message)
142 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
145 void gotText(const StringMap &fields)
147 if (m_formname == "MT_PAUSE_MENU") {
148 if (fields.find("btn_sound") != fields.end()) {
149 g_gamecallback->changeVolume();
153 if (fields.find("btn_key_config") != fields.end()) {
154 g_gamecallback->keyConfig();
158 if (fields.find("btn_exit_menu") != fields.end()) {
159 g_gamecallback->disconnect();
163 if (fields.find("btn_exit_os") != fields.end()) {
164 g_gamecallback->exitToOS();
168 if (fields.find("btn_change_password") != fields.end()) {
169 g_gamecallback->changePassword();
173 if (fields.find("quit") != fields.end()) {
177 if (fields.find("btn_continue") != fields.end()) {
182 if (m_formname == "MT_DEATH_SCREEN") {
183 assert(m_client != 0);
185 if ((fields.find("btn_respawn") != fields.end())) {
186 m_client->sendRespawn();
190 if (fields.find("quit") != fields.end()) {
191 m_client->sendRespawn();
196 // don't show error message for unhandled cursor keys
197 if ((fields.find("key_up") != fields.end()) ||
198 (fields.find("key_down") != fields.end()) ||
199 (fields.find("key_left") != fields.end()) ||
200 (fields.find("key_right") != fields.end())) {
204 errorstream << "LocalFormspecHandler::gotText unhandled >"
205 << m_formname << "< event" << std::endl;
208 StringMap::const_iterator it;
209 for (it = fields.begin(); it != fields.end(); ++it) {
210 errorstream << "\t" << i << ": " << it->first
211 << "=" << it->second << std::endl;
219 /* Form update callback */
221 class NodeMetadataFormSource: public IFormSource
224 NodeMetadataFormSource(ClientMap *map, v3s16 p):
229 std::string getForm()
231 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
236 return meta->getString("formspec");
238 std::string resolveText(std::string str)
240 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
245 return meta->resolveString(str);
252 class PlayerInventoryFormSource: public IFormSource
255 PlayerInventoryFormSource(Client *client):
259 std::string getForm()
261 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
262 return player->inventory_formspec;
269 Check if a node is pointable
271 inline bool isPointableNode(const MapNode &n,
272 Client *client, bool liquids_pointable)
274 const ContentFeatures &features = client->getNodeDefManager()->get(n);
275 return features.pointable ||
276 (liquids_pointable && features.isLiquid());
279 static inline void getNeighborConnectingFace(v3s16 p, INodeDefManager *nodedef,
280 ClientMap *map, MapNode n, u8 bitmask, u8 *neighbors)
282 MapNode n2 = map->getNodeNoEx(p);
283 if (nodedef->nodeboxConnects(n, n2, bitmask))
284 *neighbors |= bitmask;
287 static inline u8 getNeighbors(v3s16 p, INodeDefManager *nodedef, ClientMap *map, MapNode n)
290 const ContentFeatures &f = nodedef->get(n);
291 // locate possible neighboring nodes to connect to
292 if (f.drawtype == NDT_NODEBOX && f.node_box.type == NODEBOX_CONNECTED) {
296 getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
300 getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
304 getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
308 getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
312 getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
316 getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
323 Find what the player is pointing at
325 PointedThing getPointedThing(Client *client, Hud *hud, const v3f &player_position,
326 const v3f &camera_direction, const v3f &camera_position,
327 core::line3d<f32> shootline, f32 d, bool liquids_pointable,
328 bool look_for_object, const v3s16 &camera_offset,
329 ClientActiveObject *&selected_object)
333 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
334 selectionboxes->clear();
335 static const bool show_entity_selectionbox = g_settings->getBool("show_entity_selectionbox");
337 selected_object = NULL;
339 INodeDefManager *nodedef = client->getNodeDefManager();
340 ClientMap &map = client->getEnv().getClientMap();
342 f32 min_distance = BS * 1001;
344 // First try to find a pointed at active object
345 if (look_for_object) {
346 selected_object = client->getSelectedActiveObject(d * BS,
347 camera_position, shootline);
349 if (selected_object != NULL) {
350 if (show_entity_selectionbox &&
351 selected_object->doShowSelectionBox()) {
352 aabb3f *selection_box = selected_object->getSelectionBox();
353 // Box should exist because object was
354 // returned in the first place
355 assert(selection_box);
357 v3f pos = selected_object->getPosition();
358 selectionboxes->push_back(aabb3f(
359 selection_box->MinEdge, selection_box->MaxEdge));
360 hud->setSelectionPos(pos, camera_offset);
363 min_distance = (selected_object->getPosition() - camera_position).getLength();
365 result.type = POINTEDTHING_OBJECT;
366 result.object_id = selected_object->getId();
370 // That didn't work, try to find a pointed at node
372 v3s16 pos_i = floatToInt(player_position, BS);
374 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
378 s16 ystart = pos_i.Y - (camera_direction.Y < 0 ? a : 1);
379 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
380 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
381 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
382 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
383 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
385 // Prevent signed number overflow
395 v3s16 pointed_pos(0, 0, 0);
397 for (s16 y = ystart; y <= yend; y++) {
398 for (s16 z = zstart; z <= zend; z++) {
399 for (s16 x = xstart; x <= xend; x++) {
401 bool is_valid_position;
404 n = map.getNodeNoEx(p, &is_valid_position);
405 if (!is_valid_position) {
408 if (!isPointableNode(n, client, liquids_pointable)) {
412 std::vector<aabb3f> boxes;
413 n.getSelectionBoxes(nodedef, &boxes, getNeighbors(p, nodedef, &map, n));
416 v3f npf = intToFloat(np, BS);
417 for (std::vector<aabb3f>::const_iterator
419 i != boxes.end(); ++i) {
424 v3f centerpoint = box.getCenter();
425 f32 distance = (centerpoint - camera_position).getLength();
426 if (distance >= min_distance) {
429 if (!box.intersectsWithLine(shootline)) {
432 result.type = POINTEDTHING_NODE;
433 min_distance = distance;
440 if (result.type == POINTEDTHING_NODE) {
442 MapNode n = map.getNodeNoEx(pointed_pos);
443 v3f npf = intToFloat(pointed_pos, BS);
444 std::vector<aabb3f> boxes;
445 n.getSelectionBoxes(nodedef, &boxes, getNeighbors(pointed_pos, nodedef, &map, n));
446 f32 face_min_distance = 1000 * BS;
447 for (std::vector<aabb3f>::const_iterator
449 i != boxes.end(); ++i) {
453 for (u16 j = 0; j < 6; j++) {
454 v3s16 facedir = g_6dirs[j];
455 aabb3f facebox = box;
457 facebox.MinEdge.X = facebox.MaxEdge.X - d;
458 } else if (facedir.X < 0) {
459 facebox.MaxEdge.X = facebox.MinEdge.X + d;
460 } else if (facedir.Y > 0) {
461 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
462 } else if (facedir.Y < 0) {
463 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
464 } else if (facedir.Z > 0) {
465 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
466 } else if (facedir.Z < 0) {
467 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
469 v3f centerpoint = facebox.getCenter();
470 f32 distance = (centerpoint - camera_position).getLength();
471 if (distance >= face_min_distance)
473 if (!facebox.intersectsWithLine(shootline))
475 result.node_abovesurface = pointed_pos + facedir;
476 face_min_distance = distance;
479 selectionboxes->clear();
480 for (std::vector<aabb3f>::const_iterator
482 i != boxes.end(); ++i) {
484 box.MinEdge += v3f(-d, -d, -d);
485 box.MaxEdge += v3f(d, d, d);
486 selectionboxes->push_back(box);
488 hud->setSelectionPos(intToFloat(pointed_pos, BS), camera_offset);
489 result.node_undersurface = pointed_pos;
492 // Update selection mesh light level and vertex colors
493 if (selectionboxes->size() > 0) {
494 v3f pf = hud->getSelectionPos();
495 v3s16 p = floatToInt(pf, BS);
497 // Get selection mesh light level
498 MapNode n = map.getNodeNoEx(p);
499 u16 node_light = getInteriorLight(n, -1, nodedef);
500 u16 light_level = node_light;
502 for (u8 i = 0; i < 6; i++) {
503 n = map.getNodeNoEx(p + g_6dirs[i]);
504 node_light = getInteriorLight(n, -1, nodedef);
505 if (node_light > light_level)
506 light_level = node_light;
509 video::SColor c = MapBlock_LightColor(255, light_level, 0);
511 u8 night = c.getGreen();
512 u32 daynight_ratio = client->getEnv().getDayNightRatio();
513 finalColorBlend(c, day, night, daynight_ratio);
515 // Modify final color a bit with time
516 u32 timer = porting::getTimeMs() % 5000;
517 float timerf = (float)(irr::core::PI * ((timer / 2500.0) - 0.5));
518 float sin_r = 0.08 * sin(timerf);
519 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
520 float sin_b = 0.08 * sin(timerf + irr::core::PI);
521 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
522 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
523 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
525 // Set mesh final color
526 hud->setSelectionMeshColor(c);
531 /* Profiler display */
533 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
534 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
536 if (show_profiler == 0) {
537 guitext_profiler->setVisible(false);
540 std::ostringstream os(std::ios_base::binary);
541 g_profiler->printPage(os, show_profiler, show_profiler_max);
542 std::wstring text = utf8_to_wide(os.str());
543 setStaticText(guitext_profiler, text.c_str());
544 guitext_profiler->setVisible(true);
546 s32 w = fe->getTextWidth(text.c_str());
551 unsigned text_height = fe->getTextHeight();
553 core::position2di upper_left, lower_right;
556 upper_left.Y = (text_height + 5) * 2;
557 lower_right.X = 12 + w;
558 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
560 if (lower_right.Y > screen_height * 2 / 3)
561 lower_right.Y = screen_height * 2 / 3;
563 core::rect<s32> rect(upper_left, lower_right);
565 guitext_profiler->setRelativePosition(rect);
566 guitext_profiler->setVisible(true);
574 Profiler::GraphValues values;
580 Meta(float initial = 0,
581 video::SColor color = video::SColor(255, 255, 255, 255)):
587 std::deque<Piece> m_log;
595 void put(const Profiler::GraphValues &values)
598 piece.values = values;
599 m_log.push_back(piece);
601 while (m_log.size() > m_log_max_size)
602 m_log.erase(m_log.begin());
605 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
606 gui::IGUIFont *font) const
608 std::map<std::string, Meta> m_meta;
610 for (std::deque<Piece>::const_iterator k = m_log.begin();
611 k != m_log.end(); ++k) {
612 const Piece &piece = *k;
614 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
615 i != piece.values.end(); ++i) {
616 const std::string &id = i->first;
617 const float &value = i->second;
618 std::map<std::string, Meta>::iterator j =
621 if (j == m_meta.end()) {
622 m_meta[id] = Meta(value);
626 if (value < j->second.min)
627 j->second.min = value;
629 if (value > j->second.max)
630 j->second.max = value;
635 static const video::SColor usable_colors[] = {
636 video::SColor(255, 255, 100, 100),
637 video::SColor(255, 90, 225, 90),
638 video::SColor(255, 100, 100, 255),
639 video::SColor(255, 255, 150, 50),
640 video::SColor(255, 220, 220, 100)
642 static const u32 usable_colors_count =
643 sizeof(usable_colors) / sizeof(*usable_colors);
644 u32 next_color_i = 0;
646 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
647 i != m_meta.end(); ++i) {
648 Meta &meta = i->second;
649 video::SColor color(255, 200, 200, 200);
651 if (next_color_i < usable_colors_count)
652 color = usable_colors[next_color_i++];
658 s32 textx = x_left + m_log_max_size + 15;
659 s32 textx2 = textx + 200 - 15;
662 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
663 i != m_meta.end(); ++i) {
664 const std::string &id = i->first;
665 const Meta &meta = i->second;
667 s32 y = y_bottom - meta_i * 50;
668 float show_min = meta.min;
669 float show_max = meta.max;
671 if (show_min >= -0.0001 && show_max >= -0.0001) {
672 if (show_min <= show_max * 0.5)
678 snprintf(buf, 10, "%.3g", show_max);
679 font->draw(utf8_to_wide(buf).c_str(),
680 core::rect<s32>(textx, y - graphh,
681 textx2, y - graphh + texth),
683 snprintf(buf, 10, "%.3g", show_min);
684 font->draw(utf8_to_wide(buf).c_str(),
685 core::rect<s32>(textx, y - texth,
688 font->draw(utf8_to_wide(id).c_str(),
689 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
690 textx2, y - graphh / 2 + texth / 2),
693 s32 graph1h = graphh;
694 bool relativegraph = (show_min != 0 && show_min != show_max);
695 float lastscaledvalue = 0.0;
696 bool lastscaledvalue_exists = false;
698 for (std::deque<Piece>::const_iterator j = m_log.begin();
699 j != m_log.end(); ++j) {
700 const Piece &piece = *j;
702 bool value_exists = false;
703 Profiler::GraphValues::const_iterator k =
704 piece.values.find(id);
706 if (k != piece.values.end()) {
713 lastscaledvalue_exists = false;
717 float scaledvalue = 1.0;
719 if (show_max != show_min)
720 scaledvalue = (value - show_min) / (show_max - show_min);
722 if (scaledvalue == 1.0 && value == 0) {
724 lastscaledvalue_exists = false;
729 if (lastscaledvalue_exists) {
730 s32 ivalue1 = lastscaledvalue * graph1h;
731 s32 ivalue2 = scaledvalue * graph1h;
732 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
733 v2s32(x, graph1y - ivalue2), meta.color);
736 lastscaledvalue = scaledvalue;
737 lastscaledvalue_exists = true;
739 s32 ivalue = scaledvalue * graph1h;
740 driver->draw2DLine(v2s32(x, graph1y),
741 v2s32(x, graph1y - ivalue), meta.color);
752 class NodeDugEvent: public MtEvent
758 NodeDugEvent(v3s16 p, MapNode n):
762 const char *getType() const
770 ISoundManager *m_sound;
771 INodeDefManager *m_ndef;
773 float m_player_step_timer;
775 SimpleSoundSpec m_player_step_sound;
776 SimpleSoundSpec m_player_leftpunch_sound;
777 SimpleSoundSpec m_player_rightpunch_sound;
779 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
782 m_player_step_timer(0)
786 void playPlayerStep()
788 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
789 m_player_step_timer = 0.03;
790 m_sound->playSound(m_player_step_sound, false);
794 static void viewBobbingStep(MtEvent *e, void *data)
796 SoundMaker *sm = (SoundMaker *)data;
797 sm->playPlayerStep();
800 static void playerRegainGround(MtEvent *e, void *data)
802 SoundMaker *sm = (SoundMaker *)data;
803 sm->playPlayerStep();
806 static void playerJump(MtEvent *e, void *data)
808 //SoundMaker *sm = (SoundMaker*)data;
811 static void cameraPunchLeft(MtEvent *e, void *data)
813 SoundMaker *sm = (SoundMaker *)data;
814 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
817 static void cameraPunchRight(MtEvent *e, void *data)
819 SoundMaker *sm = (SoundMaker *)data;
820 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
823 static void nodeDug(MtEvent *e, void *data)
825 SoundMaker *sm = (SoundMaker *)data;
826 NodeDugEvent *nde = (NodeDugEvent *)e;
827 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
830 static void playerDamage(MtEvent *e, void *data)
832 SoundMaker *sm = (SoundMaker *)data;
833 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
836 static void playerFallingDamage(MtEvent *e, void *data)
838 SoundMaker *sm = (SoundMaker *)data;
839 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
842 void registerReceiver(MtEventManager *mgr)
844 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
845 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
846 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
847 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
848 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
849 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
850 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
851 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
854 void step(float dtime)
856 m_player_step_timer -= dtime;
860 // Locally stored sounds don't need to be preloaded because of this
861 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
863 std::set<std::string> m_fetched;
865 void fetchSounds(const std::string &name,
866 std::set<std::string> &dst_paths,
867 std::set<std::string> &dst_datas)
869 if (m_fetched.count(name))
872 m_fetched.insert(name);
873 std::string base = porting::path_share + DIR_DELIM + "testsounds";
874 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
875 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
876 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
877 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
878 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
879 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
880 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
881 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
882 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
883 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
884 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
888 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
891 bool *m_force_fog_off;
897 void onSettingsChange(const std::string &name)
899 if (name == "enable_fog")
900 m_fogEnabled = g_settings->getBool("enable_fog");
903 static void SettingsCallback(const std::string &name, void *userdata)
905 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
908 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
909 f32 *fog_range, Client *client) :
911 m_force_fog_off(force_fog_off),
912 m_fog_range(fog_range),
915 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
916 m_fogEnabled = g_settings->getBool("enable_fog");
919 ~GameGlobalShaderConstantSetter()
921 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
924 virtual void onSetConstants(video::IMaterialRendererServices *services,
931 video::SColor bgcolor = m_sky->getBgColor();
932 video::SColorf bgcolorf(bgcolor);
933 float bgcolorfa[4] = {
939 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
942 float fog_distance = 10000 * BS;
944 if (m_fogEnabled && !*m_force_fog_off)
945 fog_distance = *m_fog_range;
947 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
950 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
951 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
952 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
954 u32 animation_timer = porting::getTimeMs() % 100000;
955 float animation_timer_f = (float)animation_timer / 100000.0;
956 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
957 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
959 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
960 v3f eye_position = player->getEyePosition();
961 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
962 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
964 v3f minimap_yaw_vec = m_client->getMapper()->getYawVec();
965 services->setPixelShaderConstant("yawVec", (irr::f32 *)&minimap_yaw_vec, 3);
967 // Uniform sampler layers
968 // before 1.8 there isn't a "integer interface", only float
969 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
973 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
974 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
975 services->setPixelShaderConstant("textureFlags" , (irr::f32 *)&layer2, 1);
980 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
981 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
982 services->setPixelShaderConstant("textureFlags" , (irr::s32 *)&layer2, 1);
987 bool nodePlacementPrediction(Client &client,
988 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
990 std::string prediction = playeritem_def.node_placement_prediction;
991 INodeDefManager *nodedef = client.ndef();
992 ClientMap &map = client.getEnv().getClientMap();
994 bool is_valid_position;
996 node = map.getNodeNoEx(nodepos, &is_valid_position);
997 if (!is_valid_position)
1000 if (prediction != "" && !nodedef->get(node).rightclickable) {
1001 verbosestream << "Node placement prediction for "
1002 << playeritem_def.name << " is "
1003 << prediction << std::endl;
1004 v3s16 p = neighbourpos;
1006 // Place inside node itself if buildable_to
1007 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
1008 if (is_valid_position)
1010 if (nodedef->get(n_under).buildable_to)
1013 node = map.getNodeNoEx(p, &is_valid_position);
1014 if (is_valid_position &&!nodedef->get(node).buildable_to)
1019 // Find id of predicted node
1021 bool found = nodedef->getId(prediction, id);
1024 errorstream << "Node placement prediction failed for "
1025 << playeritem_def.name << " (places "
1027 << ") - Name not known" << std::endl;
1031 // Predict param2 for facedir and wallmounted nodes
1034 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
1035 v3s16 dir = nodepos - neighbourpos;
1037 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
1038 param2 = dir.Y < 0 ? 1 : 0;
1039 } else if (abs(dir.X) > abs(dir.Z)) {
1040 param2 = dir.X < 0 ? 3 : 2;
1042 param2 = dir.Z < 0 ? 5 : 4;
1046 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
1047 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
1049 if (abs(dir.X) > abs(dir.Z)) {
1050 param2 = dir.X < 0 ? 3 : 1;
1052 param2 = dir.Z < 0 ? 2 : 0;
1056 assert(param2 <= 5);
1058 //Check attachment if node is in group attached_node
1059 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
1060 static v3s16 wallmounted_dirs[8] = {
1070 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
1071 pp = p + wallmounted_dirs[param2];
1073 pp = p + v3s16(0, -1, 0);
1075 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
1079 // Add node to client map
1080 MapNode n(id, 0, param2);
1083 LocalPlayer *player = client.getEnv().getLocalPlayer();
1085 // Dont place node when player would be inside new node
1086 // NOTE: This is to be eventually implemented by a mod as client-side Lua
1087 if (!nodedef->get(n).walkable ||
1088 g_settings->getBool("enable_build_where_you_stand") ||
1089 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
1090 (nodedef->get(n).walkable &&
1091 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
1092 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
1094 // This triggers the required mesh update too
1095 client.addNode(p, n);
1098 } catch (InvalidPositionException &e) {
1099 errorstream << "Node placement prediction failed for "
1100 << playeritem_def.name << " (places "
1102 << ") - Position not loaded" << std::endl;
1109 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1110 InventoryManager *invmgr, IGameDef *gamedef,
1111 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1112 JoystickController *joystick,
1113 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1116 if (*cur_formspec == 0) {
1117 *cur_formspec = new GUIFormSpecMenu(device, joystick,
1118 guiroot, -1, &g_menumgr, invmgr, gamedef, tsrc,
1119 fs_src, txt_dest, client);
1120 (*cur_formspec)->doPause = false;
1123 Caution: do not call (*cur_formspec)->drop() here --
1124 the reference might outlive the menu, so we will
1125 periodically check if *cur_formspec is the only
1126 remaining reference (i.e. the menu was removed)
1127 and delete it in that case.
1131 (*cur_formspec)->setFormSource(fs_src);
1132 (*cur_formspec)->setTextDest(txt_dest);
1137 #define SIZE_TAG "size[11,5.5]"
1139 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1142 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1143 InventoryManager *invmgr, IGameDef *gamedef,
1144 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1145 JoystickController *joystick, Client *client)
1147 std::string formspec =
1148 std::string(FORMSPEC_VERSION_STRING) +
1150 "bgcolor[#320000b4;true]"
1151 "label[4.85,1.35;" + gettext("You died.") + "]"
1152 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1156 /* Note: FormspecFormSource and LocalFormspecHandler
1157 * are deleted by guiFormSpecMenu */
1158 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1159 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1161 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,
1162 joystick, fs_src, txt_dst, NULL);
1165 /******************************************************************************/
1166 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1167 InventoryManager *invmgr, IGameDef *gamedef,
1168 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1169 JoystickController *joystick, bool singleplayermode)
1172 std::string control_text = strgettext("Default Controls:\n"
1173 "No menu visible:\n"
1174 "- single tap: button activate\n"
1175 "- double tap: place/use\n"
1176 "- slide finger: look around\n"
1177 "Menu/Inventory visible:\n"
1178 "- double tap (outside):\n"
1180 "- touch stack, touch slot:\n"
1182 "- touch&drag, tap 2nd finger\n"
1183 " --> place single item to slot\n"
1186 std::string control_text = strgettext("Default Controls:\n"
1188 "- Space: jump/climb\n"
1189 "- Shift: sneak/go down\n"
1192 "- Mouse: turn/look\n"
1193 "- Mouse left: dig/punch\n"
1194 "- Mouse right: place/use\n"
1195 "- Mouse wheel: select item\n"
1200 float ypos = singleplayermode ? 0.5 : 0.1;
1201 std::ostringstream os;
1203 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1204 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1205 << strgettext("Continue") << "]";
1207 if (!singleplayermode) {
1208 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1209 << strgettext("Change Password") << "]";
1213 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1214 << strgettext("Sound Volume") << "]";
1215 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1216 << strgettext("Change Keys") << "]";
1218 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1219 << strgettext("Exit to Menu") << "]";
1220 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1221 << strgettext("Exit to OS") << "]"
1222 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1223 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1224 << g_build_info << "\n"
1225 << "path_user = " << wrap_rows(porting::path_user, 20)
1229 /* Note: FormspecFormSource and LocalFormspecHandler *
1230 * are deleted by guiFormSpecMenu */
1231 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1232 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1234 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,
1235 joystick, fs_src, txt_dst, NULL);
1236 std::string con("btn_continue");
1237 (*cur_formspec)->setFocus(con);
1238 (*cur_formspec)->doPause = true;
1241 /******************************************************************************/
1242 static void updateChat(Client &client, f32 dtime, bool show_debug,
1243 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1244 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1246 // Add chat log output for errors to be shown in chat
1247 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
1249 // Get new messages from error log buffer
1250 while (!chat_log_error_buf.empty()) {
1251 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
1252 if (!g_settings->getBool("disable_escape_sequences")) {
1253 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
1255 chat_backend.addMessage(L"", error_message);
1258 // Get new messages from client
1259 std::wstring message;
1261 while (client.getChatMessage(message)) {
1262 chat_backend.addUnparsedMessage(message);
1265 // Remove old messages
1266 chat_backend.step(dtime);
1268 // Display all messages in a static text element
1269 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1270 EnrichedString recent_chat = chat_backend.getRecentChat();
1271 unsigned int line_height = g_fontengine->getLineHeight();
1273 setStaticText(guitext_chat, recent_chat);
1275 // Update gui element size and position
1279 chat_y += 2 * line_height;
1281 // first pass to calculate height of text to be set
1282 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
1283 porting::getWindowSize().X - 20);
1284 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1285 guitext_chat->setRelativePosition(rect);
1287 //now use real height of text and adjust rect according to this size
1288 rect = core::rect<s32>(10, chat_y, width,
1289 chat_y + guitext_chat->getTextHeight());
1292 guitext_chat->setRelativePosition(rect);
1293 // Don't show chat if disabled or empty or profiler is enabled
1294 guitext_chat->setVisible(
1295 show_chat && recent_chat_count != 0 && !show_profiler);
1299 /****************************************************************************
1300 Fast key cache for main game loop
1301 ****************************************************************************/
1303 /* This is faster than using getKeySetting with the tradeoff that functions
1304 * using it must make sure that it's initialised before using it and there is
1305 * no error handling (for example bounds checking). This is really intended for
1306 * use only in the main running loop of the client (the_game()) where the faster
1307 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1308 * (e.g. formspecs) should continue using getKeySetting().
1316 populate_nonchanging();
1321 // Keys that are not settings dependent
1322 void populate_nonchanging();
1324 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1325 InputHandler *handler;
1328 void KeyCache::populate_nonchanging()
1330 key[KeyType::ESC] = EscapeKey;
1333 void KeyCache::populate()
1335 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1336 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1337 key[KeyType::LEFT] = getKeySetting("keymap_left");
1338 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1339 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1340 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1341 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1343 key[KeyType::AUTORUN] = getKeySetting("keymap_autorun");
1345 key[KeyType::DROP] = getKeySetting("keymap_drop");
1346 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1347 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1348 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1349 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1350 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1351 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1352 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1353 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1354 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1355 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1356 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1357 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1358 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1359 = getKeySetting("keymap_toggle_force_fog_off");
1360 key[KeyType::TOGGLE_UPDATE_CAMERA]
1361 = getKeySetting("keymap_toggle_update_camera");
1362 key[KeyType::TOGGLE_DEBUG]
1363 = getKeySetting("keymap_toggle_debug");
1364 key[KeyType::TOGGLE_PROFILER]
1365 = getKeySetting("keymap_toggle_profiler");
1366 key[KeyType::CAMERA_MODE]
1367 = getKeySetting("keymap_camera_mode");
1368 key[KeyType::INCREASE_VIEWING_RANGE]
1369 = getKeySetting("keymap_increase_viewing_range_min");
1370 key[KeyType::DECREASE_VIEWING_RANGE]
1371 = getKeySetting("keymap_decrease_viewing_range_min");
1372 key[KeyType::RANGESELECT]
1373 = getKeySetting("keymap_rangeselect");
1374 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1376 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1377 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1378 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1379 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1381 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1384 // First clear all keys, then re-add the ones we listen for
1385 handler->dontListenForKeys();
1386 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1387 handler->listenForKey(key[i]);
1389 handler->listenForKey(EscapeKey);
1390 handler->listenForKey(CancelKey);
1391 for (size_t i = 0; i < 10; i++) {
1392 handler->listenForKey(NumberKey[i]);
1398 /****************************************************************************
1400 ****************************************************************************/
1402 const float object_hit_delay = 0.2;
1405 u32 last_time, busy_time, sleep_time;
1409 /* The reason the following structs are not anonymous structs within the
1410 * class is that they are not used by the majority of member functions and
1411 * many functions that do require objects of thse types do not modify them
1412 * (so they can be passed as a const qualified parameter)
1414 struct CameraOrientation {
1415 f32 camera_yaw; // "right/left"
1416 f32 camera_pitch; // "up/down"
1419 struct GameRunData {
1422 PointedThing pointed_old;
1426 bool update_wielded_item_trigger;
1427 bool reset_jump_timer;
1428 float nodig_delay_timer;
1430 float dig_time_complete;
1431 float repeat_rightclick_timer;
1432 float object_hit_delay_timer;
1433 float time_from_last_punch;
1434 ClientActiveObject *selected_object;
1438 float update_draw_list_timer;
1439 float statustext_time;
1443 v3f update_draw_list_last_cam_dir;
1445 u32 profiler_current_page;
1446 u32 profiler_max_page; // Number of pages
1449 float time_of_day_smooth;
1453 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1461 Jitter dtime_jitter, busy_time_jitter;
1464 /* Flags that can, or may, change during main game loop
1466 struct VolatileRunFlags {
1473 bool show_profiler_graph;
1474 bool disable_camera_update;
1475 bool first_loop_after_window_activation;
1476 bool camera_offset_changed;
1480 /****************************************************************************
1482 ****************************************************************************/
1484 /* This is not intended to be a public class. If a public class becomes
1485 * desirable then it may be better to create another 'wrapper' class that
1486 * hides most of the stuff in this class (nothing in this class is required
1487 * by any other file) but exposes the public methods/data only.
1494 bool startup(bool *kill,
1496 InputHandler *input,
1497 IrrlichtDevice *device,
1498 const std::string &map_dir,
1499 const std::string &playername,
1500 const std::string &password,
1501 // If address is "", local server is used and address is updated
1502 std::string *address,
1504 std::string &error_message,
1506 ChatBackend *chat_backend,
1507 const SubgameSpec &gamespec, // Used for local game
1508 bool simple_singleplayer_mode);
1515 void extendedResourceCleanup();
1517 // Basic initialisation
1518 bool init(const std::string &map_dir, std::string *address,
1520 const SubgameSpec &gamespec);
1522 bool createSingleplayerServer(const std::string map_dir,
1523 const SubgameSpec &gamespec, u16 port, std::string *address);
1526 bool createClient(const std::string &playername,
1527 const std::string &password, std::string *address, u16 port);
1530 // Client connection
1531 bool connectToServer(const std::string &playername,
1532 const std::string &password, std::string *address, u16 port,
1533 bool *connect_ok, bool *aborted);
1534 bool getServerContent(bool *aborted);
1538 void updateInteractTimers(GameRunData *runData, f32 dtime);
1539 bool checkConnection();
1540 bool handleCallbacks();
1541 void processQueues();
1542 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1543 const FpsControl &draw_times, f32 dtime);
1544 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1546 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1549 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1551 void processKeyInput(VolatileRunFlags *flags,
1552 float *statustext_time,
1554 bool *reset_jump_timer,
1555 u32 *profiler_current_page,
1556 u32 profiler_max_page);
1557 void processItemSelection(u16 *new_playeritem);
1559 void dropSelectedItem();
1560 void openInventory();
1561 void openConsole(float height, const wchar_t *line=NULL);
1562 void toggleFreeMove(float *statustext_time);
1563 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1564 void toggleFast(float *statustext_time);
1565 void toggleNoClip(float *statustext_time);
1566 void toggleCinematic(float *statustext_time);
1567 void toggleAutorun(float *statustext_time);
1569 void toggleChat(float *statustext_time, bool *flag);
1570 void toggleHud(float *statustext_time, bool *flag);
1571 void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
1572 bool shift_pressed);
1573 void toggleFog(float *statustext_time, bool *flag);
1574 void toggleDebug(float *statustext_time, bool *show_debug,
1575 bool *show_profiler_graph);
1576 void toggleUpdateCamera(float *statustext_time, bool *flag);
1577 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1578 u32 profiler_max_page);
1580 void increaseViewRange(float *statustext_time);
1581 void decreaseViewRange(float *statustext_time);
1582 void toggleFullViewRange(float *statustext_time);
1584 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags,
1586 void updateCameraOrientation(CameraOrientation *cam,
1587 const VolatileRunFlags &flags, float dtime);
1588 void updatePlayerControl(const CameraOrientation &cam);
1589 void step(f32 *dtime);
1590 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1591 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1592 float time_from_last_punch);
1593 void updateSound(f32 dtime);
1594 void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud,
1596 void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
1597 void handlePointingAtNode(GameRunData *runData,
1598 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1599 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1600 void handlePointingAtObject(GameRunData *runData,
1601 const PointedThing &pointed, const ItemStack &playeritem,
1602 const v3f &player_position, bool show_debug);
1603 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1604 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1606 void updateFrame(ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
1607 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1608 void updateGui(float *statustext_time, const RunStats &stats,
1609 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1610 const CameraOrientation &cam);
1611 void updateProfilerGraphs(ProfilerGraph *graph);
1614 void limitFps(FpsControl *fps_timings, f32 *dtime);
1616 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1617 bool draw_clouds = true);
1619 static void settingChangedCallback(const std::string &setting_name, void *data);
1620 void readSettings();
1622 inline bool getLeftClicked()
1624 return input->getLeftClicked() ||
1625 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1627 inline bool getRightClicked()
1629 return input->getRightClicked() ||
1630 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1632 inline bool isLeftPressed()
1634 return input->getLeftState() ||
1635 input->joystick.isKeyDown(KeyType::MOUSE_L);
1637 inline bool isRightPressed()
1639 return input->getRightState() ||
1640 input->joystick.isKeyDown(KeyType::MOUSE_R);
1642 inline bool getLeftReleased()
1644 return input->getLeftReleased() ||
1645 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1648 inline bool isKeyDown(GameKeyType k)
1650 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1652 inline bool wasKeyDown(GameKeyType k)
1654 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1658 void handleAndroidChatInput();
1662 InputHandler *input;
1667 IWritableTextureSource *texture_src;
1668 IWritableShaderSource *shader_src;
1670 // When created, these will be filled with data received from the server
1671 IWritableItemDefManager *itemdef_manager;
1672 IWritableNodeDefManager *nodedef_manager;
1674 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1675 ISoundManager *sound;
1676 bool sound_is_dummy;
1677 SoundMaker *soundmaker;
1679 ChatBackend *chat_backend;
1681 GUIFormSpecMenu *current_formspec;
1683 EventManager *eventmgr;
1684 QuicktuneShortcutter *quicktune;
1686 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1687 MapDrawControl *draw_control;
1689 Clouds *clouds; // Free using ->Drop()
1690 Sky *sky; // Free using ->Drop()
1691 Inventory *local_inventory;
1696 This class does take ownership/responsibily for cleaning up etc of any of
1697 these items (e.g. device)
1699 IrrlichtDevice *device;
1700 video::IVideoDriver *driver;
1701 scene::ISceneManager *smgr;
1703 std::string *error_message;
1704 bool *reconnect_requested;
1705 IGameDef *gamedef; // Convenience (same as *client)
1706 scene::ISceneNode *skybox;
1709 bool simple_singleplayer_mode;
1712 /* Pre-calculated values
1714 int crack_animation_length;
1718 gui::IGUIStaticText *guitext; // First line of debug text
1719 gui::IGUIStaticText *guitext2; // Second line of debug text
1720 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1721 gui::IGUIStaticText *guitext_status;
1722 gui::IGUIStaticText *guitext_chat; // Chat text
1723 gui::IGUIStaticText *guitext_profiler; // Profiler text
1725 std::wstring infotext;
1726 std::wstring statustext;
1730 IntervalLimiter profiler_interval;
1733 * TODO: Local caching of settings is not optimal and should at some stage
1734 * be updated to use a global settings object for getting thse values
1735 * (as opposed to the this local caching). This can be addressed in
1738 bool m_cache_doubletap_jump;
1739 bool m_cache_enable_clouds;
1740 bool m_cache_enable_joysticks;
1741 bool m_cache_enable_particles;
1742 bool m_cache_enable_fog;
1743 f32 m_cache_mouse_sensitivity;
1744 f32 m_cache_joystick_frustum_sensitivity;
1745 f32 m_repeat_right_click_time;
1748 bool m_cache_hold_aux1;
1749 bool m_android_chat_open;
1758 itemdef_manager(NULL),
1759 nodedef_manager(NULL),
1761 sound_is_dummy(false),
1764 current_formspec(NULL),
1767 gui_chat_console(NULL),
1772 local_inventory(NULL),
1776 g_settings->registerChangedCallback("doubletap_jump",
1777 &settingChangedCallback, this);
1778 g_settings->registerChangedCallback("enable_clouds",
1779 &settingChangedCallback, this);
1780 g_settings->registerChangedCallback("doubletap_joysticks",
1781 &settingChangedCallback, this);
1782 g_settings->registerChangedCallback("enable_particles",
1783 &settingChangedCallback, this);
1784 g_settings->registerChangedCallback("enable_fog",
1785 &settingChangedCallback, this);
1786 g_settings->registerChangedCallback("mouse_sensitivity",
1787 &settingChangedCallback, this);
1788 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1789 &settingChangedCallback, this);
1790 g_settings->registerChangedCallback("repeat_rightclick_time",
1791 &settingChangedCallback, this);
1796 m_cache_hold_aux1 = false; // This is initialised properly later
1803 /****************************************************************************
1805 ****************************************************************************/
1811 if (!sound_is_dummy)
1814 delete server; // deleted first to stop all server threads
1817 delete local_inventory;
1823 delete nodedef_manager;
1824 delete itemdef_manager;
1825 delete draw_control;
1827 extendedResourceCleanup();
1829 g_settings->deregisterChangedCallback("doubletap_jump",
1830 &settingChangedCallback, this);
1831 g_settings->deregisterChangedCallback("enable_clouds",
1832 &settingChangedCallback, this);
1833 g_settings->deregisterChangedCallback("enable_particles",
1834 &settingChangedCallback, this);
1835 g_settings->deregisterChangedCallback("enable_fog",
1836 &settingChangedCallback, this);
1837 g_settings->deregisterChangedCallback("mouse_sensitivity",
1838 &settingChangedCallback, this);
1839 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1840 &settingChangedCallback, this);
1843 bool Game::startup(bool *kill,
1845 InputHandler *input,
1846 IrrlichtDevice *device,
1847 const std::string &map_dir,
1848 const std::string &playername,
1849 const std::string &password,
1850 std::string *address, // can change if simple_singleplayer_mode
1852 std::string &error_message,
1854 ChatBackend *chat_backend,
1855 const SubgameSpec &gamespec,
1856 bool simple_singleplayer_mode)
1859 this->device = device;
1861 this->error_message = &error_message;
1862 this->reconnect_requested = reconnect;
1863 this->random_input = random_input;
1864 this->input = input;
1865 this->chat_backend = chat_backend;
1866 this->simple_singleplayer_mode = simple_singleplayer_mode;
1868 keycache.handler = input;
1869 keycache.populate();
1871 driver = device->getVideoDriver();
1872 smgr = device->getSceneManager();
1874 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1876 if (!init(map_dir, address, port, gamespec))
1879 if (!createClient(playername, password, address, port))
1888 ProfilerGraph graph;
1889 RunStats stats = { 0 };
1890 CameraOrientation cam_view_target = { 0 };
1891 CameraOrientation cam_view = { 0 };
1892 GameRunData runData = { 0 };
1893 FpsControl draw_times = { 0 };
1894 VolatileRunFlags flags = { 0 };
1895 f32 dtime; // in seconds
1897 runData.time_from_last_punch = 10.0;
1898 runData.profiler_max_page = 3;
1899 runData.update_wielded_item_trigger = true;
1901 flags.show_chat = true;
1902 flags.show_hud = true;
1903 flags.show_minimap = g_settings->getBool("enable_minimap");
1904 flags.show_debug = g_settings->getBool("show_debug");
1905 flags.invert_mouse = g_settings->getBool("invert_mouse");
1906 flags.first_loop_after_window_activation = true;
1908 /* Clear the profiler */
1909 Profiler::GraphValues dummyvalues;
1910 g_profiler->graphGet(dummyvalues);
1912 draw_times.last_time = device->getTimer()->getTime();
1914 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1916 &flags.force_fog_off,
1920 set_light_table(g_settings->getFloat("display_gamma"));
1923 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1924 && client->checkPrivilege("fast");
1927 while (device->run()
1928 && !(*kill || g_gamecallback->shutdown_requested
1929 || (server && server->getShutdownRequested()))) {
1931 /* Must be called immediately after a device->run() call because it
1932 * uses device->getTimer()->getTime()
1934 limitFps(&draw_times, &dtime);
1936 updateStats(&stats, draw_times, dtime);
1937 updateInteractTimers(&runData, dtime);
1939 if (!checkConnection())
1941 if (!handleCallbacks())
1947 hud->resizeHotbar();
1949 updateProfilers(runData, stats, draw_times, dtime);
1950 processUserInput(&flags, &runData, dtime);
1951 // Update camera before player movement to avoid camera lag of one frame
1952 updateCameraDirection(&cam_view_target, &flags, dtime);
1953 float cam_smoothing = 0;
1954 if (g_settings->getBool("cinematic"))
1955 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1957 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1958 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1959 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1960 cam_view.camera_yaw) * cam_smoothing;
1961 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1962 cam_view.camera_pitch) * cam_smoothing;
1963 updatePlayerControl(cam_view);
1965 processClientEvents(&cam_view_target, &runData.damage_flash);
1966 updateCamera(&flags, draw_times.busy_time, dtime,
1967 runData.time_from_last_punch);
1969 processPlayerInteraction(&runData, dtime, flags.show_hud,
1971 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
1972 updateProfilerGraphs(&graph);
1974 // Update if minimap has been disabled by the server
1975 flags.show_minimap &= !client->isMinimapDisabledByServer();
1980 void Game::shutdown()
1982 if (g_settings->get("3d_mode") == "pageflip") {
1983 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1986 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1991 if (gui_chat_console)
1992 gui_chat_console->drop();
1998 while (g_menumgr.menuCount() > 0) {
1999 g_menumgr.m_stack.front()->setVisible(false);
2000 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
2003 if (current_formspec) {
2004 current_formspec->drop();
2005 current_formspec = NULL;
2008 chat_backend->addMessage(L"", L"# Disconnected.");
2009 chat_backend->addMessage(L"", L"");
2013 while (!client->isShutdown()) {
2014 assert(texture_src != NULL);
2015 assert(shader_src != NULL);
2016 texture_src->processQueue();
2017 shader_src->processQueue();
2024 /****************************************************************************/
2025 /****************************************************************************
2027 ****************************************************************************/
2028 /****************************************************************************/
2031 const std::string &map_dir,
2032 std::string *address,
2034 const SubgameSpec &gamespec)
2036 showOverlayMessage(wgettext("Loading..."), 0, 0);
2038 texture_src = createTextureSource(device);
2039 shader_src = createShaderSource(device);
2041 itemdef_manager = createItemDefManager();
2042 nodedef_manager = createNodeDefManager();
2044 eventmgr = new EventManager();
2045 quicktune = new QuicktuneShortcutter();
2047 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
2048 && eventmgr && quicktune))
2054 // Create a server if not connecting to an existing one
2055 if (*address == "") {
2056 if (!createSingleplayerServer(map_dir, gamespec, port, address))
2063 bool Game::initSound()
2066 if (g_settings->getBool("enable_sound")) {
2067 infostream << "Attempting to use OpenAL audio" << std::endl;
2068 sound = createOpenALSoundManager(&soundfetcher);
2070 infostream << "Failed to initialize OpenAL audio" << std::endl;
2072 infostream << "Sound disabled." << std::endl;
2076 infostream << "Using dummy audio." << std::endl;
2077 sound = &dummySoundManager;
2078 sound_is_dummy = true;
2081 soundmaker = new SoundMaker(sound, nodedef_manager);
2085 soundmaker->registerReceiver(eventmgr);
2090 bool Game::createSingleplayerServer(const std::string map_dir,
2091 const SubgameSpec &gamespec, u16 port, std::string *address)
2093 showOverlayMessage(wgettext("Creating server..."), 0, 5);
2095 std::string bind_str = g_settings->get("bind_address");
2096 Address bind_addr(0, 0, 0, 0, port);
2098 if (g_settings->getBool("ipv6_server")) {
2099 bind_addr.setAddress((IPv6AddressBytes *) NULL);
2103 bind_addr.Resolve(bind_str.c_str());
2104 } catch (ResolveError &e) {
2105 infostream << "Resolving bind address \"" << bind_str
2106 << "\" failed: " << e.what()
2107 << " -- Listening on all addresses." << std::endl;
2110 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2111 *error_message = "Unable to listen on " +
2112 bind_addr.serializeString() +
2113 " because IPv6 is disabled";
2114 errorstream << *error_message << std::endl;
2118 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
2119 bind_addr.isIPv6());
2121 server->start(bind_addr);
2126 bool Game::createClient(const std::string &playername,
2127 const std::string &password, std::string *address, u16 port)
2129 showOverlayMessage(wgettext("Creating client..."), 0, 10);
2131 draw_control = new MapDrawControl;
2135 bool could_connect, connect_aborted;
2137 if (!connectToServer(playername, password, address, port,
2138 &could_connect, &connect_aborted))
2141 if (!could_connect) {
2142 if (error_message->empty() && !connect_aborted) {
2143 // Should not happen if error messages are set properly
2144 *error_message = "Connection failed for unknown reason";
2145 errorstream << *error_message << std::endl;
2150 if (!getServerContent(&connect_aborted)) {
2151 if (error_message->empty() && !connect_aborted) {
2152 // Should not happen if error messages are set properly
2153 *error_message = "Connection failed for unknown reason";
2154 errorstream << *error_message << std::endl;
2159 // Update cached textures, meshes and materials
2160 client->afterContentReceived(device);
2164 camera = new Camera(smgr, *draw_control, gamedef);
2165 if (!camera || !camera->successfullyCreated(*error_message))
2167 client->setCamera(camera);
2171 if (m_cache_enable_clouds) {
2172 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2174 *error_message = "Memory allocation error (clouds)";
2175 errorstream << *error_message << std::endl;
2182 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2183 skybox = NULL; // This is used/set later on in the main run loop
2185 local_inventory = new Inventory(itemdef_manager);
2187 if (!(sky && local_inventory)) {
2188 *error_message = "Memory allocation error (sky or local inventory)";
2189 errorstream << *error_message << std::endl;
2193 /* Pre-calculated values
2195 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2197 v2u32 size = t->getOriginalSize();
2198 crack_animation_length = size.Y / size.X;
2200 crack_animation_length = 5;
2206 /* Set window caption
2208 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2210 str += utf8_to_wide(g_version_hash);
2212 str += driver->getName();
2214 device->setWindowCaption(str.c_str());
2216 LocalPlayer *player = client->getEnv().getLocalPlayer();
2217 player->hurt_tilt_timer = 0;
2218 player->hurt_tilt_strength = 0;
2220 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2223 *error_message = "Memory error: could not create HUD";
2224 errorstream << *error_message << std::endl;
2228 mapper = client->getMapper();
2229 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2234 bool Game::initGui()
2236 // First line of debug text
2237 guitext = addStaticText(guienv,
2238 utf8_to_wide(PROJECT_NAME_C).c_str(),
2239 core::rect<s32>(0, 0, 0, 0),
2240 false, false, guiroot);
2242 // Second line of debug text
2243 guitext2 = addStaticText(guienv,
2245 core::rect<s32>(0, 0, 0, 0),
2246 false, false, guiroot);
2248 // At the middle of the screen
2249 // Object infos are shown in this
2250 guitext_info = addStaticText(guienv,
2252 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2253 false, true, guiroot);
2255 // Status text (displays info when showing and hiding GUI stuff, etc.)
2256 guitext_status = addStaticText(guienv,
2258 core::rect<s32>(0, 0, 0, 0),
2259 false, false, guiroot);
2260 guitext_status->setVisible(false);
2263 guitext_chat = addStaticText(
2266 core::rect<s32>(0, 0, 0, 0),
2267 //false, false); // Disable word wrap as of now
2268 false, true, guiroot);
2270 // Remove stale "recent" chat messages from previous connections
2271 chat_backend->clearRecentChat();
2273 // Chat backend and console
2274 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2275 -1, chat_backend, client, &g_menumgr);
2276 if (!gui_chat_console) {
2277 *error_message = "Could not allocate memory for chat console";
2278 errorstream << *error_message << std::endl;
2282 // Profiler text (size is updated when text is updated)
2283 guitext_profiler = addStaticText(guienv,
2285 core::rect<s32>(0, 0, 0, 0),
2286 false, false, guiroot);
2287 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2288 guitext_profiler->setVisible(false);
2289 guitext_profiler->setWordWrap(true);
2291 #ifdef HAVE_TOUCHSCREENGUI
2293 if (g_touchscreengui)
2294 g_touchscreengui->init(texture_src);
2301 bool Game::connectToServer(const std::string &playername,
2302 const std::string &password, std::string *address, u16 port,
2303 bool *connect_ok, bool *aborted)
2305 *connect_ok = false; // Let's not be overly optimistic
2307 bool local_server_mode = false;
2309 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2311 Address connect_address(0, 0, 0, 0, port);
2314 connect_address.Resolve(address->c_str());
2316 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2317 //connect_address.Resolve("localhost");
2318 if (connect_address.isIPv6()) {
2319 IPv6AddressBytes addr_bytes;
2320 addr_bytes.bytes[15] = 1;
2321 connect_address.setAddress(&addr_bytes);
2323 connect_address.setAddress(127, 0, 0, 1);
2325 local_server_mode = true;
2327 } catch (ResolveError &e) {
2328 *error_message = std::string("Couldn't resolve address: ") + e.what();
2329 errorstream << *error_message << std::endl;
2333 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2334 *error_message = "Unable to connect to " +
2335 connect_address.serializeString() +
2336 " because IPv6 is disabled";
2337 errorstream << *error_message << std::endl;
2341 client = new Client(device,
2342 playername.c_str(), password,
2343 *draw_control, texture_src, shader_src,
2344 itemdef_manager, nodedef_manager, sound, eventmgr,
2345 connect_address.isIPv6());
2350 gamedef = client; // Client acts as our GameDef
2352 infostream << "Connecting to server at ";
2353 connect_address.print(&infostream);
2354 infostream << std::endl;
2356 client->connect(connect_address, *address,
2357 simple_singleplayer_mode || local_server_mode);
2360 Wait for server to accept connection
2366 FpsControl fps_control = { 0 };
2368 f32 wait_time = 0; // in seconds
2370 fps_control.last_time = device->getTimer()->getTime();
2372 while (device->run()) {
2374 limitFps(&fps_control, &dtime);
2376 // Update client and server
2377 client->step(dtime);
2380 server->step(dtime);
2383 if (client->getState() == LC_Init) {
2389 if (client->accessDenied()) {
2390 *error_message = "Access denied. Reason: "
2391 + client->accessDeniedReason();
2392 *reconnect_requested = client->reconnectRequested();
2393 errorstream << *error_message << std::endl;
2397 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2399 infostream << "Connect aborted [Escape]" << std::endl;
2404 // Only time out if we aren't waiting for the server we started
2405 if ((*address != "") && (wait_time > 10)) {
2406 *error_message = "Connection timed out.";
2407 errorstream << *error_message << std::endl;
2412 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2414 } catch (con::PeerNotFoundException &e) {
2415 // TODO: Should something be done here? At least an info/error
2423 bool Game::getServerContent(bool *aborted)
2427 FpsControl fps_control = { 0 };
2428 f32 dtime; // in seconds
2430 fps_control.last_time = device->getTimer()->getTime();
2432 while (device->run()) {
2434 limitFps(&fps_control, &dtime);
2436 // Update client and server
2437 client->step(dtime);
2440 server->step(dtime);
2443 if (client->mediaReceived() && client->itemdefReceived() &&
2444 client->nodedefReceived()) {
2449 if (!checkConnection())
2452 if (client->getState() < LC_Init) {
2453 *error_message = "Client disconnected";
2454 errorstream << *error_message << std::endl;
2458 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2460 infostream << "Connect aborted [Escape]" << std::endl;
2467 if (!client->itemdefReceived()) {
2468 const wchar_t *text = wgettext("Item definitions...");
2470 draw_load_screen(text, device, guienv, dtime, progress);
2472 } else if (!client->nodedefReceived()) {
2473 const wchar_t *text = wgettext("Node definitions...");
2475 draw_load_screen(text, device, guienv, dtime, progress);
2478 std::stringstream message;
2479 message.precision(3);
2480 message << gettext("Media...");
2482 if ((USE_CURL == 0) ||
2483 (!g_settings->getBool("enable_remote_media_server"))) {
2484 float cur = client->getCurRate();
2485 std::string cur_unit = gettext("KiB/s");
2489 cur_unit = gettext("MiB/s");
2492 message << " (" << cur << ' ' << cur_unit << ")";
2495 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2496 draw_load_screen(utf8_to_wide(message.str()), device,
2497 guienv, dtime, progress);
2505 /****************************************************************************/
2506 /****************************************************************************
2508 ****************************************************************************/
2509 /****************************************************************************/
2511 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2513 if (runData->nodig_delay_timer >= 0)
2514 runData->nodig_delay_timer -= dtime;
2516 if (runData->object_hit_delay_timer >= 0)
2517 runData->object_hit_delay_timer -= dtime;
2519 runData->time_from_last_punch += dtime;
2523 /* returns false if game should exit, otherwise true
2525 inline bool Game::checkConnection()
2527 if (client->accessDenied()) {
2528 *error_message = "Access denied. Reason: "
2529 + client->accessDeniedReason();
2530 *reconnect_requested = client->reconnectRequested();
2531 errorstream << *error_message << std::endl;
2539 /* returns false if game should exit, otherwise true
2541 inline bool Game::handleCallbacks()
2543 if (g_gamecallback->disconnect_requested) {
2544 g_gamecallback->disconnect_requested = false;
2548 if (g_gamecallback->changepassword_requested) {
2549 (new GUIPasswordChange(guienv, guiroot, -1,
2550 &g_menumgr, client))->drop();
2551 g_gamecallback->changepassword_requested = false;
2554 if (g_gamecallback->changevolume_requested) {
2555 (new GUIVolumeChange(guienv, guiroot, -1,
2556 &g_menumgr, client))->drop();
2557 g_gamecallback->changevolume_requested = false;
2560 if (g_gamecallback->keyconfig_requested) {
2561 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2562 &g_menumgr))->drop();
2563 g_gamecallback->keyconfig_requested = false;
2566 if (g_gamecallback->keyconfig_changed) {
2567 keycache.populate(); // update the cache with new settings
2568 g_gamecallback->keyconfig_changed = false;
2575 void Game::processQueues()
2577 texture_src->processQueue();
2578 itemdef_manager->processQueue(gamedef);
2579 shader_src->processQueue();
2583 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2584 const FpsControl &draw_times, f32 dtime)
2586 float profiler_print_interval =
2587 g_settings->getFloat("profiler_print_interval");
2588 bool print_to_log = true;
2590 if (profiler_print_interval == 0) {
2591 print_to_log = false;
2592 profiler_print_interval = 5;
2595 if (profiler_interval.step(dtime, profiler_print_interval)) {
2597 infostream << "Profiler:" << std::endl;
2598 g_profiler->print(infostream);
2601 update_profiler_gui(guitext_profiler, g_fontengine,
2602 runData.profiler_current_page, runData.profiler_max_page,
2603 driver->getScreenSize().Height);
2605 g_profiler->clear();
2608 addProfilerGraphs(stats, draw_times, dtime);
2612 void Game::addProfilerGraphs(const RunStats &stats,
2613 const FpsControl &draw_times, f32 dtime)
2615 g_profiler->graphAdd("mainloop_other",
2616 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2618 if (draw_times.sleep_time != 0)
2619 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2620 g_profiler->graphAdd("mainloop_dtime", dtime);
2622 g_profiler->add("Elapsed time", dtime);
2623 g_profiler->avg("FPS", 1. / dtime);
2627 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2634 /* Time average and jitter calculation
2636 jp = &stats->dtime_jitter;
2637 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2639 jitter = dtime - jp->avg;
2641 if (jitter > jp->max)
2644 jp->counter += dtime;
2646 if (jp->counter > 0.0) {
2648 jp->max_sample = jp->max;
2649 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2653 /* Busytime average and jitter calculation
2655 jp = &stats->busy_time_jitter;
2656 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2658 jitter = draw_times.busy_time - jp->avg;
2660 if (jitter > jp->max)
2662 if (jitter < jp->min)
2665 jp->counter += dtime;
2667 if (jp->counter > 0.0) {
2669 jp->max_sample = jp->max;
2670 jp->min_sample = jp->min;
2678 /****************************************************************************
2680 ****************************************************************************/
2682 void Game::processUserInput(VolatileRunFlags *flags,
2683 GameRunData *runData, f32 dtime)
2685 // Reset input if window not active or some menu is active
2686 if (device->isWindowActive() == false
2687 || noMenuActive() == false
2688 || guienv->hasFocus(gui_chat_console)) {
2690 #ifdef HAVE_TOUCHSCREENGUI
2691 g_touchscreengui->hide();
2694 #ifdef HAVE_TOUCHSCREENGUI
2695 else if (g_touchscreengui) {
2696 /* on touchscreengui step may generate own input events which ain't
2697 * what we want in case we just did clear them */
2698 g_touchscreengui->step(dtime);
2702 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2703 gui_chat_console->closeConsoleAtOnce();
2706 // Input handler step() (used by the random input generator)
2710 if (current_formspec != NULL)
2711 current_formspec->getAndroidUIInput();
2713 handleAndroidChatInput();
2716 // Increase timer for double tap of "keymap_jump"
2717 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2718 runData->jump_timer += dtime;
2722 &runData->statustext_time,
2723 &runData->jump_timer,
2724 &runData->reset_jump_timer,
2725 &runData->profiler_current_page,
2726 runData->profiler_max_page);
2728 processItemSelection(&runData->new_playeritem);
2732 void Game::processKeyInput(VolatileRunFlags *flags,
2733 float *statustext_time,
2735 bool *reset_jump_timer,
2736 u32 *profiler_current_page,
2737 u32 profiler_max_page)
2740 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2742 if (wasKeyDown(KeyType::DROP)) {
2744 } else if (wasKeyDown(KeyType::AUTORUN)) {
2745 toggleAutorun(statustext_time);
2746 } else if (wasKeyDown(KeyType::INVENTORY)) {
2748 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2749 if (!gui_chat_console->isOpenInhibited()) {
2750 show_pause_menu(¤t_formspec, client, gamedef,
2751 texture_src, device, &input->joystick,
2752 simple_singleplayer_mode);
2754 } else if (wasKeyDown(KeyType::CHAT)) {
2755 openConsole(0.2, L"");
2756 } else if (wasKeyDown(KeyType::CMD)) {
2757 openConsole(0.2, L"/");
2758 } else if (wasKeyDown(KeyType::CONSOLE)) {
2760 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2761 toggleFreeMove(statustext_time);
2762 } else if (wasKeyDown(KeyType::JUMP)) {
2763 toggleFreeMoveAlt(statustext_time, jump_timer);
2764 *reset_jump_timer = true;
2765 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2766 toggleFast(statustext_time);
2767 } else if (wasKeyDown(KeyType::NOCLIP)) {
2768 toggleNoClip(statustext_time);
2769 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2770 toggleCinematic(statustext_time);
2771 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2772 client->makeScreenshot(device);
2773 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2774 toggleHud(statustext_time, &flags->show_hud);
2775 } else if (wasKeyDown(KeyType::MINIMAP)) {
2776 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2777 isKeyDown(KeyType::SNEAK));
2778 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2779 toggleChat(statustext_time, &flags->show_chat);
2780 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2781 toggleFog(statustext_time, &flags->force_fog_off);
2782 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2783 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2784 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2785 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2786 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2787 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2788 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2789 increaseViewRange(statustext_time);
2790 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2791 decreaseViewRange(statustext_time);
2792 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2793 toggleFullViewRange(statustext_time);
2794 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2796 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2798 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2800 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2802 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2803 // Print debug stacks
2804 dstream << "-----------------------------------------"
2806 dstream << "Printing debug stacks:" << std::endl;
2807 dstream << "-----------------------------------------"
2809 debug_stacks_print();
2812 if (!isKeyDown(KeyType::JUMP) && *reset_jump_timer) {
2813 *reset_jump_timer = false;
2819 if (quicktune->hasMessage()) {
2820 std::string msg = quicktune->getMessage();
2821 statustext = utf8_to_wide(msg);
2822 *statustext_time = 0;
2826 void Game::processItemSelection(u16 *new_playeritem)
2828 LocalPlayer *player = client->getEnv().getLocalPlayer();
2830 /* Item selection using mouse wheel
2832 *new_playeritem = client->getPlayerItem();
2834 s32 wheel = input->getMouseWheel();
2835 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2836 player->hud_hotbar_itemcount - 1);
2840 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN)) {
2844 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP)) {
2849 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2851 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2854 /* Item selection using keyboard
2856 for (u16 i = 0; i < 10; i++) {
2857 static const KeyPress *item_keys[10] = {
2858 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2859 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2860 NumberKey + 9, NumberKey + 0,
2863 if (input->wasKeyDown(*item_keys[i])) {
2864 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2865 *new_playeritem = i;
2866 infostream << "Selected item: " << new_playeritem << std::endl;
2874 void Game::dropSelectedItem()
2876 IDropAction *a = new IDropAction();
2878 a->from_inv.setCurrentPlayer();
2879 a->from_list = "main";
2880 a->from_i = client->getPlayerItem();
2881 client->inventoryAction(a);
2885 void Game::openInventory()
2888 * Don't permit to open inventory is CAO or player doesn't exists.
2889 * This prevent showing an empty inventory at player load
2892 LocalPlayer *player = client->getEnv().getLocalPlayer();
2893 if (player == NULL || player->getCAO() == NULL)
2896 infostream << "the_game: " << "Launching inventory" << std::endl;
2898 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2899 TextDest *txt_dst = new TextDestPlayerInventory(client);
2901 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2902 device, &input->joystick, fs_src, txt_dst, client);
2904 InventoryLocation inventoryloc;
2905 inventoryloc.setCurrentPlayer();
2906 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2910 void Game::openConsole(float height, const wchar_t *line)
2913 porting::showInputDialog(gettext("ok"), "", "", 2);
2914 m_android_chat_open = true;
2916 if (gui_chat_console->isOpenInhibited())
2918 gui_chat_console->openConsole(height);
2920 gui_chat_console->setCloseOnEnter(true);
2921 gui_chat_console->replaceAndAddToHistory(line);
2927 void Game::handleAndroidChatInput()
2929 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2930 std::string text = porting::getInputDialogValue();
2931 client->typeChatMessage(utf8_to_wide(text));
2937 void Game::toggleFreeMove(float *statustext_time)
2939 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2941 bool free_move = !g_settings->getBool("free_move");
2942 g_settings->set("free_move", bool_to_cstr(free_move));
2944 *statustext_time = 0;
2945 statustext = msg[free_move];
2946 if (free_move && !client->checkPrivilege("fly"))
2947 statustext += L" (note: no 'fly' privilege)";
2951 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2953 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2954 toggleFreeMove(statustext_time);
2958 void Game::toggleFast(float *statustext_time)
2960 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2961 bool fast_move = !g_settings->getBool("fast_move");
2962 g_settings->set("fast_move", bool_to_cstr(fast_move));
2964 *statustext_time = 0;
2965 statustext = msg[fast_move];
2967 bool has_fast_privs = client->checkPrivilege("fast");
2969 if (fast_move && !has_fast_privs)
2970 statustext += L" (note: no 'fast' privilege)";
2973 m_cache_hold_aux1 = fast_move && has_fast_privs;
2978 void Game::toggleNoClip(float *statustext_time)
2980 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2981 bool noclip = !g_settings->getBool("noclip");
2982 g_settings->set("noclip", bool_to_cstr(noclip));
2984 *statustext_time = 0;
2985 statustext = msg[noclip];
2987 if (noclip && !client->checkPrivilege("noclip"))
2988 statustext += L" (note: no 'noclip' privilege)";
2991 void Game::toggleCinematic(float *statustext_time)
2993 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2994 bool cinematic = !g_settings->getBool("cinematic");
2995 g_settings->set("cinematic", bool_to_cstr(cinematic));
2997 *statustext_time = 0;
2998 statustext = msg[cinematic];
3001 // Add WoW-style autorun by toggling continuous forward.
3002 void Game::toggleAutorun(float *statustext_time)
3004 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
3005 bool autorun_enabled = !g_settings->getBool("continuous_forward");
3006 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
3008 *statustext_time = 0;
3009 statustext = msg[autorun_enabled ? 1 : 0];
3012 void Game::toggleChat(float *statustext_time, bool *flag)
3014 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
3017 *statustext_time = 0;
3018 statustext = msg[*flag];
3022 void Game::toggleHud(float *statustext_time, bool *flag)
3024 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
3027 *statustext_time = 0;
3028 statustext = msg[*flag];
3031 void Game::toggleMinimap(float *statustext_time, bool *flag,
3032 bool show_hud, bool shift_pressed)
3034 if (!show_hud || !g_settings->getBool("enable_minimap"))
3037 if (shift_pressed) {
3038 mapper->toggleMinimapShape();
3042 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
3044 MinimapMode mode = MINIMAP_MODE_OFF;
3045 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
3046 mode = mapper->getMinimapMode();
3047 mode = (MinimapMode)((int)mode + 1);
3052 case MINIMAP_MODE_SURFACEx1:
3053 statustext = L"Minimap in surface mode, Zoom x1";
3055 case MINIMAP_MODE_SURFACEx2:
3056 statustext = L"Minimap in surface mode, Zoom x2";
3058 case MINIMAP_MODE_SURFACEx4:
3059 statustext = L"Minimap in surface mode, Zoom x4";
3061 case MINIMAP_MODE_RADARx1:
3062 statustext = L"Minimap in radar mode, Zoom x1";
3064 case MINIMAP_MODE_RADARx2:
3065 statustext = L"Minimap in radar mode, Zoom x2";
3067 case MINIMAP_MODE_RADARx4:
3068 statustext = L"Minimap in radar mode, Zoom x4";
3071 mode = MINIMAP_MODE_OFF;
3073 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
3074 L"Minimap hidden" : L"Minimap disabled by server";
3077 *statustext_time = 0;
3078 mapper->setMinimapMode(mode);
3081 void Game::toggleFog(float *statustext_time, bool *flag)
3083 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
3086 *statustext_time = 0;
3087 statustext = msg[*flag];
3091 void Game::toggleDebug(float *statustext_time, bool *show_debug,
3092 bool *show_profiler_graph)
3094 // Initial / 3x toggle: Chat only
3095 // 1x toggle: Debug text with chat
3096 // 2x toggle: Debug text with profiler graph
3099 *show_profiler_graph = false;
3100 statustext = L"Debug info shown";
3101 } else if (*show_profiler_graph) {
3102 *show_debug = false;
3103 *show_profiler_graph = false;
3104 statustext = L"Debug info and profiler graph hidden";
3106 *show_profiler_graph = true;
3107 statustext = L"Profiler graph shown";
3109 *statustext_time = 0;
3113 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
3115 static const wchar_t *msg[] = {
3116 L"Camera update enabled",
3117 L"Camera update disabled"
3121 *statustext_time = 0;
3122 statustext = msg[*flag];
3126 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
3127 u32 profiler_max_page)
3129 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
3131 // FIXME: This updates the profiler with incomplete values
3132 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
3133 profiler_max_page, driver->getScreenSize().Height);
3135 if (*profiler_current_page != 0) {
3136 std::wstringstream sstr;
3137 sstr << "Profiler shown (page " << *profiler_current_page
3138 << " of " << profiler_max_page << ")";
3139 statustext = sstr.str();
3141 statustext = L"Profiler hidden";
3143 *statustext_time = 0;
3147 void Game::increaseViewRange(float *statustext_time)
3149 s16 range = g_settings->getS16("viewing_range");
3150 s16 range_new = range + 10;
3151 g_settings->set("viewing_range", itos(range_new));
3152 statustext = utf8_to_wide("Viewing range changed to "
3154 *statustext_time = 0;
3158 void Game::decreaseViewRange(float *statustext_time)
3160 s16 range = g_settings->getS16("viewing_range");
3161 s16 range_new = range - 10;
3166 g_settings->set("viewing_range", itos(range_new));
3167 statustext = utf8_to_wide("Viewing range changed to "
3169 *statustext_time = 0;
3173 void Game::toggleFullViewRange(float *statustext_time)
3175 static const wchar_t *msg[] = {
3176 L"Disabled full viewing range",
3177 L"Enabled full viewing range"
3180 draw_control->range_all = !draw_control->range_all;
3181 infostream << msg[draw_control->range_all] << std::endl;
3182 statustext = msg[draw_control->range_all];
3183 *statustext_time = 0;
3187 void Game::updateCameraDirection(CameraOrientation *cam,
3188 VolatileRunFlags *flags, float dtime)
3190 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3193 if (!random_input) {
3194 // Mac OSX gets upset if this is set every frame
3195 if (device->getCursorControl()->isVisible())
3196 device->getCursorControl()->setVisible(false);
3200 if (flags->first_loop_after_window_activation)
3201 flags->first_loop_after_window_activation = false;
3203 updateCameraOrientation(cam, *flags, dtime);
3205 input->setMousePos((driver->getScreenSize().Width / 2),
3206 (driver->getScreenSize().Height / 2));
3210 // Mac OSX gets upset if this is set every frame
3211 if (device->getCursorControl()->isVisible() == false)
3212 device->getCursorControl()->setVisible(true);
3215 if (!flags->first_loop_after_window_activation)
3216 flags->first_loop_after_window_activation = true;
3221 void Game::updateCameraOrientation(CameraOrientation *cam,
3222 const VolatileRunFlags &flags, float dtime)
3224 #ifdef HAVE_TOUCHSCREENGUI
3225 if (g_touchscreengui) {
3226 cam->camera_yaw = g_touchscreengui->getYaw();
3227 cam->camera_pitch = g_touchscreengui->getPitch();
3231 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3232 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3234 if (flags.invert_mouse
3235 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3239 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3240 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3242 #ifdef HAVE_TOUCHSCREENGUI
3246 if (m_cache_enable_joysticks) {
3247 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3248 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) *
3250 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) *
3254 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3258 void Game::updatePlayerControl(const CameraOrientation &cam)
3260 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3262 // DO NOT use the isKeyDown method for the forward, backward, left, right
3263 // buttons, as the code that uses the controls needs to be able to
3264 // distinguish between the two in order to know when to use joysticks.
3266 PlayerControl control(
3267 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3268 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3269 input->isKeyDown(keycache.key[KeyType::LEFT]),
3270 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3271 isKeyDown(KeyType::JUMP),
3272 isKeyDown(KeyType::SPECIAL1),
3273 isKeyDown(KeyType::SNEAK),
3274 isKeyDown(KeyType::ZOOM),
3279 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3280 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3284 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3285 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3286 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3287 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3288 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3289 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3290 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3291 ( (u32)(isLeftPressed() & 0x1) << 7) |
3292 ( (u32)(isRightPressed() & 0x1) << 8
3296 /* For Android, simulate holding down AUX1 (fast move) if the user has
3297 * the fast_move setting toggled on. If there is an aux1 key defined for
3298 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3301 if (m_cache_hold_aux1) {
3302 control.aux1 = control.aux1 ^ true;
3303 keypress_bits ^= ((u32)(1U << 5));
3307 client->setPlayerControl(control);
3308 LocalPlayer *player = client->getEnv().getLocalPlayer();
3309 player->keyPressed = keypress_bits;
3315 inline void Game::step(f32 *dtime)
3317 bool can_be_and_is_paused =
3318 (simple_singleplayer_mode && g_menumgr.pausesGame());
3320 if (can_be_and_is_paused) { // This is for a singleplayer server
3321 *dtime = 0; // No time passes
3323 if (server != NULL) {
3324 //TimeTaker timer("server->step(dtime)");
3325 server->step(*dtime);
3328 //TimeTaker timer("client.step(dtime)");
3329 client->step(*dtime);
3334 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3336 ClientEvent event = client->getClientEvent();
3338 LocalPlayer *player = client->getEnv().getLocalPlayer();
3340 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3342 if (event.type == CE_PLAYER_DAMAGE &&
3343 client->getHP() != 0) {
3344 //u16 damage = event.player_damage.amount;
3345 //infostream<<"Player damage: "<<damage<<std::endl;
3347 *damage_flash += 100.0;
3348 *damage_flash += 8.0 * event.player_damage.amount;
3350 player->hurt_tilt_timer = 1.5;
3351 player->hurt_tilt_strength = event.player_damage.amount / 4;
3352 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3354 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3355 gamedef->event()->put(e);
3356 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3357 cam->camera_yaw = event.player_force_move.yaw;
3358 cam->camera_pitch = event.player_force_move.pitch;
3359 } else if (event.type == CE_DEATHSCREEN) {
3360 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3361 device, &input->joystick, client);
3363 chat_backend->addMessage(L"", L"You died.");
3365 /* Handle visualization */
3367 player->hurt_tilt_timer = 0;
3368 player->hurt_tilt_strength = 0;
3370 } else if (event.type == CE_SHOW_FORMSPEC) {
3371 FormspecFormSource *fs_src =
3372 new FormspecFormSource(*(event.show_formspec.formspec));
3373 TextDestPlayerInventory *txt_dst =
3374 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3376 create_formspec_menu(¤t_formspec, client, gamedef,
3377 texture_src, device, &input->joystick,
3378 fs_src, txt_dst, client);
3380 delete(event.show_formspec.formspec);
3381 delete(event.show_formspec.formname);
3382 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3383 (event.type == CE_ADD_PARTICLESPAWNER) ||
3384 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3385 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3387 } else if (event.type == CE_HUDADD) {
3388 u32 id = event.hudadd.id;
3390 LocalPlayer *player = client->getEnv().getLocalPlayer();
3391 HudElement *e = player->getHud(id);
3394 delete event.hudadd.pos;
3395 delete event.hudadd.name;
3396 delete event.hudadd.scale;
3397 delete event.hudadd.text;
3398 delete event.hudadd.align;
3399 delete event.hudadd.offset;
3400 delete event.hudadd.world_pos;
3401 delete event.hudadd.size;
3406 e->type = (HudElementType)event.hudadd.type;
3407 e->pos = *event.hudadd.pos;
3408 e->name = *event.hudadd.name;
3409 e->scale = *event.hudadd.scale;
3410 e->text = *event.hudadd.text;
3411 e->number = event.hudadd.number;
3412 e->item = event.hudadd.item;
3413 e->dir = event.hudadd.dir;
3414 e->align = *event.hudadd.align;
3415 e->offset = *event.hudadd.offset;
3416 e->world_pos = *event.hudadd.world_pos;
3417 e->size = *event.hudadd.size;
3419 u32 new_id = player->addHud(e);
3420 //if this isn't true our huds aren't consistent
3421 sanity_check(new_id == id);
3423 delete event.hudadd.pos;
3424 delete event.hudadd.name;
3425 delete event.hudadd.scale;
3426 delete event.hudadd.text;
3427 delete event.hudadd.align;
3428 delete event.hudadd.offset;
3429 delete event.hudadd.world_pos;
3430 delete event.hudadd.size;
3431 } else if (event.type == CE_HUDRM) {
3432 HudElement *e = player->removeHud(event.hudrm.id);
3436 } else if (event.type == CE_HUDCHANGE) {
3437 u32 id = event.hudchange.id;
3438 HudElement *e = player->getHud(id);
3441 delete event.hudchange.v3fdata;
3442 delete event.hudchange.v2fdata;
3443 delete event.hudchange.sdata;
3444 delete event.hudchange.v2s32data;
3448 switch (event.hudchange.stat) {
3450 e->pos = *event.hudchange.v2fdata;
3454 e->name = *event.hudchange.sdata;
3457 case HUD_STAT_SCALE:
3458 e->scale = *event.hudchange.v2fdata;
3462 e->text = *event.hudchange.sdata;
3465 case HUD_STAT_NUMBER:
3466 e->number = event.hudchange.data;
3470 e->item = event.hudchange.data;
3474 e->dir = event.hudchange.data;
3477 case HUD_STAT_ALIGN:
3478 e->align = *event.hudchange.v2fdata;
3481 case HUD_STAT_OFFSET:
3482 e->offset = *event.hudchange.v2fdata;
3485 case HUD_STAT_WORLD_POS:
3486 e->world_pos = *event.hudchange.v3fdata;
3490 e->size = *event.hudchange.v2s32data;
3494 delete event.hudchange.v3fdata;
3495 delete event.hudchange.v2fdata;
3496 delete event.hudchange.sdata;
3497 delete event.hudchange.v2s32data;
3498 } else if (event.type == CE_SET_SKY) {
3499 sky->setVisible(false);
3506 // Handle according to type
3507 if (*event.set_sky.type == "regular") {
3508 sky->setVisible(true);
3509 } else if (*event.set_sky.type == "skybox" &&
3510 event.set_sky.params->size() == 6) {
3511 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3512 skybox = smgr->addSkyBoxSceneNode(
3513 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3514 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3515 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3516 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3517 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3518 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3520 // Handle everything else as plain color
3522 if (*event.set_sky.type != "plain")
3523 infostream << "Unknown sky type: "
3524 << (*event.set_sky.type) << std::endl;
3526 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3529 delete event.set_sky.bgcolor;
3530 delete event.set_sky.type;
3531 delete event.set_sky.params;
3532 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3533 bool enable = event.override_day_night_ratio.do_override;
3534 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3535 client->getEnv().setDayNightRatioOverride(enable, value);
3541 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3542 f32 dtime, float time_from_last_punch)
3544 LocalPlayer *player = client->getEnv().getLocalPlayer();
3547 For interaction purposes, get info about the held item
3549 - Is it a usable item?
3550 - Can it point to liquids?
3552 ItemStack playeritem;
3554 InventoryList *mlist = local_inventory->getList("main");
3556 if (mlist && client->getPlayerItem() < mlist->getSize())
3557 playeritem = mlist->getItem(client->getPlayerItem());
3560 ToolCapabilities playeritem_toolcap =
3561 playeritem.getToolCapabilities(itemdef_manager);
3563 v3s16 old_camera_offset = camera->getOffset();
3565 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3566 GenericCAO *playercao = player->getCAO();
3568 // If playercao not loaded, don't change camera
3569 if (playercao == NULL)
3572 camera->toggleCameraMode();
3574 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3575 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3578 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3579 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3581 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3582 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3584 camera->step(dtime);
3586 v3f camera_position = camera->getPosition();
3587 v3f camera_direction = camera->getDirection();
3588 f32 camera_fov = camera->getFovMax();
3589 v3s16 camera_offset = camera->getOffset();
3591 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3593 if (!flags->disable_camera_update) {
3594 client->getEnv().getClientMap().updateCamera(camera_position,
3595 camera_direction, camera_fov, camera_offset);
3597 if (flags->camera_offset_changed) {
3598 client->updateCameraOffset(camera_offset);
3599 client->getEnv().updateCameraOffset(camera_offset);
3602 clouds->updateCameraOffset(camera_offset);
3608 void Game::updateSound(f32 dtime)
3610 // Update sound listener
3611 v3s16 camera_offset = camera->getOffset();
3612 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3613 v3f(0, 0, 0), // velocity
3614 camera->getDirection(),
3615 camera->getCameraNode()->getUpVector());
3616 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3619 // Update sound maker
3620 soundmaker->step(dtime);
3622 LocalPlayer *player = client->getEnv().getLocalPlayer();
3624 ClientMap &map = client->getEnv().getClientMap();
3625 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3626 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3630 void Game::processPlayerInteraction(GameRunData *runData,
3631 f32 dtime, bool show_hud, bool show_debug)
3633 LocalPlayer *player = client->getEnv().getLocalPlayer();
3635 ItemStack playeritem;
3637 InventoryList *mlist = local_inventory->getList("main");
3639 if (mlist && client->getPlayerItem() < mlist->getSize())
3640 playeritem = mlist->getItem(client->getPlayerItem());
3643 const ItemDefinition &playeritem_def =
3644 playeritem.getDefinition(itemdef_manager);
3646 v3f player_position = player->getPosition();
3647 v3f camera_position = camera->getPosition();
3648 v3f camera_direction = camera->getDirection();
3649 v3s16 camera_offset = camera->getOffset();
3653 Calculate what block is the crosshair pointing to
3656 f32 d = playeritem_def.range; // max. distance
3657 f32 d_hand = itemdef_manager->get("").range;
3659 if (d < 0 && d_hand >= 0)
3664 core::line3d<f32> shootline;
3666 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3668 shootline = core::line3d<f32>(camera_position,
3669 camera_position + camera_direction * BS * (d + 1));
3672 // prevent player pointing anything in front-view
3673 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3674 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3677 #ifdef HAVE_TOUCHSCREENGUI
3679 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3680 shootline = g_touchscreengui->getShootline();
3681 shootline.start += intToFloat(camera_offset, BS);
3682 shootline.end += intToFloat(camera_offset, BS);
3687 PointedThing pointed = getPointedThing(
3689 client, hud, player_position, camera_direction,
3690 camera_position, shootline, d,
3691 playeritem_def.liquids_pointable,
3692 !runData->ldown_for_dig,
3695 runData->selected_object);
3697 if (pointed != runData->pointed_old) {
3698 infostream << "Pointing at " << pointed.dump() << std::endl;
3699 hud->updateSelectionMesh(camera_offset);
3704 - releasing left mouse button
3705 - pointing away from node
3707 if (runData->digging) {
3708 if (getLeftReleased()) {
3709 infostream << "Left button released"
3710 << " (stopped digging)" << std::endl;
3711 runData->digging = false;
3712 } else if (pointed != runData->pointed_old) {
3713 if (pointed.type == POINTEDTHING_NODE
3714 && runData->pointed_old.type == POINTEDTHING_NODE
3715 && pointed.node_undersurface
3716 == runData->pointed_old.node_undersurface) {
3717 // Still pointing to the same node, but a different face.
3720 infostream << "Pointing away from node"
3721 << " (stopped digging)" << std::endl;
3722 runData->digging = false;
3723 hud->updateSelectionMesh(camera_offset);
3727 if (!runData->digging) {
3728 client->interact(1, runData->pointed_old);
3729 client->setCrack(-1, v3s16(0, 0, 0));
3730 runData->dig_time = 0.0;
3734 if (!runData->digging && runData->ldown_for_dig && !isLeftPressed()) {
3735 runData->ldown_for_dig = false;
3738 runData->left_punch = false;
3740 soundmaker->m_player_leftpunch_sound.name = "";
3742 if (isRightPressed())
3743 runData->repeat_rightclick_timer += dtime;
3745 runData->repeat_rightclick_timer = 0;
3747 if (playeritem_def.usable && isLeftPressed()) {
3748 if (getLeftClicked())
3749 client->interact(4, pointed);
3750 } else if (pointed.type == POINTEDTHING_NODE) {
3751 ToolCapabilities playeritem_toolcap =
3752 playeritem.getToolCapabilities(itemdef_manager);
3753 handlePointingAtNode(runData, pointed, playeritem_def,
3754 playeritem_toolcap, dtime);
3755 } else if (pointed.type == POINTEDTHING_OBJECT) {
3756 handlePointingAtObject(runData, pointed, playeritem,
3757 player_position, show_debug);
3758 } else if (isLeftPressed()) {
3759 // When button is held down in air, show continuous animation
3760 runData->left_punch = true;
3761 } else if (getRightClicked()) {
3762 handlePointingAtNothing(runData, playeritem);
3765 runData->pointed_old = pointed;
3767 if (runData->left_punch || getLeftClicked())
3768 camera->setDigging(0); // left click animation
3770 input->resetLeftClicked();
3771 input->resetRightClicked();
3773 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3774 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3776 input->resetLeftReleased();
3777 input->resetRightReleased();
3779 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3780 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3784 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3786 infostream << "Right Clicked in Air" << std::endl;
3787 PointedThing fauxPointed;
3788 fauxPointed.type = POINTEDTHING_NOTHING;
3789 client->interact(5, fauxPointed);
3793 void Game::handlePointingAtNode(GameRunData *runData,
3794 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3795 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3797 v3s16 nodepos = pointed.node_undersurface;
3798 v3s16 neighbourpos = pointed.node_abovesurface;
3801 Check information text of node
3804 ClientMap &map = client->getEnv().getClientMap();
3805 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3808 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3810 MapNode n = map.getNodeNoEx(nodepos);
3812 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3813 infotext = L"Unknown node: ";
3814 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3818 if (runData->nodig_delay_timer <= 0.0 && isLeftPressed()
3819 && client->checkPrivilege("interact")) {
3820 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3823 if ((getRightClicked() ||
3824 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3825 client->checkPrivilege("interact")) {
3826 runData->repeat_rightclick_timer = 0;
3827 infostream << "Ground right-clicked" << std::endl;
3829 if (meta && meta->getString("formspec") != "" && !random_input
3830 && !isKeyDown(KeyType::SNEAK)) {
3831 infostream << "Launching custom inventory view" << std::endl;
3833 InventoryLocation inventoryloc;
3834 inventoryloc.setNodeMeta(nodepos);
3836 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3837 &client->getEnv().getClientMap(), nodepos);
3838 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3840 create_formspec_menu(¤t_formspec, client, gamedef,
3841 texture_src, device, &input->joystick, fs_src, txt_dst, client);
3843 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3845 // Report right click to server
3847 camera->setDigging(1); // right click animation (always shown for feedback)
3849 // If the wielded item has node placement prediction,
3851 bool placed = nodePlacementPrediction(*client,
3853 nodepos, neighbourpos);
3857 client->interact(3, pointed);
3859 soundmaker->m_player_rightpunch_sound =
3860 playeritem_def.sound_place;
3862 soundmaker->m_player_rightpunch_sound =
3865 if (playeritem_def.node_placement_prediction == "" ||
3866 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3867 client->interact(3, pointed); // Report to server
3869 soundmaker->m_player_rightpunch_sound =
3870 playeritem_def.sound_place_failed;
3878 void Game::handlePointingAtObject(GameRunData *runData,
3879 const PointedThing &pointed,
3880 const ItemStack &playeritem,
3881 const v3f &player_position,
3884 infotext = unescape_enriched(
3885 utf8_to_wide(runData->selected_object->infoText()));
3888 if (infotext != L"") {
3891 infotext += unescape_enriched(utf8_to_wide(
3892 runData->selected_object->debugInfoText()));
3895 if (isLeftPressed()) {
3896 bool do_punch = false;
3897 bool do_punch_damage = false;
3899 if (runData->object_hit_delay_timer <= 0.0) {
3901 do_punch_damage = true;
3902 runData->object_hit_delay_timer = object_hit_delay;
3905 if (getLeftClicked())
3909 infostream << "Left-clicked object" << std::endl;
3910 runData->left_punch = true;
3913 if (do_punch_damage) {
3914 // Report direct punch
3915 v3f objpos = runData->selected_object->getPosition();
3916 v3f dir = (objpos - player_position).normalize();
3918 bool disable_send = runData->selected_object->directReportPunch(
3919 dir, &playeritem, runData->time_from_last_punch);
3920 runData->time_from_last_punch = 0;
3923 client->interact(0, pointed);
3925 } else if (getRightClicked()) {
3926 infostream << "Right-clicked object" << std::endl;
3927 client->interact(3, pointed); // place
3932 void Game::handleDigging(GameRunData *runData,
3933 const PointedThing &pointed, const v3s16 &nodepos,
3934 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3936 if (!runData->digging) {
3937 infostream << "Started digging" << std::endl;
3938 client->interact(0, pointed);
3939 runData->digging = true;
3940 runData->ldown_for_dig = true;
3943 LocalPlayer *player = client->getEnv().getLocalPlayer();
3944 ClientMap &map = client->getEnv().getClientMap();
3945 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3947 // NOTE: Similar piece of code exists on the server side for
3949 // Get digging parameters
3950 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3951 &playeritem_toolcap);
3953 // If can't dig, try hand
3954 if (!params.diggable) {
3955 const ItemDefinition &hand = itemdef_manager->get("");
3956 const ToolCapabilities *tp = hand.tool_capabilities;
3959 params = getDigParams(nodedef_manager->get(n).groups, tp);
3962 if (params.diggable == false) {
3963 // I guess nobody will wait for this long
3964 runData->dig_time_complete = 10000000.0;
3966 runData->dig_time_complete = params.time;
3968 if (m_cache_enable_particles) {
3969 const ContentFeatures &features =
3970 client->getNodeDefManager()->get(n);
3971 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3972 player, nodepos, features.tiles);
3976 if (runData->dig_time_complete >= 0.001) {
3977 runData->dig_index = (float)crack_animation_length
3979 / runData->dig_time_complete;
3981 // This is for torches
3982 runData->dig_index = crack_animation_length;
3985 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3987 if (sound_dig.exists() && params.diggable) {
3988 if (sound_dig.name == "__group") {
3989 if (params.main_group != "") {
3990 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3991 soundmaker->m_player_leftpunch_sound.name =
3992 std::string("default_dig_") +
3996 soundmaker->m_player_leftpunch_sound = sound_dig;
4000 // Don't show cracks if not diggable
4001 if (runData->dig_time_complete >= 100000.0) {
4002 } else if (runData->dig_index < crack_animation_length) {
4003 //TimeTaker timer("client.setTempMod");
4004 //infostream<<"dig_index="<<dig_index<<std::endl;
4005 client->setCrack(runData->dig_index, nodepos);
4007 infostream << "Digging completed" << std::endl;
4008 client->interact(2, pointed);
4009 client->setCrack(-1, v3s16(0, 0, 0));
4010 bool is_valid_position;
4011 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
4012 if (is_valid_position)
4013 client->removeNode(nodepos);
4015 if (m_cache_enable_particles) {
4016 const ContentFeatures &features =
4017 client->getNodeDefManager()->get(wasnode);
4018 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
4019 player, nodepos, features.tiles);
4022 runData->dig_time = 0;
4023 runData->digging = false;
4025 runData->nodig_delay_timer =
4026 runData->dig_time_complete / (float)crack_animation_length;
4028 // We don't want a corresponding delay to
4029 // very time consuming nodes
4030 if (runData->nodig_delay_timer > 0.3)
4031 runData->nodig_delay_timer = 0.3;
4033 // We want a slight delay to very little
4034 // time consuming nodes
4035 const float mindelay = 0.15;
4037 if (runData->nodig_delay_timer < mindelay)
4038 runData->nodig_delay_timer = mindelay;
4040 // Send event to trigger sound
4041 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4042 gamedef->event()->put(e);
4045 if (runData->dig_time_complete < 100000.0) {
4046 runData->dig_time += dtime;
4048 runData->dig_time = 0;
4049 client->setCrack(-1, nodepos);
4052 camera->setDigging(0); // left click animation
4056 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
4057 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
4058 const CameraOrientation &cam)
4060 LocalPlayer *player = client->getEnv().getLocalPlayer();
4066 if (draw_control->range_all) {
4067 runData->fog_range = 100000 * BS;
4069 runData->fog_range = 0.9 * draw_control->wanted_range * BS;
4073 Calculate general brightness
4075 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4076 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4077 float direct_brightness;
4080 if (g_settings->getBool("free_move")) {
4081 direct_brightness = time_brightness;
4082 sunlight_seen = true;
4084 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4085 float old_brightness = sky->getBrightness();
4086 direct_brightness = client->getEnv().getClientMap()
4087 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
4088 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4092 float time_of_day = runData->time_of_day;
4093 float time_of_day_smooth = runData->time_of_day_smooth;
4095 time_of_day = client->getEnv().getTimeOfDayF();
4097 const float maxsm = 0.05;
4098 const float todsm = 0.05;
4100 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4101 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4102 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4103 time_of_day_smooth = time_of_day;
4105 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4106 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4107 + (time_of_day + 1.0) * todsm;
4109 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4110 + time_of_day * todsm;
4112 runData->time_of_day = time_of_day;
4113 runData->time_of_day_smooth = time_of_day_smooth;
4115 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4116 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4117 player->getPitch());
4123 v3f player_position = player->getPosition();
4124 if (sky->getCloudsVisible()) {
4125 clouds->setVisible(true);
4126 clouds->step(dtime);
4127 clouds->update(v2f(player_position.X, player_position.Z),
4128 sky->getCloudColor());
4130 clouds->setVisible(false);
4137 client->getParticleManager()->step(dtime);
4143 if (m_cache_enable_fog && !flags.force_fog_off) {
4146 video::EFT_FOG_LINEAR,
4147 runData->fog_range * 0.4,
4148 runData->fog_range * 1.0,
4156 video::EFT_FOG_LINEAR,
4166 Get chat messages from client
4169 v2u32 screensize = driver->getScreenSize();
4171 updateChat(*client, dtime, flags.show_debug, screensize,
4172 flags.show_chat, runData->profiler_current_page,
4173 *chat_backend, guitext_chat);
4179 if (client->getPlayerItem() != runData->new_playeritem)
4180 client->selectPlayerItem(runData->new_playeritem);
4182 // Update local inventory if it has changed
4183 if (client->getLocalInventoryUpdated()) {
4184 //infostream<<"Updating local inventory"<<std::endl;
4185 client->getLocalInventory(*local_inventory);
4186 runData->update_wielded_item_trigger = true;
4189 if (runData->update_wielded_item_trigger) {
4190 // Update wielded tool
4191 InventoryList *mlist = local_inventory->getList("main");
4193 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4194 ItemStack item = mlist->getItem(client->getPlayerItem());
4195 camera->wield(item);
4197 runData->update_wielded_item_trigger = false;
4201 Update block draw list every 200ms or when camera direction has
4204 runData->update_draw_list_timer += dtime;
4206 v3f camera_direction = camera->getDirection();
4207 if (runData->update_draw_list_timer >= 0.2
4208 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4209 || flags.camera_offset_changed) {
4210 runData->update_draw_list_timer = 0;
4211 client->getEnv().getClientMap().updateDrawList(driver);
4212 runData->update_draw_list_last_cam_dir = camera_direction;
4215 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4218 make sure menu is on top
4219 1. Delete formspec menu reference if menu was removed
4220 2. Else, make sure formspec menu is on top
4222 if (current_formspec) {
4223 if (current_formspec->getReferenceCount() == 1) {
4224 current_formspec->drop();
4225 current_formspec = NULL;
4226 } else if (!noMenuActive()) {
4227 guiroot->bringToFront(current_formspec);
4235 video::SColor skycolor = sky->getSkyColor();
4237 TimeTaker tt_draw("mainloop: draw");
4239 TimeTaker timer("beginScene");
4240 driver->beginScene(true, true, skycolor);
4241 stats->beginscenetime = timer.stop(true);
4244 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4245 guienv, screensize, skycolor, flags.show_hud,
4246 flags.show_minimap);
4251 if (flags.show_profiler_graph)
4252 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4257 if (runData->damage_flash > 0.0) {
4258 video::SColor color(std::min(runData->damage_flash, 180.0f),
4262 driver->draw2DRectangle(color,
4263 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4266 runData->damage_flash -= 100.0 * dtime;
4272 if (player->hurt_tilt_timer > 0.0) {
4273 player->hurt_tilt_timer -= dtime * 5;
4275 if (player->hurt_tilt_timer < 0)
4276 player->hurt_tilt_strength = 0;
4280 Update minimap pos and rotation
4282 if (flags.show_minimap && flags.show_hud) {
4283 mapper->setPos(floatToInt(player->getPosition(), BS));
4284 mapper->setAngle(player->getYaw());
4291 TimeTaker timer("endScene");
4293 stats->endscenetime = timer.stop(true);
4296 stats->drawtime = tt_draw.stop(true);
4297 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4301 inline static const char *yawToDirectionString(int yaw)
4303 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4305 yaw = wrapDegrees_0_360(yaw);
4306 yaw = (yaw + 45) % 360 / 90;
4308 return direction[yaw];
4312 void Game::updateGui(float *statustext_time, const RunStats &stats,
4313 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4314 const CameraOrientation &cam)
4316 v2u32 screensize = driver->getScreenSize();
4317 LocalPlayer *player = client->getEnv().getLocalPlayer();
4318 v3f player_position = player->getPosition();
4320 if (flags.show_debug) {
4321 static float drawtime_avg = 0;
4322 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4324 u16 fps = 1.0 / stats.dtime_jitter.avg;
4325 //s32 fps = driver->getFPS();
4327 std::ostringstream os(std::ios_base::binary);
4329 << PROJECT_NAME_C " " << g_version_hash
4331 << " (R: range_all=" << draw_control->range_all << ")"
4332 << std::setprecision(0)
4333 << " drawtime = " << drawtime_avg
4334 << std::setprecision(1)
4335 << ", dtime_jitter = "
4336 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4337 << std::setprecision(1)
4338 << ", v_range = " << draw_control->wanted_range
4339 << std::setprecision(3)
4340 << ", RTT = " << client->getRTT();
4341 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4342 guitext->setVisible(true);
4344 guitext->setVisible(false);
4347 if (guitext->isVisible()) {
4348 core::rect<s32> rect(
4350 screensize.X, 5 + g_fontengine->getTextHeight()
4352 guitext->setRelativePosition(rect);
4355 if (flags.show_debug) {
4356 std::ostringstream os(std::ios_base::binary);
4357 os << std::setprecision(1) << std::fixed
4358 << "(" << (player_position.X / BS)
4359 << ", " << (player_position.Y / BS)
4360 << ", " << (player_position.Z / BS)
4361 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4362 << " " << yawToDirectionString(cam.camera_yaw)
4363 << ") (seed = " << ((u64)client->getMapSeed())
4366 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4367 ClientMap &map = client->getEnv().getClientMap();
4368 const INodeDefManager *nodedef = client->getNodeDefManager();
4369 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4370 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4371 const ContentFeatures &features = nodedef->get(n);
4372 os << " (pointing_at = " << nodedef->get(n).name
4373 << " - " << features.tiledef[0].name.c_str()
4378 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4379 guitext2->setVisible(true);
4381 core::rect<s32> rect(
4382 5, 5 + g_fontengine->getTextHeight(),
4383 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4385 guitext2->setRelativePosition(rect);
4387 guitext2->setVisible(false);
4390 setStaticText(guitext_info, infotext.c_str());
4391 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4393 float statustext_time_max = 1.5;
4395 if (!statustext.empty()) {
4396 *statustext_time += dtime;
4398 if (*statustext_time >= statustext_time_max) {
4400 *statustext_time = 0;
4404 setStaticText(guitext_status, statustext.c_str());
4405 guitext_status->setVisible(!statustext.empty());
4407 if (!statustext.empty()) {
4408 s32 status_width = guitext_status->getTextWidth();
4409 s32 status_height = guitext_status->getTextHeight();
4410 s32 status_y = screensize.Y - 150;
4411 s32 status_x = (screensize.X - status_width) / 2;
4412 core::rect<s32> rect(
4413 status_x , status_y - status_height,
4414 status_x + status_width, status_y
4416 guitext_status->setRelativePosition(rect);
4419 video::SColor initial_color(255, 0, 0, 0);
4421 if (guienv->getSkin())
4422 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4424 video::SColor final_color = initial_color;
4425 final_color.setAlpha(0);
4426 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4427 initial_color, final_color,
4428 pow(*statustext_time / statustext_time_max, 2.0f));
4429 guitext_status->setOverrideColor(fade_color);
4430 guitext_status->enableOverrideColor(true);
4435 /* Log times and stuff for visualization */
4436 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4438 Profiler::GraphValues values;
4439 g_profiler->graphGet(values);
4445 /****************************************************************************
4447 ****************************************************************************/
4449 /* On some computers framerate doesn't seem to be automatically limited
4451 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4453 // not using getRealTime is necessary for wine
4454 device->getTimer()->tick(); // Maker sure device time is up-to-date
4455 u32 time = device->getTimer()->getTime();
4456 u32 last_time = fps_timings->last_time;
4458 if (time > last_time) // Make sure time hasn't overflowed
4459 fps_timings->busy_time = time - last_time;
4461 fps_timings->busy_time = 0;
4463 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4464 ? g_settings->getFloat("pause_fps_max")
4465 : g_settings->getFloat("fps_max"));
4467 if (fps_timings->busy_time < frametime_min) {
4468 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4469 device->sleep(fps_timings->sleep_time);
4471 fps_timings->sleep_time = 0;
4474 /* Get the new value of the device timer. Note that device->sleep() may
4475 * not sleep for the entire requested time as sleep may be interrupted and
4476 * therefore it is arguably more accurate to get the new time from the
4477 * device rather than calculating it by adding sleep_time to time.
4480 device->getTimer()->tick(); // Update device timer
4481 time = device->getTimer()->getTime();
4483 if (time > last_time) // Make sure last_time hasn't overflowed
4484 *dtime = (time - last_time) / 1000.0;
4488 fps_timings->last_time = time;
4491 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4492 // pass a copy of it to this function
4493 // Note: \p msg must be allocated using new (not malloc())
4494 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4495 int percent, bool draw_clouds)
4497 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4501 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4503 ((Game *)data)->readSettings();
4506 void Game::readSettings()
4508 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4509 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4510 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4511 m_cache_enable_particles = g_settings->getBool("enable_particles");
4512 m_cache_enable_fog = g_settings->getBool("enable_fog");
4513 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4514 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4515 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4517 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4520 /****************************************************************************/
4521 /****************************************************************************
4523 ****************************************************************************/
4524 /****************************************************************************/
4526 void Game::extendedResourceCleanup()
4528 // Extended resource accounting
4529 infostream << "Irrlicht resources after cleanup:" << std::endl;
4530 infostream << "\tRemaining meshes : "
4531 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4532 infostream << "\tRemaining textures : "
4533 << driver->getTextureCount() << std::endl;
4535 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4536 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4537 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4541 clearTextureNameCache();
4542 infostream << "\tRemaining materials: "
4543 << driver-> getMaterialRendererCount()
4544 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4548 /****************************************************************************/
4549 /****************************************************************************
4550 extern function for launching the game
4551 ****************************************************************************/
4552 /****************************************************************************/
4554 void the_game(bool *kill,
4556 InputHandler *input,
4557 IrrlichtDevice *device,
4559 const std::string &map_dir,
4560 const std::string &playername,
4561 const std::string &password,
4562 const std::string &address, // If empty local server is created
4565 std::string &error_message,
4566 ChatBackend &chat_backend,
4567 bool *reconnect_requested,
4568 const SubgameSpec &gamespec, // Used for local game
4569 bool simple_singleplayer_mode)
4573 /* Make a copy of the server address because if a local singleplayer server
4574 * is created then this is updated and we don't want to change the value
4575 * passed to us by the calling function
4577 std::string server_address = address;
4581 if (game.startup(kill, random_input, input, device, map_dir,
4582 playername, password, &server_address, port, error_message,
4583 reconnect_requested, &chat_backend, gamespec,
4584 simple_singleplayer_mode)) {
4589 } catch (SerializationError &e) {
4590 error_message = std::string("A serialization error occurred:\n")
4591 + e.what() + "\n\nThe server is probably "
4592 " running a different version of " PROJECT_NAME_C ".";
4593 errorstream << error_message << std::endl;
4594 } catch (ServerError &e) {
4595 error_message = e.what();
4596 errorstream << "ServerError: " << error_message << std::endl;
4597 } catch (ModError &e) {
4598 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4599 errorstream << "ModError: " << error_message << std::endl;