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 "clientmap.h"
30 #include "content_cao.h"
31 #include "drawscene.h"
32 #include "event_manager.h"
33 #include "fontengine.h"
38 #include "guiChatConsole.h"
39 #include "guiFormSpecMenu.h"
40 #include "guiKeyChangeMenu.h"
41 #include "guiPasswordChange.h"
42 #include "guiVolumeChange.h"
44 #include "mainmenumanager.h"
46 #include "nodedef.h" // Needed for determining pointing to nodes
47 #include "nodemetadata.h"
48 #include "particles.h"
50 #include "quicktune_shortcutter.h"
53 #include "shader.h" // For ShaderSource
57 #include "util/directiontables.h"
58 #include "util/pointedthing.h"
59 #include "irrlicht_changes/static_text.h"
62 #include "mapblock_mesh.h"
67 #include "sound_openal.h"
70 #ifdef HAVE_TOUCHSCREENGUI
71 #include "touchscreengui.h"
74 extern Settings *g_settings;
75 extern Profiler *g_profiler;
81 struct TextDestNodeMetadata : public TextDest {
82 TextDestNodeMetadata(v3s16 p, Client *client)
87 // This is deprecated I guess? -celeron55
88 void gotText(std::wstring text)
90 std::string ntext = wide_to_utf8(text);
91 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
92 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
94 fields["text"] = ntext;
95 m_client->sendNodemetaFields(m_p, "", fields);
97 void gotText(const StringMap &fields)
99 m_client->sendNodemetaFields(m_p, "", fields);
106 struct TextDestPlayerInventory : public TextDest {
107 TextDestPlayerInventory(Client *client)
112 TextDestPlayerInventory(Client *client, std::string formname)
115 m_formname = formname;
117 void gotText(const StringMap &fields)
119 m_client->sendInventoryFields(m_formname, fields);
125 struct LocalFormspecHandler : public TextDest {
126 LocalFormspecHandler();
127 LocalFormspecHandler(std::string formname) :
130 m_formname = formname;
133 LocalFormspecHandler(std::string formname, Client *client) :
136 m_formname = formname;
139 void gotText(std::wstring message)
141 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
144 void gotText(const StringMap &fields)
146 if (m_formname == "MT_PAUSE_MENU") {
147 if (fields.find("btn_sound") != fields.end()) {
148 g_gamecallback->changeVolume();
152 if (fields.find("btn_key_config") != fields.end()) {
153 g_gamecallback->keyConfig();
157 if (fields.find("btn_exit_menu") != fields.end()) {
158 g_gamecallback->disconnect();
162 if (fields.find("btn_exit_os") != fields.end()) {
163 g_gamecallback->exitToOS();
167 if (fields.find("btn_change_password") != fields.end()) {
168 g_gamecallback->changePassword();
172 if (fields.find("quit") != fields.end()) {
176 if (fields.find("btn_continue") != fields.end()) {
181 if (m_formname == "MT_DEATH_SCREEN") {
182 assert(m_client != 0);
184 if ((fields.find("btn_respawn") != fields.end())) {
185 m_client->sendRespawn();
189 if (fields.find("quit") != fields.end()) {
190 m_client->sendRespawn();
195 // don't show error message for unhandled cursor keys
196 if ((fields.find("key_up") != fields.end()) ||
197 (fields.find("key_down") != fields.end()) ||
198 (fields.find("key_left") != fields.end()) ||
199 (fields.find("key_right") != fields.end())) {
203 errorstream << "LocalFormspecHandler::gotText unhandled >"
204 << m_formname << "< event" << std::endl;
207 StringMap::const_iterator it;
208 for (it = fields.begin(); it != fields.end(); ++it) {
209 errorstream << "\t" << i << ": " << it->first
210 << "=" << it->second << std::endl;
218 /* Form update callback */
220 class NodeMetadataFormSource: public IFormSource
223 NodeMetadataFormSource(ClientMap *map, v3s16 p):
228 std::string getForm()
230 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
235 return meta->getString("formspec");
237 std::string resolveText(std::string str)
239 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
244 return meta->resolveString(str);
251 class PlayerInventoryFormSource: public IFormSource
254 PlayerInventoryFormSource(Client *client):
258 std::string getForm()
260 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
261 return player->inventory_formspec;
268 Check if a node is pointable
270 inline bool isPointableNode(const MapNode &n,
271 Client *client, bool liquids_pointable)
273 const ContentFeatures &features = client->getNodeDefManager()->get(n);
274 return features.pointable ||
275 (liquids_pointable && features.isLiquid());
278 static inline void getNeighborConnectingFace(v3s16 p, INodeDefManager *nodedef,
279 ClientMap *map, MapNode n, u8 bitmask, u8 *neighbors)
281 MapNode n2 = map->getNodeNoEx(p);
282 if (nodedef->nodeboxConnects(n, n2, bitmask))
283 *neighbors |= bitmask;
286 static inline u8 getNeighbors(v3s16 p, INodeDefManager *nodedef, ClientMap *map, MapNode n)
289 const ContentFeatures &f = nodedef->get(n);
290 // locate possible neighboring nodes to connect to
291 if (f.drawtype == NDT_NODEBOX && f.node_box.type == NODEBOX_CONNECTED) {
295 getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
299 getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
303 getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
307 getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
311 getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
315 getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
322 Find what the player is pointing at
324 PointedThing getPointedThing(Client *client, Hud *hud, const v3f &player_position,
325 const v3f &camera_direction, const v3f &camera_position,
326 core::line3d<f32> shootline, f32 d, bool liquids_pointable,
327 bool look_for_object, const v3s16 &camera_offset,
328 ClientActiveObject *&selected_object)
332 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
333 selectionboxes->clear();
334 static const bool show_entity_selectionbox = g_settings->getBool("show_entity_selectionbox");
336 selected_object = NULL;
338 INodeDefManager *nodedef = client->getNodeDefManager();
339 ClientMap &map = client->getEnv().getClientMap();
341 f32 min_distance = BS * 1001;
343 // First try to find a pointed at active object
344 if (look_for_object) {
345 selected_object = client->getSelectedActiveObject(d * BS,
346 camera_position, shootline);
348 if (selected_object != NULL) {
349 if (show_entity_selectionbox &&
350 selected_object->doShowSelectionBox()) {
351 aabb3f *selection_box = selected_object->getSelectionBox();
352 // Box should exist because object was
353 // returned in the first place
354 assert(selection_box);
356 v3f pos = selected_object->getPosition();
357 selectionboxes->push_back(aabb3f(
358 selection_box->MinEdge, selection_box->MaxEdge));
359 hud->setSelectionPos(pos, camera_offset);
362 min_distance = (selected_object->getPosition() - camera_position).getLength();
364 result.type = POINTEDTHING_OBJECT;
365 result.object_id = selected_object->getId();
369 // That didn't work, try to find a pointed at node
371 v3s16 pos_i = floatToInt(player_position, BS);
373 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
377 s16 ystart = pos_i.Y - (camera_direction.Y < 0 ? a : 1);
378 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
379 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
380 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
381 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
382 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
384 // Prevent signed number overflow
394 v3s16 pointed_pos(0, 0, 0);
396 for (s16 y = ystart; y <= yend; y++) {
397 for (s16 z = zstart; z <= zend; z++) {
398 for (s16 x = xstart; x <= xend; x++) {
400 bool is_valid_position;
403 n = map.getNodeNoEx(p, &is_valid_position);
404 if (!is_valid_position) {
407 if (!isPointableNode(n, client, liquids_pointable)) {
411 std::vector<aabb3f> boxes;
412 n.getSelectionBoxes(nodedef, &boxes, getNeighbors(p, nodedef, &map, n));
415 v3f npf = intToFloat(np, BS);
416 for (std::vector<aabb3f>::const_iterator
418 i != boxes.end(); ++i) {
423 v3f centerpoint = box.getCenter();
424 f32 distance = (centerpoint - camera_position).getLength();
425 if (distance >= min_distance) {
428 if (!box.intersectsWithLine(shootline)) {
431 result.type = POINTEDTHING_NODE;
432 min_distance = distance;
439 if (result.type == POINTEDTHING_NODE) {
441 MapNode n = map.getNodeNoEx(pointed_pos);
442 v3f npf = intToFloat(pointed_pos, BS);
443 std::vector<aabb3f> boxes;
444 n.getSelectionBoxes(nodedef, &boxes, getNeighbors(pointed_pos, nodedef, &map, n));
445 f32 face_min_distance = 1000 * BS;
446 for (std::vector<aabb3f>::const_iterator
448 i != boxes.end(); ++i) {
452 for (u16 j = 0; j < 6; j++) {
453 v3s16 facedir = g_6dirs[j];
454 aabb3f facebox = box;
456 facebox.MinEdge.X = facebox.MaxEdge.X - d;
457 } else if (facedir.X < 0) {
458 facebox.MaxEdge.X = facebox.MinEdge.X + d;
459 } else if (facedir.Y > 0) {
460 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
461 } else if (facedir.Y < 0) {
462 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
463 } else if (facedir.Z > 0) {
464 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
465 } else if (facedir.Z < 0) {
466 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
468 v3f centerpoint = facebox.getCenter();
469 f32 distance = (centerpoint - camera_position).getLength();
470 if (distance >= face_min_distance)
472 if (!facebox.intersectsWithLine(shootline))
474 result.node_abovesurface = pointed_pos + facedir;
475 face_min_distance = distance;
478 selectionboxes->clear();
479 for (std::vector<aabb3f>::const_iterator
481 i != boxes.end(); ++i) {
483 box.MinEdge += v3f(-d, -d, -d);
484 box.MaxEdge += v3f(d, d, d);
485 selectionboxes->push_back(box);
487 hud->setSelectionPos(intToFloat(pointed_pos, BS), camera_offset);
488 result.node_undersurface = pointed_pos;
491 // Update selection mesh light level and vertex colors
492 if (selectionboxes->size() > 0) {
493 v3f pf = hud->getSelectionPos();
494 v3s16 p = floatToInt(pf, BS);
496 // Get selection mesh light level
497 MapNode n = map.getNodeNoEx(p);
498 u16 node_light = getInteriorLight(n, -1, nodedef);
499 u16 light_level = node_light;
501 for (u8 i = 0; i < 6; i++) {
502 n = map.getNodeNoEx(p + g_6dirs[i]);
503 node_light = getInteriorLight(n, -1, nodedef);
504 if (node_light > light_level)
505 light_level = node_light;
508 video::SColor c = MapBlock_LightColor(255, light_level, 0);
510 u8 night = c.getGreen();
511 u32 daynight_ratio = client->getEnv().getDayNightRatio();
512 finalColorBlend(c, day, night, daynight_ratio);
514 // Modify final color a bit with time
515 u32 timer = porting::getTimeMs() % 5000;
516 float timerf = (float)(irr::core::PI * ((timer / 2500.0) - 0.5));
517 float sin_r = 0.08 * sin(timerf);
518 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
519 float sin_b = 0.08 * sin(timerf + irr::core::PI);
520 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
521 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
522 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
524 // Set mesh final color
525 hud->setSelectionMeshColor(c);
530 /* Profiler display */
532 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
533 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
535 if (show_profiler == 0) {
536 guitext_profiler->setVisible(false);
539 std::ostringstream os(std::ios_base::binary);
540 g_profiler->printPage(os, show_profiler, show_profiler_max);
541 std::wstring text = utf8_to_wide(os.str());
542 setStaticText(guitext_profiler, text.c_str());
543 guitext_profiler->setVisible(true);
545 s32 w = fe->getTextWidth(text.c_str());
550 unsigned text_height = fe->getTextHeight();
552 core::position2di upper_left, lower_right;
555 upper_left.Y = (text_height + 5) * 2;
556 lower_right.X = 12 + w;
557 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
559 if (lower_right.Y > screen_height * 2 / 3)
560 lower_right.Y = screen_height * 2 / 3;
562 core::rect<s32> rect(upper_left, lower_right);
564 guitext_profiler->setRelativePosition(rect);
565 guitext_profiler->setVisible(true);
573 Profiler::GraphValues values;
579 Meta(float initial = 0,
580 video::SColor color = video::SColor(255, 255, 255, 255)):
586 std::deque<Piece> m_log;
594 void put(const Profiler::GraphValues &values)
597 piece.values = values;
598 m_log.push_back(piece);
600 while (m_log.size() > m_log_max_size)
601 m_log.erase(m_log.begin());
604 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
605 gui::IGUIFont *font) const
607 std::map<std::string, Meta> m_meta;
609 for (std::deque<Piece>::const_iterator k = m_log.begin();
610 k != m_log.end(); ++k) {
611 const Piece &piece = *k;
613 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
614 i != piece.values.end(); ++i) {
615 const std::string &id = i->first;
616 const float &value = i->second;
617 std::map<std::string, Meta>::iterator j =
620 if (j == m_meta.end()) {
621 m_meta[id] = Meta(value);
625 if (value < j->second.min)
626 j->second.min = value;
628 if (value > j->second.max)
629 j->second.max = value;
634 static const video::SColor usable_colors[] = {
635 video::SColor(255, 255, 100, 100),
636 video::SColor(255, 90, 225, 90),
637 video::SColor(255, 100, 100, 255),
638 video::SColor(255, 255, 150, 50),
639 video::SColor(255, 220, 220, 100)
641 static const u32 usable_colors_count =
642 sizeof(usable_colors) / sizeof(*usable_colors);
643 u32 next_color_i = 0;
645 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
646 i != m_meta.end(); ++i) {
647 Meta &meta = i->second;
648 video::SColor color(255, 200, 200, 200);
650 if (next_color_i < usable_colors_count)
651 color = usable_colors[next_color_i++];
657 s32 textx = x_left + m_log_max_size + 15;
658 s32 textx2 = textx + 200 - 15;
661 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
662 i != m_meta.end(); ++i) {
663 const std::string &id = i->first;
664 const Meta &meta = i->second;
666 s32 y = y_bottom - meta_i * 50;
667 float show_min = meta.min;
668 float show_max = meta.max;
670 if (show_min >= -0.0001 && show_max >= -0.0001) {
671 if (show_min <= show_max * 0.5)
677 snprintf(buf, 10, "%.3g", show_max);
678 font->draw(utf8_to_wide(buf).c_str(),
679 core::rect<s32>(textx, y - graphh,
680 textx2, y - graphh + texth),
682 snprintf(buf, 10, "%.3g", show_min);
683 font->draw(utf8_to_wide(buf).c_str(),
684 core::rect<s32>(textx, y - texth,
687 font->draw(utf8_to_wide(id).c_str(),
688 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
689 textx2, y - graphh / 2 + texth / 2),
692 s32 graph1h = graphh;
693 bool relativegraph = (show_min != 0 && show_min != show_max);
694 float lastscaledvalue = 0.0;
695 bool lastscaledvalue_exists = false;
697 for (std::deque<Piece>::const_iterator j = m_log.begin();
698 j != m_log.end(); ++j) {
699 const Piece &piece = *j;
701 bool value_exists = false;
702 Profiler::GraphValues::const_iterator k =
703 piece.values.find(id);
705 if (k != piece.values.end()) {
712 lastscaledvalue_exists = false;
716 float scaledvalue = 1.0;
718 if (show_max != show_min)
719 scaledvalue = (value - show_min) / (show_max - show_min);
721 if (scaledvalue == 1.0 && value == 0) {
723 lastscaledvalue_exists = false;
728 if (lastscaledvalue_exists) {
729 s32 ivalue1 = lastscaledvalue * graph1h;
730 s32 ivalue2 = scaledvalue * graph1h;
731 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
732 v2s32(x, graph1y - ivalue2), meta.color);
735 lastscaledvalue = scaledvalue;
736 lastscaledvalue_exists = true;
738 s32 ivalue = scaledvalue * graph1h;
739 driver->draw2DLine(v2s32(x, graph1y),
740 v2s32(x, graph1y - ivalue), meta.color);
751 class NodeDugEvent: public MtEvent
757 NodeDugEvent(v3s16 p, MapNode n):
761 const char *getType() const
769 ISoundManager *m_sound;
770 INodeDefManager *m_ndef;
772 float m_player_step_timer;
774 SimpleSoundSpec m_player_step_sound;
775 SimpleSoundSpec m_player_leftpunch_sound;
776 SimpleSoundSpec m_player_rightpunch_sound;
778 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
781 m_player_step_timer(0)
785 void playPlayerStep()
787 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
788 m_player_step_timer = 0.03;
789 m_sound->playSound(m_player_step_sound, false);
793 static void viewBobbingStep(MtEvent *e, void *data)
795 SoundMaker *sm = (SoundMaker *)data;
796 sm->playPlayerStep();
799 static void playerRegainGround(MtEvent *e, void *data)
801 SoundMaker *sm = (SoundMaker *)data;
802 sm->playPlayerStep();
805 static void playerJump(MtEvent *e, void *data)
807 //SoundMaker *sm = (SoundMaker*)data;
810 static void cameraPunchLeft(MtEvent *e, void *data)
812 SoundMaker *sm = (SoundMaker *)data;
813 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
816 static void cameraPunchRight(MtEvent *e, void *data)
818 SoundMaker *sm = (SoundMaker *)data;
819 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
822 static void nodeDug(MtEvent *e, void *data)
824 SoundMaker *sm = (SoundMaker *)data;
825 NodeDugEvent *nde = (NodeDugEvent *)e;
826 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
829 static void playerDamage(MtEvent *e, void *data)
831 SoundMaker *sm = (SoundMaker *)data;
832 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
835 static void playerFallingDamage(MtEvent *e, void *data)
837 SoundMaker *sm = (SoundMaker *)data;
838 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
841 void registerReceiver(MtEventManager *mgr)
843 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
844 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
845 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
846 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
847 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
848 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
849 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
850 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
853 void step(float dtime)
855 m_player_step_timer -= dtime;
859 // Locally stored sounds don't need to be preloaded because of this
860 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
862 std::set<std::string> m_fetched;
864 void fetchSounds(const std::string &name,
865 std::set<std::string> &dst_paths,
866 std::set<std::string> &dst_datas)
868 if (m_fetched.count(name))
871 m_fetched.insert(name);
872 std::string base = porting::path_share + DIR_DELIM + "testsounds";
873 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
874 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
875 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
876 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
877 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
878 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
879 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
880 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
881 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
882 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
883 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
887 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
890 bool *m_force_fog_off;
896 void onSettingsChange(const std::string &name)
898 if (name == "enable_fog")
899 m_fogEnabled = g_settings->getBool("enable_fog");
902 static void SettingsCallback(const std::string &name, void *userdata)
904 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
907 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
908 f32 *fog_range, Client *client) :
910 m_force_fog_off(force_fog_off),
911 m_fog_range(fog_range),
914 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
915 m_fogEnabled = g_settings->getBool("enable_fog");
918 ~GameGlobalShaderConstantSetter()
920 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
923 virtual void onSetConstants(video::IMaterialRendererServices *services,
930 video::SColor bgcolor = m_sky->getBgColor();
931 video::SColorf bgcolorf(bgcolor);
932 float bgcolorfa[4] = {
938 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
941 float fog_distance = 10000 * BS;
943 if (m_fogEnabled && !*m_force_fog_off)
944 fog_distance = *m_fog_range;
946 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
949 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
950 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
951 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
953 u32 animation_timer = porting::getTimeMs() % 100000;
954 float animation_timer_f = (float)animation_timer / 100000.0;
955 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
956 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
958 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
959 v3f eye_position = player->getEyePosition();
960 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
961 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
963 v3f minimap_yaw_vec = m_client->getMapper()->getYawVec();
964 services->setPixelShaderConstant("yawVec", (irr::f32 *)&minimap_yaw_vec, 3);
966 // Uniform sampler layers
967 // before 1.8 there isn't a "integer interface", only float
968 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
972 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
973 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
974 services->setPixelShaderConstant("textureFlags" , (irr::f32 *)&layer2, 1);
979 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
980 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
981 services->setPixelShaderConstant("textureFlags" , (irr::s32 *)&layer2, 1);
986 bool nodePlacementPrediction(Client &client,
987 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
989 std::string prediction = playeritem_def.node_placement_prediction;
990 INodeDefManager *nodedef = client.ndef();
991 ClientMap &map = client.getEnv().getClientMap();
993 bool is_valid_position;
995 node = map.getNodeNoEx(nodepos, &is_valid_position);
996 if (!is_valid_position)
999 if (prediction != "" && !nodedef->get(node).rightclickable) {
1000 verbosestream << "Node placement prediction for "
1001 << playeritem_def.name << " is "
1002 << prediction << std::endl;
1003 v3s16 p = neighbourpos;
1005 // Place inside node itself if buildable_to
1006 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
1007 if (is_valid_position)
1009 if (nodedef->get(n_under).buildable_to)
1012 node = map.getNodeNoEx(p, &is_valid_position);
1013 if (is_valid_position &&!nodedef->get(node).buildable_to)
1018 // Find id of predicted node
1020 bool found = nodedef->getId(prediction, id);
1023 errorstream << "Node placement prediction failed for "
1024 << playeritem_def.name << " (places "
1026 << ") - Name not known" << std::endl;
1030 // Predict param2 for facedir and wallmounted nodes
1033 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
1034 v3s16 dir = nodepos - neighbourpos;
1036 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
1037 param2 = dir.Y < 0 ? 1 : 0;
1038 } else if (abs(dir.X) > abs(dir.Z)) {
1039 param2 = dir.X < 0 ? 3 : 2;
1041 param2 = dir.Z < 0 ? 5 : 4;
1045 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
1046 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
1048 if (abs(dir.X) > abs(dir.Z)) {
1049 param2 = dir.X < 0 ? 3 : 1;
1051 param2 = dir.Z < 0 ? 2 : 0;
1055 assert(param2 <= 5);
1057 //Check attachment if node is in group attached_node
1058 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
1059 static v3s16 wallmounted_dirs[8] = {
1069 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
1070 pp = p + wallmounted_dirs[param2];
1072 pp = p + v3s16(0, -1, 0);
1074 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
1078 // Add node to client map
1079 MapNode n(id, 0, param2);
1082 LocalPlayer *player = client.getEnv().getLocalPlayer();
1084 // Dont place node when player would be inside new node
1085 // NOTE: This is to be eventually implemented by a mod as client-side Lua
1086 if (!nodedef->get(n).walkable ||
1087 g_settings->getBool("enable_build_where_you_stand") ||
1088 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
1089 (nodedef->get(n).walkable &&
1090 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
1091 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
1093 // This triggers the required mesh update too
1094 client.addNode(p, n);
1097 } catch (InvalidPositionException &e) {
1098 errorstream << "Node placement prediction failed for "
1099 << playeritem_def.name << " (places "
1101 << ") - Position not loaded" << std::endl;
1108 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1109 InventoryManager *invmgr, IGameDef *gamedef,
1110 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1111 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1114 if (*cur_formspec == 0) {
1115 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1116 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1117 (*cur_formspec)->doPause = false;
1120 Caution: do not call (*cur_formspec)->drop() here --
1121 the reference might outlive the menu, so we will
1122 periodically check if *cur_formspec is the only
1123 remaining reference (i.e. the menu was removed)
1124 and delete it in that case.
1128 (*cur_formspec)->setFormSource(fs_src);
1129 (*cur_formspec)->setTextDest(txt_dest);
1134 #define SIZE_TAG "size[11,5.5]"
1136 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1139 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1140 InventoryManager *invmgr, IGameDef *gamedef,
1141 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1143 std::string formspec =
1144 std::string(FORMSPEC_VERSION_STRING) +
1146 "bgcolor[#320000b4;true]"
1147 "label[4.85,1.35;" + gettext("You died.") + "]"
1148 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1152 /* Note: FormspecFormSource and LocalFormspecHandler
1153 * are deleted by guiFormSpecMenu */
1154 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1155 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1157 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1160 /******************************************************************************/
1161 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1162 InventoryManager *invmgr, IGameDef *gamedef,
1163 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1164 bool singleplayermode)
1167 std::string control_text = strgettext("Default Controls:\n"
1168 "No menu visible:\n"
1169 "- single tap: button activate\n"
1170 "- double tap: place/use\n"
1171 "- slide finger: look around\n"
1172 "Menu/Inventory visible:\n"
1173 "- double tap (outside):\n"
1175 "- touch stack, touch slot:\n"
1177 "- touch&drag, tap 2nd finger\n"
1178 " --> place single item to slot\n"
1181 std::string control_text = strgettext("Default Controls:\n"
1183 "- Space: jump/climb\n"
1184 "- Shift: sneak/go down\n"
1187 "- Mouse: turn/look\n"
1188 "- Mouse left: dig/punch\n"
1189 "- Mouse right: place/use\n"
1190 "- Mouse wheel: select item\n"
1195 float ypos = singleplayermode ? 0.5 : 0.1;
1196 std::ostringstream os;
1198 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1199 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1200 << strgettext("Continue") << "]";
1202 if (!singleplayermode) {
1203 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1204 << strgettext("Change Password") << "]";
1208 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1209 << strgettext("Sound Volume") << "]";
1210 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1211 << strgettext("Change Keys") << "]";
1213 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1214 << strgettext("Exit to Menu") << "]";
1215 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1216 << strgettext("Exit to OS") << "]"
1217 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1218 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1219 << g_build_info << "\n"
1220 << "path_user = " << wrap_rows(porting::path_user, 20)
1224 /* Note: FormspecFormSource and LocalFormspecHandler *
1225 * are deleted by guiFormSpecMenu */
1226 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1227 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1229 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1230 std::string con("btn_continue");
1231 (*cur_formspec)->setFocus(con);
1232 (*cur_formspec)->doPause = true;
1235 /******************************************************************************/
1236 static void updateChat(Client &client, f32 dtime, bool show_debug,
1237 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1238 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1240 // Add chat log output for errors to be shown in chat
1241 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
1243 // Get new messages from error log buffer
1244 while (!chat_log_error_buf.empty()) {
1245 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
1246 if (!g_settings->getBool("disable_escape_sequences")) {
1247 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
1249 chat_backend.addMessage(L"", error_message);
1252 // Get new messages from client
1253 std::wstring message;
1255 while (client.getChatMessage(message)) {
1256 chat_backend.addUnparsedMessage(message);
1259 // Remove old messages
1260 chat_backend.step(dtime);
1262 // Display all messages in a static text element
1263 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1264 EnrichedString recent_chat = chat_backend.getRecentChat();
1265 unsigned int line_height = g_fontengine->getLineHeight();
1267 setStaticText(guitext_chat, recent_chat);
1269 // Update gui element size and position
1270 s32 chat_y = 5 + line_height;
1273 chat_y += line_height;
1275 // first pass to calculate height of text to be set
1276 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
1277 porting::getWindowSize().X - 20);
1278 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1279 guitext_chat->setRelativePosition(rect);
1281 //now use real height of text and adjust rect according to this size
1282 rect = core::rect<s32>(10, chat_y, width,
1283 chat_y + guitext_chat->getTextHeight());
1286 guitext_chat->setRelativePosition(rect);
1287 // Don't show chat if disabled or empty or profiler is enabled
1288 guitext_chat->setVisible(
1289 show_chat && recent_chat_count != 0 && !show_profiler);
1293 /****************************************************************************
1294 Fast key cache for main game loop
1295 ****************************************************************************/
1297 /* This is faster than using getKeySetting with the tradeoff that functions
1298 * using it must make sure that it's initialised before using it and there is
1299 * no error handling (for example bounds checking). This is really intended for
1300 * use only in the main running loop of the client (the_game()) where the faster
1301 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1302 * (e.g. formspecs) should continue using getKeySetting().
1310 populate_nonchanging();
1315 // Keys that are not settings dependent
1316 void populate_nonchanging();
1318 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1319 InputHandler *handler;
1322 void KeyCache::populate_nonchanging()
1324 key[KeyType::ESC] = EscapeKey;
1327 void KeyCache::populate()
1329 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1330 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1331 key[KeyType::LEFT] = getKeySetting("keymap_left");
1332 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1333 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1334 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1335 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1337 key[KeyType::AUTORUN] = getKeySetting("keymap_autorun");
1339 key[KeyType::DROP] = getKeySetting("keymap_drop");
1340 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1341 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1342 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1343 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1344 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1345 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1346 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1347 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1348 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1349 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1350 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1351 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1352 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1353 = getKeySetting("keymap_toggle_force_fog_off");
1354 key[KeyType::TOGGLE_UPDATE_CAMERA]
1355 = getKeySetting("keymap_toggle_update_camera");
1356 key[KeyType::TOGGLE_DEBUG]
1357 = getKeySetting("keymap_toggle_debug");
1358 key[KeyType::TOGGLE_PROFILER]
1359 = getKeySetting("keymap_toggle_profiler");
1360 key[KeyType::CAMERA_MODE]
1361 = getKeySetting("keymap_camera_mode");
1362 key[KeyType::INCREASE_VIEWING_RANGE]
1363 = getKeySetting("keymap_increase_viewing_range_min");
1364 key[KeyType::DECREASE_VIEWING_RANGE]
1365 = getKeySetting("keymap_decrease_viewing_range_min");
1366 key[KeyType::RANGESELECT]
1367 = getKeySetting("keymap_rangeselect");
1369 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1370 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1371 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1372 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1374 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1377 // First clear all keys, then re-add the ones we listen for
1378 handler->dontListenForKeys();
1379 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1380 handler->listenForKey(key[i]);
1382 handler->listenForKey(EscapeKey);
1383 handler->listenForKey(CancelKey);
1384 for (size_t i = 0; i < 10; i++) {
1385 handler->listenForKey(NumberKey[i]);
1391 /****************************************************************************
1393 ****************************************************************************/
1395 const float object_hit_delay = 0.2;
1398 u32 last_time, busy_time, sleep_time;
1402 /* The reason the following structs are not anonymous structs within the
1403 * class is that they are not used by the majority of member functions and
1404 * many functions that do require objects of thse types do not modify them
1405 * (so they can be passed as a const qualified parameter)
1407 struct CameraOrientation {
1408 f32 camera_yaw; // "right/left"
1409 f32 camera_pitch; // "up/down"
1412 struct GameRunData {
1415 PointedThing pointed_old;
1419 bool update_wielded_item_trigger;
1420 bool reset_jump_timer;
1421 float nodig_delay_timer;
1423 float dig_time_complete;
1424 float repeat_rightclick_timer;
1425 float object_hit_delay_timer;
1426 float time_from_last_punch;
1427 ClientActiveObject *selected_object;
1431 float update_draw_list_timer;
1432 float statustext_time;
1436 v3f update_draw_list_last_cam_dir;
1438 u32 profiler_current_page;
1439 u32 profiler_max_page; // Number of pages
1442 float time_of_day_smooth;
1446 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1454 Jitter dtime_jitter, busy_time_jitter;
1457 /* Flags that can, or may, change during main game loop
1459 struct VolatileRunFlags {
1466 bool show_profiler_graph;
1467 bool disable_camera_update;
1468 bool first_loop_after_window_activation;
1469 bool camera_offset_changed;
1473 /****************************************************************************
1475 ****************************************************************************/
1477 /* This is not intended to be a public class. If a public class becomes
1478 * desirable then it may be better to create another 'wrapper' class that
1479 * hides most of the stuff in this class (nothing in this class is required
1480 * by any other file) but exposes the public methods/data only.
1487 bool startup(bool *kill,
1489 InputHandler *input,
1490 IrrlichtDevice *device,
1491 const std::string &map_dir,
1492 const std::string &playername,
1493 const std::string &password,
1494 // If address is "", local server is used and address is updated
1495 std::string *address,
1497 std::string &error_message,
1499 ChatBackend *chat_backend,
1500 const SubgameSpec &gamespec, // Used for local game
1501 bool simple_singleplayer_mode);
1508 void extendedResourceCleanup();
1510 // Basic initialisation
1511 bool init(const std::string &map_dir, std::string *address,
1513 const SubgameSpec &gamespec);
1515 bool createSingleplayerServer(const std::string map_dir,
1516 const SubgameSpec &gamespec, u16 port, std::string *address);
1519 bool createClient(const std::string &playername,
1520 const std::string &password, std::string *address, u16 port);
1523 // Client connection
1524 bool connectToServer(const std::string &playername,
1525 const std::string &password, std::string *address, u16 port,
1526 bool *connect_ok, bool *aborted);
1527 bool getServerContent(bool *aborted);
1531 void updateInteractTimers(GameRunData *runData, f32 dtime);
1532 bool checkConnection();
1533 bool handleCallbacks();
1534 void processQueues();
1535 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1536 const FpsControl &draw_times, f32 dtime);
1537 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1539 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1542 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1544 void processKeyInput(VolatileRunFlags *flags,
1545 float *statustext_time,
1547 bool *reset_jump_timer,
1548 u32 *profiler_current_page,
1549 u32 profiler_max_page);
1550 void processItemSelection(u16 *new_playeritem);
1552 void dropSelectedItem();
1553 void openInventory();
1554 void openConsole(float height, const wchar_t *line=NULL);
1555 void toggleFreeMove(float *statustext_time);
1556 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1557 void toggleFast(float *statustext_time);
1558 void toggleNoClip(float *statustext_time);
1559 void toggleCinematic(float *statustext_time);
1560 void toggleAutorun(float *statustext_time);
1562 void toggleChat(float *statustext_time, bool *flag);
1563 void toggleHud(float *statustext_time, bool *flag);
1564 void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
1565 bool shift_pressed);
1566 void toggleFog(float *statustext_time, bool *flag);
1567 void toggleDebug(float *statustext_time, bool *show_debug,
1568 bool *show_profiler_graph);
1569 void toggleUpdateCamera(float *statustext_time, bool *flag);
1570 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1571 u32 profiler_max_page);
1573 void increaseViewRange(float *statustext_time);
1574 void decreaseViewRange(float *statustext_time);
1575 void toggleFullViewRange(float *statustext_time);
1577 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1578 void updateCameraOrientation(CameraOrientation *cam,
1579 const VolatileRunFlags &flags);
1580 void updatePlayerControl(const CameraOrientation &cam);
1581 void step(f32 *dtime);
1582 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1583 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1584 float time_from_last_punch);
1585 void updateSound(f32 dtime);
1586 void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud,
1588 void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
1589 void handlePointingAtNode(GameRunData *runData,
1590 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1591 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1592 void handlePointingAtObject(GameRunData *runData,
1593 const PointedThing &pointed, const ItemStack &playeritem,
1594 const v3f &player_position, bool show_debug);
1595 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1596 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1598 void updateFrame(ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
1599 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1600 void updateGui(float *statustext_time, const RunStats &stats,
1601 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1602 const CameraOrientation &cam);
1603 void updateProfilerGraphs(ProfilerGraph *graph);
1606 void limitFps(FpsControl *fps_timings, f32 *dtime);
1608 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1609 bool draw_clouds = true);
1611 static void settingChangedCallback(const std::string &setting_name, void *data);
1612 void readSettings();
1614 bool getLeftClicked()
1616 return input->getLeftClicked();
1618 bool getRightClicked()
1620 return input->getRightClicked();
1622 bool isLeftPressed()
1624 return input->getLeftState();
1626 bool isRightPressed()
1628 return input->getRightState();
1630 bool getLeftReleased()
1632 return input->getLeftReleased();
1635 bool isKeyDown(GameKeyType k)
1637 return input->isKeyDown(keycache.key[k]);
1639 bool wasKeyDown(GameKeyType k)
1641 return input->wasKeyDown(keycache.key[k]);
1645 void handleAndroidChatInput();
1649 InputHandler *input;
1654 IWritableTextureSource *texture_src;
1655 IWritableShaderSource *shader_src;
1657 // When created, these will be filled with data received from the server
1658 IWritableItemDefManager *itemdef_manager;
1659 IWritableNodeDefManager *nodedef_manager;
1661 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1662 ISoundManager *sound;
1663 bool sound_is_dummy;
1664 SoundMaker *soundmaker;
1666 ChatBackend *chat_backend;
1668 GUIFormSpecMenu *current_formspec;
1670 EventManager *eventmgr;
1671 QuicktuneShortcutter *quicktune;
1673 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1674 MapDrawControl *draw_control;
1676 Clouds *clouds; // Free using ->Drop()
1677 Sky *sky; // Free using ->Drop()
1678 Inventory *local_inventory;
1683 This class does take ownership/responsibily for cleaning up etc of any of
1684 these items (e.g. device)
1686 IrrlichtDevice *device;
1687 video::IVideoDriver *driver;
1688 scene::ISceneManager *smgr;
1690 std::string *error_message;
1691 bool *reconnect_requested;
1692 IGameDef *gamedef; // Convenience (same as *client)
1693 scene::ISceneNode *skybox;
1696 bool simple_singleplayer_mode;
1699 /* Pre-calculated values
1701 int crack_animation_length;
1705 gui::IGUIStaticText *guitext; // First line of debug text
1706 gui::IGUIStaticText *guitext2; // Second line of debug text
1707 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1708 gui::IGUIStaticText *guitext_status;
1709 gui::IGUIStaticText *guitext_chat; // Chat text
1710 gui::IGUIStaticText *guitext_profiler; // Profiler text
1712 std::wstring infotext;
1713 std::wstring statustext;
1717 IntervalLimiter profiler_interval;
1720 * TODO: Local caching of settings is not optimal and should at some stage
1721 * be updated to use a global settings object for getting thse values
1722 * (as opposed to the this local caching). This can be addressed in
1725 bool m_cache_doubletap_jump;
1726 bool m_cache_enable_clouds;
1727 bool m_cache_enable_particles;
1728 bool m_cache_enable_fog;
1729 f32 m_cache_mouse_sensitivity;
1730 f32 m_repeat_right_click_time;
1733 bool m_cache_hold_aux1;
1734 bool m_android_chat_open;
1743 itemdef_manager(NULL),
1744 nodedef_manager(NULL),
1746 sound_is_dummy(false),
1749 current_formspec(NULL),
1752 gui_chat_console(NULL),
1757 local_inventory(NULL),
1761 g_settings->registerChangedCallback("doubletap_jump",
1762 &settingChangedCallback, this);
1763 g_settings->registerChangedCallback("enable_clouds",
1764 &settingChangedCallback, this);
1765 g_settings->registerChangedCallback("enable_particles",
1766 &settingChangedCallback, this);
1767 g_settings->registerChangedCallback("enable_fog",
1768 &settingChangedCallback, this);
1769 g_settings->registerChangedCallback("mouse_sensitivity",
1770 &settingChangedCallback, this);
1771 g_settings->registerChangedCallback("repeat_rightclick_time",
1772 &settingChangedCallback, this);
1777 m_cache_hold_aux1 = false; // This is initialised properly later
1784 /****************************************************************************
1786 ****************************************************************************/
1792 if (!sound_is_dummy)
1795 delete server; // deleted first to stop all server threads
1798 delete local_inventory;
1804 delete nodedef_manager;
1805 delete itemdef_manager;
1806 delete draw_control;
1808 extendedResourceCleanup();
1810 g_settings->deregisterChangedCallback("doubletap_jump",
1811 &settingChangedCallback, this);
1812 g_settings->deregisterChangedCallback("enable_clouds",
1813 &settingChangedCallback, this);
1814 g_settings->deregisterChangedCallback("enable_particles",
1815 &settingChangedCallback, this);
1816 g_settings->deregisterChangedCallback("enable_fog",
1817 &settingChangedCallback, this);
1818 g_settings->deregisterChangedCallback("mouse_sensitivity",
1819 &settingChangedCallback, this);
1820 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1821 &settingChangedCallback, this);
1824 bool Game::startup(bool *kill,
1826 InputHandler *input,
1827 IrrlichtDevice *device,
1828 const std::string &map_dir,
1829 const std::string &playername,
1830 const std::string &password,
1831 std::string *address, // can change if simple_singleplayer_mode
1833 std::string &error_message,
1835 ChatBackend *chat_backend,
1836 const SubgameSpec &gamespec,
1837 bool simple_singleplayer_mode)
1840 this->device = device;
1842 this->error_message = &error_message;
1843 this->reconnect_requested = reconnect;
1844 this->random_input = random_input;
1845 this->input = input;
1846 this->chat_backend = chat_backend;
1847 this->simple_singleplayer_mode = simple_singleplayer_mode;
1849 keycache.handler = input;
1850 keycache.populate();
1852 driver = device->getVideoDriver();
1853 smgr = device->getSceneManager();
1855 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1857 if (!init(map_dir, address, port, gamespec))
1860 if (!createClient(playername, password, address, port))
1869 ProfilerGraph graph;
1870 RunStats stats = { 0 };
1871 CameraOrientation cam_view_target = { 0 };
1872 CameraOrientation cam_view = { 0 };
1873 GameRunData runData = { 0 };
1874 FpsControl draw_times = { 0 };
1875 VolatileRunFlags flags = { 0 };
1876 f32 dtime; // in seconds
1878 runData.time_from_last_punch = 10.0;
1879 runData.profiler_max_page = 3;
1880 runData.update_wielded_item_trigger = true;
1882 flags.show_chat = true;
1883 flags.show_hud = true;
1884 flags.show_minimap = g_settings->getBool("enable_minimap");
1885 flags.show_debug = g_settings->getBool("show_debug");
1886 flags.invert_mouse = g_settings->getBool("invert_mouse");
1887 flags.first_loop_after_window_activation = true;
1889 /* Clear the profiler */
1890 Profiler::GraphValues dummyvalues;
1891 g_profiler->graphGet(dummyvalues);
1893 draw_times.last_time = device->getTimer()->getTime();
1895 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1897 &flags.force_fog_off,
1901 set_light_table(g_settings->getFloat("display_gamma"));
1904 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1905 && client->checkPrivilege("fast");
1908 while (device->run()
1909 && !(*kill || g_gamecallback->shutdown_requested
1910 || (server && server->getShutdownRequested()))) {
1912 /* Must be called immediately after a device->run() call because it
1913 * uses device->getTimer()->getTime()
1915 limitFps(&draw_times, &dtime);
1917 updateStats(&stats, draw_times, dtime);
1918 updateInteractTimers(&runData, dtime);
1920 if (!checkConnection())
1922 if (!handleCallbacks())
1928 hud->resizeHotbar();
1930 updateProfilers(runData, stats, draw_times, dtime);
1931 processUserInput(&flags, &runData, dtime);
1932 // Update camera before player movement to avoid camera lag of one frame
1933 updateCameraDirection(&cam_view_target, &flags);
1934 float cam_smoothing = 0;
1935 if (g_settings->getBool("cinematic"))
1936 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1938 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1939 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1940 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1941 cam_view.camera_yaw) * cam_smoothing;
1942 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1943 cam_view.camera_pitch) * cam_smoothing;
1944 updatePlayerControl(cam_view);
1946 processClientEvents(&cam_view_target, &runData.damage_flash);
1947 updateCamera(&flags, draw_times.busy_time, dtime,
1948 runData.time_from_last_punch);
1950 processPlayerInteraction(&runData, dtime, flags.show_hud,
1952 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
1953 updateProfilerGraphs(&graph);
1955 // Update if minimap has been disabled by the server
1956 flags.show_minimap &= !client->isMinimapDisabledByServer();
1961 void Game::shutdown()
1963 if (g_settings->get("3d_mode") == "pageflip") {
1964 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1967 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1972 if (gui_chat_console)
1973 gui_chat_console->drop();
1979 while (g_menumgr.menuCount() > 0) {
1980 g_menumgr.m_stack.front()->setVisible(false);
1981 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1984 if (current_formspec) {
1985 current_formspec->drop();
1986 current_formspec = NULL;
1989 chat_backend->addMessage(L"", L"# Disconnected.");
1990 chat_backend->addMessage(L"", L"");
1994 while (!client->isShutdown()) {
1995 assert(texture_src != NULL);
1996 assert(shader_src != NULL);
1997 texture_src->processQueue();
1998 shader_src->processQueue();
2005 /****************************************************************************/
2006 /****************************************************************************
2008 ****************************************************************************/
2009 /****************************************************************************/
2012 const std::string &map_dir,
2013 std::string *address,
2015 const SubgameSpec &gamespec)
2017 showOverlayMessage(wgettext("Loading..."), 0, 0);
2019 texture_src = createTextureSource(device);
2020 shader_src = createShaderSource(device);
2022 itemdef_manager = createItemDefManager();
2023 nodedef_manager = createNodeDefManager();
2025 eventmgr = new EventManager();
2026 quicktune = new QuicktuneShortcutter();
2028 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
2029 && eventmgr && quicktune))
2035 // Create a server if not connecting to an existing one
2036 if (*address == "") {
2037 if (!createSingleplayerServer(map_dir, gamespec, port, address))
2044 bool Game::initSound()
2047 if (g_settings->getBool("enable_sound")) {
2048 infostream << "Attempting to use OpenAL audio" << std::endl;
2049 sound = createOpenALSoundManager(&soundfetcher);
2051 infostream << "Failed to initialize OpenAL audio" << std::endl;
2053 infostream << "Sound disabled." << std::endl;
2057 infostream << "Using dummy audio." << std::endl;
2058 sound = &dummySoundManager;
2059 sound_is_dummy = true;
2062 soundmaker = new SoundMaker(sound, nodedef_manager);
2066 soundmaker->registerReceiver(eventmgr);
2071 bool Game::createSingleplayerServer(const std::string map_dir,
2072 const SubgameSpec &gamespec, u16 port, std::string *address)
2074 showOverlayMessage(wgettext("Creating server..."), 0, 5);
2076 std::string bind_str = g_settings->get("bind_address");
2077 Address bind_addr(0, 0, 0, 0, port);
2079 if (g_settings->getBool("ipv6_server")) {
2080 bind_addr.setAddress((IPv6AddressBytes *) NULL);
2084 bind_addr.Resolve(bind_str.c_str());
2085 } catch (ResolveError &e) {
2086 infostream << "Resolving bind address \"" << bind_str
2087 << "\" failed: " << e.what()
2088 << " -- Listening on all addresses." << std::endl;
2091 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2092 *error_message = "Unable to listen on " +
2093 bind_addr.serializeString() +
2094 " because IPv6 is disabled";
2095 errorstream << *error_message << std::endl;
2099 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
2100 bind_addr.isIPv6());
2102 server->start(bind_addr);
2107 bool Game::createClient(const std::string &playername,
2108 const std::string &password, std::string *address, u16 port)
2110 showOverlayMessage(wgettext("Creating client..."), 0, 10);
2112 draw_control = new MapDrawControl;
2116 bool could_connect, connect_aborted;
2118 if (!connectToServer(playername, password, address, port,
2119 &could_connect, &connect_aborted))
2122 if (!could_connect) {
2123 if (error_message->empty() && !connect_aborted) {
2124 // Should not happen if error messages are set properly
2125 *error_message = "Connection failed for unknown reason";
2126 errorstream << *error_message << std::endl;
2131 if (!getServerContent(&connect_aborted)) {
2132 if (error_message->empty() && !connect_aborted) {
2133 // Should not happen if error messages are set properly
2134 *error_message = "Connection failed for unknown reason";
2135 errorstream << *error_message << std::endl;
2140 // Update cached textures, meshes and materials
2141 client->afterContentReceived(device);
2145 camera = new Camera(smgr, *draw_control, gamedef);
2146 if (!camera || !camera->successfullyCreated(*error_message))
2148 client->setCamera(camera);
2152 if (m_cache_enable_clouds) {
2153 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2155 *error_message = "Memory allocation error (clouds)";
2156 errorstream << *error_message << std::endl;
2163 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2164 skybox = NULL; // This is used/set later on in the main run loop
2166 local_inventory = new Inventory(itemdef_manager);
2168 if (!(sky && local_inventory)) {
2169 *error_message = "Memory allocation error (sky or local inventory)";
2170 errorstream << *error_message << std::endl;
2174 /* Pre-calculated values
2176 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2178 v2u32 size = t->getOriginalSize();
2179 crack_animation_length = size.Y / size.X;
2181 crack_animation_length = 5;
2187 /* Set window caption
2189 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2191 str += driver->getName();
2193 device->setWindowCaption(str.c_str());
2195 LocalPlayer *player = client->getEnv().getLocalPlayer();
2196 player->hurt_tilt_timer = 0;
2197 player->hurt_tilt_strength = 0;
2199 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2202 *error_message = "Memory error: could not create HUD";
2203 errorstream << *error_message << std::endl;
2207 mapper = client->getMapper();
2208 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2213 bool Game::initGui()
2215 // First line of debug text
2216 guitext = addStaticText(guienv,
2217 utf8_to_wide(PROJECT_NAME_C).c_str(),
2218 core::rect<s32>(0, 0, 0, 0),
2219 false, false, guiroot);
2221 // Second line of debug text
2222 guitext2 = addStaticText(guienv,
2224 core::rect<s32>(0, 0, 0, 0),
2225 false, false, guiroot);
2227 // At the middle of the screen
2228 // Object infos are shown in this
2229 guitext_info = addStaticText(guienv,
2231 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2232 false, true, guiroot);
2234 // Status text (displays info when showing and hiding GUI stuff, etc.)
2235 guitext_status = addStaticText(guienv,
2237 core::rect<s32>(0, 0, 0, 0),
2238 false, false, guiroot);
2239 guitext_status->setVisible(false);
2242 guitext_chat = addStaticText(
2245 core::rect<s32>(0, 0, 0, 0),
2246 //false, false); // Disable word wrap as of now
2247 false, true, guiroot);
2249 // Remove stale "recent" chat messages from previous connections
2250 chat_backend->clearRecentChat();
2252 // Chat backend and console
2253 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2254 -1, chat_backend, client, &g_menumgr);
2255 if (!gui_chat_console) {
2256 *error_message = "Could not allocate memory for chat console";
2257 errorstream << *error_message << std::endl;
2261 // Profiler text (size is updated when text is updated)
2262 guitext_profiler = addStaticText(guienv,
2264 core::rect<s32>(0, 0, 0, 0),
2265 false, false, guiroot);
2266 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2267 guitext_profiler->setVisible(false);
2268 guitext_profiler->setWordWrap(true);
2270 #ifdef HAVE_TOUCHSCREENGUI
2272 if (g_touchscreengui)
2273 g_touchscreengui->init(texture_src);
2280 bool Game::connectToServer(const std::string &playername,
2281 const std::string &password, std::string *address, u16 port,
2282 bool *connect_ok, bool *aborted)
2284 *connect_ok = false; // Let's not be overly optimistic
2286 bool local_server_mode = false;
2288 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2290 Address connect_address(0, 0, 0, 0, port);
2293 connect_address.Resolve(address->c_str());
2295 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2296 //connect_address.Resolve("localhost");
2297 if (connect_address.isIPv6()) {
2298 IPv6AddressBytes addr_bytes;
2299 addr_bytes.bytes[15] = 1;
2300 connect_address.setAddress(&addr_bytes);
2302 connect_address.setAddress(127, 0, 0, 1);
2304 local_server_mode = true;
2306 } catch (ResolveError &e) {
2307 *error_message = std::string("Couldn't resolve address: ") + e.what();
2308 errorstream << *error_message << std::endl;
2312 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2313 *error_message = "Unable to connect to " +
2314 connect_address.serializeString() +
2315 " because IPv6 is disabled";
2316 errorstream << *error_message << std::endl;
2320 client = new Client(device,
2321 playername.c_str(), password,
2322 *draw_control, texture_src, shader_src,
2323 itemdef_manager, nodedef_manager, sound, eventmgr,
2324 connect_address.isIPv6());
2329 gamedef = client; // Client acts as our GameDef
2331 infostream << "Connecting to server at ";
2332 connect_address.print(&infostream);
2333 infostream << std::endl;
2335 client->connect(connect_address, *address,
2336 simple_singleplayer_mode || local_server_mode);
2339 Wait for server to accept connection
2345 FpsControl fps_control = { 0 };
2347 f32 wait_time = 0; // in seconds
2349 fps_control.last_time = device->getTimer()->getTime();
2351 while (device->run()) {
2353 limitFps(&fps_control, &dtime);
2355 // Update client and server
2356 client->step(dtime);
2359 server->step(dtime);
2362 if (client->getState() == LC_Init) {
2368 if (client->accessDenied()) {
2369 *error_message = "Access denied. Reason: "
2370 + client->accessDeniedReason();
2371 *reconnect_requested = client->reconnectRequested();
2372 errorstream << *error_message << std::endl;
2376 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2378 infostream << "Connect aborted [Escape]" << std::endl;
2383 // Only time out if we aren't waiting for the server we started
2384 if ((*address != "") && (wait_time > 10)) {
2385 *error_message = "Connection timed out.";
2386 errorstream << *error_message << std::endl;
2391 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2393 } catch (con::PeerNotFoundException &e) {
2394 // TODO: Should something be done here? At least an info/error
2402 bool Game::getServerContent(bool *aborted)
2406 FpsControl fps_control = { 0 };
2407 f32 dtime; // in seconds
2409 fps_control.last_time = device->getTimer()->getTime();
2411 while (device->run()) {
2413 limitFps(&fps_control, &dtime);
2415 // Update client and server
2416 client->step(dtime);
2419 server->step(dtime);
2422 if (client->mediaReceived() && client->itemdefReceived() &&
2423 client->nodedefReceived()) {
2428 if (!checkConnection())
2431 if (client->getState() < LC_Init) {
2432 *error_message = "Client disconnected";
2433 errorstream << *error_message << std::endl;
2437 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2439 infostream << "Connect aborted [Escape]" << std::endl;
2446 if (!client->itemdefReceived()) {
2447 const wchar_t *text = wgettext("Item definitions...");
2449 draw_load_screen(text, device, guienv, dtime, progress);
2451 } else if (!client->nodedefReceived()) {
2452 const wchar_t *text = wgettext("Node definitions...");
2454 draw_load_screen(text, device, guienv, dtime, progress);
2457 std::stringstream message;
2458 message.precision(3);
2459 message << gettext("Media...");
2461 if ((USE_CURL == 0) ||
2462 (!g_settings->getBool("enable_remote_media_server"))) {
2463 float cur = client->getCurRate();
2464 std::string cur_unit = gettext("KiB/s");
2468 cur_unit = gettext("MiB/s");
2471 message << " (" << cur << ' ' << cur_unit << ")";
2474 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2475 draw_load_screen(utf8_to_wide(message.str()), device,
2476 guienv, dtime, progress);
2484 /****************************************************************************/
2485 /****************************************************************************
2487 ****************************************************************************/
2488 /****************************************************************************/
2490 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2492 if (runData->nodig_delay_timer >= 0)
2493 runData->nodig_delay_timer -= dtime;
2495 if (runData->object_hit_delay_timer >= 0)
2496 runData->object_hit_delay_timer -= dtime;
2498 runData->time_from_last_punch += dtime;
2502 /* returns false if game should exit, otherwise true
2504 inline bool Game::checkConnection()
2506 if (client->accessDenied()) {
2507 *error_message = "Access denied. Reason: "
2508 + client->accessDeniedReason();
2509 *reconnect_requested = client->reconnectRequested();
2510 errorstream << *error_message << std::endl;
2518 /* returns false if game should exit, otherwise true
2520 inline bool Game::handleCallbacks()
2522 if (g_gamecallback->disconnect_requested) {
2523 g_gamecallback->disconnect_requested = false;
2527 if (g_gamecallback->changepassword_requested) {
2528 (new GUIPasswordChange(guienv, guiroot, -1,
2529 &g_menumgr, client))->drop();
2530 g_gamecallback->changepassword_requested = false;
2533 if (g_gamecallback->changevolume_requested) {
2534 (new GUIVolumeChange(guienv, guiroot, -1,
2535 &g_menumgr, client))->drop();
2536 g_gamecallback->changevolume_requested = false;
2539 if (g_gamecallback->keyconfig_requested) {
2540 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2541 &g_menumgr))->drop();
2542 g_gamecallback->keyconfig_requested = false;
2545 if (g_gamecallback->keyconfig_changed) {
2546 keycache.populate(); // update the cache with new settings
2547 g_gamecallback->keyconfig_changed = false;
2554 void Game::processQueues()
2556 texture_src->processQueue();
2557 itemdef_manager->processQueue(gamedef);
2558 shader_src->processQueue();
2562 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2563 const FpsControl &draw_times, f32 dtime)
2565 float profiler_print_interval =
2566 g_settings->getFloat("profiler_print_interval");
2567 bool print_to_log = true;
2569 if (profiler_print_interval == 0) {
2570 print_to_log = false;
2571 profiler_print_interval = 5;
2574 if (profiler_interval.step(dtime, profiler_print_interval)) {
2576 infostream << "Profiler:" << std::endl;
2577 g_profiler->print(infostream);
2580 update_profiler_gui(guitext_profiler, g_fontengine,
2581 runData.profiler_current_page, runData.profiler_max_page,
2582 driver->getScreenSize().Height);
2584 g_profiler->clear();
2587 addProfilerGraphs(stats, draw_times, dtime);
2591 void Game::addProfilerGraphs(const RunStats &stats,
2592 const FpsControl &draw_times, f32 dtime)
2594 g_profiler->graphAdd("mainloop_other",
2595 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2597 if (draw_times.sleep_time != 0)
2598 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2599 g_profiler->graphAdd("mainloop_dtime", dtime);
2601 g_profiler->add("Elapsed time", dtime);
2602 g_profiler->avg("FPS", 1. / dtime);
2606 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2613 /* Time average and jitter calculation
2615 jp = &stats->dtime_jitter;
2616 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2618 jitter = dtime - jp->avg;
2620 if (jitter > jp->max)
2623 jp->counter += dtime;
2625 if (jp->counter > 0.0) {
2627 jp->max_sample = jp->max;
2628 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2632 /* Busytime average and jitter calculation
2634 jp = &stats->busy_time_jitter;
2635 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2637 jitter = draw_times.busy_time - jp->avg;
2639 if (jitter > jp->max)
2641 if (jitter < jp->min)
2644 jp->counter += dtime;
2646 if (jp->counter > 0.0) {
2648 jp->max_sample = jp->max;
2649 jp->min_sample = jp->min;
2657 /****************************************************************************
2659 ****************************************************************************/
2661 void Game::processUserInput(VolatileRunFlags *flags,
2662 GameRunData *runData, f32 dtime)
2664 // Reset input if window not active or some menu is active
2665 if (device->isWindowActive() == false
2666 || noMenuActive() == false
2667 || guienv->hasFocus(gui_chat_console)) {
2669 #ifdef HAVE_TOUCHSCREENGUI
2670 g_touchscreengui->hide();
2673 #ifdef HAVE_TOUCHSCREENGUI
2674 else if (g_touchscreengui) {
2675 /* on touchscreengui step may generate own input events which ain't
2676 * what we want in case we just did clear them */
2677 g_touchscreengui->step(dtime);
2681 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2682 gui_chat_console->closeConsoleAtOnce();
2685 // Input handler step() (used by the random input generator)
2689 if (current_formspec != NULL)
2690 current_formspec->getAndroidUIInput();
2692 handleAndroidChatInput();
2695 // Increase timer for double tap of "keymap_jump"
2696 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2697 runData->jump_timer += dtime;
2701 &runData->statustext_time,
2702 &runData->jump_timer,
2703 &runData->reset_jump_timer,
2704 &runData->profiler_current_page,
2705 runData->profiler_max_page);
2707 processItemSelection(&runData->new_playeritem);
2711 void Game::processKeyInput(VolatileRunFlags *flags,
2712 float *statustext_time,
2714 bool *reset_jump_timer,
2715 u32 *profiler_current_page,
2716 u32 profiler_max_page)
2719 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2721 if (wasKeyDown(KeyType::DROP)) {
2723 } else if (wasKeyDown(KeyType::AUTORUN)) {
2724 toggleAutorun(statustext_time);
2725 } else if (wasKeyDown(KeyType::INVENTORY)) {
2727 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2728 if (!gui_chat_console->isOpenInhibited()) {
2729 show_pause_menu(¤t_formspec, client, gamedef,
2730 texture_src, device, simple_singleplayer_mode);
2732 } else if (wasKeyDown(KeyType::CHAT)) {
2733 openConsole(0.2, L"");
2734 } else if (wasKeyDown(KeyType::CMD)) {
2735 openConsole(0.2, L"/");
2736 } else if (wasKeyDown(KeyType::CONSOLE)) {
2738 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2739 toggleFreeMove(statustext_time);
2740 } else if (wasKeyDown(KeyType::JUMP)) {
2741 toggleFreeMoveAlt(statustext_time, jump_timer);
2742 *reset_jump_timer = true;
2743 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2744 toggleFast(statustext_time);
2745 } else if (wasKeyDown(KeyType::NOCLIP)) {
2746 toggleNoClip(statustext_time);
2747 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2748 toggleCinematic(statustext_time);
2749 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2750 client->makeScreenshot(device);
2751 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2752 toggleHud(statustext_time, &flags->show_hud);
2753 } else if (wasKeyDown(KeyType::MINIMAP)) {
2754 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2755 isKeyDown(KeyType::SNEAK));
2756 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2757 toggleChat(statustext_time, &flags->show_chat);
2758 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2759 toggleFog(statustext_time, &flags->force_fog_off);
2760 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2761 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2762 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2763 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2764 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2765 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2766 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2767 increaseViewRange(statustext_time);
2768 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2769 decreaseViewRange(statustext_time);
2770 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2771 toggleFullViewRange(statustext_time);
2772 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2774 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2776 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2778 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2780 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2781 // Print debug stacks
2782 dstream << "-----------------------------------------"
2784 dstream << "Printing debug stacks:" << std::endl;
2785 dstream << "-----------------------------------------"
2787 debug_stacks_print();
2790 if (!isKeyDown(KeyType::JUMP) && *reset_jump_timer) {
2791 *reset_jump_timer = false;
2797 if (quicktune->hasMessage()) {
2798 std::string msg = quicktune->getMessage();
2799 statustext = utf8_to_wide(msg);
2800 *statustext_time = 0;
2804 void Game::processItemSelection(u16 *new_playeritem)
2806 LocalPlayer *player = client->getEnv().getLocalPlayer();
2808 /* Item selection using mouse wheel
2810 *new_playeritem = client->getPlayerItem();
2812 s32 wheel = input->getMouseWheel();
2813 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2814 player->hud_hotbar_itemcount - 1);
2817 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2819 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2823 /* Item selection using keyboard
2825 for (u16 i = 0; i < 10; i++) {
2826 static const KeyPress *item_keys[10] = {
2827 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2828 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2829 NumberKey + 9, NumberKey + 0,
2832 if (input->wasKeyDown(*item_keys[i])) {
2833 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2834 *new_playeritem = i;
2835 infostream << "Selected item: " << new_playeritem << std::endl;
2843 void Game::dropSelectedItem()
2845 IDropAction *a = new IDropAction();
2847 a->from_inv.setCurrentPlayer();
2848 a->from_list = "main";
2849 a->from_i = client->getPlayerItem();
2850 client->inventoryAction(a);
2854 void Game::openInventory()
2857 * Don't permit to open inventory is CAO or player doesn't exists.
2858 * This prevent showing an empty inventory at player load
2861 LocalPlayer *player = client->getEnv().getLocalPlayer();
2862 if (player == NULL || player->getCAO() == NULL)
2865 infostream << "the_game: " << "Launching inventory" << std::endl;
2867 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2868 TextDest *txt_dst = new TextDestPlayerInventory(client);
2870 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2871 device, fs_src, txt_dst, client);
2873 InventoryLocation inventoryloc;
2874 inventoryloc.setCurrentPlayer();
2875 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2879 void Game::openConsole(float height, const wchar_t *line)
2882 porting::showInputDialog(gettext("ok"), "", "", 2);
2883 m_android_chat_open = true;
2885 if (gui_chat_console->isOpenInhibited())
2887 gui_chat_console->openConsole(height);
2889 gui_chat_console->setCloseOnEnter(true);
2890 gui_chat_console->replaceAndAddToHistory(line);
2896 void Game::handleAndroidChatInput()
2898 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2899 std::string text = porting::getInputDialogValue();
2900 client->typeChatMessage(utf8_to_wide(text));
2906 void Game::toggleFreeMove(float *statustext_time)
2908 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2910 bool free_move = !g_settings->getBool("free_move");
2911 g_settings->set("free_move", bool_to_cstr(free_move));
2913 *statustext_time = 0;
2914 statustext = msg[free_move];
2915 if (free_move && !client->checkPrivilege("fly"))
2916 statustext += L" (note: no 'fly' privilege)";
2920 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2922 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2923 toggleFreeMove(statustext_time);
2927 void Game::toggleFast(float *statustext_time)
2929 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2930 bool fast_move = !g_settings->getBool("fast_move");
2931 g_settings->set("fast_move", bool_to_cstr(fast_move));
2933 *statustext_time = 0;
2934 statustext = msg[fast_move];
2936 bool has_fast_privs = client->checkPrivilege("fast");
2938 if (fast_move && !has_fast_privs)
2939 statustext += L" (note: no 'fast' privilege)";
2942 m_cache_hold_aux1 = fast_move && has_fast_privs;
2947 void Game::toggleNoClip(float *statustext_time)
2949 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2950 bool noclip = !g_settings->getBool("noclip");
2951 g_settings->set("noclip", bool_to_cstr(noclip));
2953 *statustext_time = 0;
2954 statustext = msg[noclip];
2956 if (noclip && !client->checkPrivilege("noclip"))
2957 statustext += L" (note: no 'noclip' privilege)";
2960 void Game::toggleCinematic(float *statustext_time)
2962 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2963 bool cinematic = !g_settings->getBool("cinematic");
2964 g_settings->set("cinematic", bool_to_cstr(cinematic));
2966 *statustext_time = 0;
2967 statustext = msg[cinematic];
2970 // Add WoW-style autorun by toggling continuous forward.
2971 void Game::toggleAutorun(float *statustext_time)
2973 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2974 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2975 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2977 *statustext_time = 0;
2978 statustext = msg[autorun_enabled ? 1 : 0];
2981 void Game::toggleChat(float *statustext_time, bool *flag)
2983 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2986 *statustext_time = 0;
2987 statustext = msg[*flag];
2991 void Game::toggleHud(float *statustext_time, bool *flag)
2993 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2996 *statustext_time = 0;
2997 statustext = msg[*flag];
3000 void Game::toggleMinimap(float *statustext_time, bool *flag,
3001 bool show_hud, bool shift_pressed)
3003 if (!show_hud || !g_settings->getBool("enable_minimap"))
3006 if (shift_pressed) {
3007 mapper->toggleMinimapShape();
3011 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
3013 MinimapMode mode = MINIMAP_MODE_OFF;
3014 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
3015 mode = mapper->getMinimapMode();
3016 mode = (MinimapMode)((int)mode + 1);
3021 case MINIMAP_MODE_SURFACEx1:
3022 statustext = L"Minimap in surface mode, Zoom x1";
3024 case MINIMAP_MODE_SURFACEx2:
3025 statustext = L"Minimap in surface mode, Zoom x2";
3027 case MINIMAP_MODE_SURFACEx4:
3028 statustext = L"Minimap in surface mode, Zoom x4";
3030 case MINIMAP_MODE_RADARx1:
3031 statustext = L"Minimap in radar mode, Zoom x1";
3033 case MINIMAP_MODE_RADARx2:
3034 statustext = L"Minimap in radar mode, Zoom x2";
3036 case MINIMAP_MODE_RADARx4:
3037 statustext = L"Minimap in radar mode, Zoom x4";
3040 mode = MINIMAP_MODE_OFF;
3042 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
3043 L"Minimap hidden" : L"Minimap disabled by server";
3046 *statustext_time = 0;
3047 mapper->setMinimapMode(mode);
3050 void Game::toggleFog(float *statustext_time, bool *flag)
3052 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
3055 *statustext_time = 0;
3056 statustext = msg[*flag];
3060 void Game::toggleDebug(float *statustext_time, bool *show_debug,
3061 bool *show_profiler_graph)
3063 // Initial / 3x toggle: Chat only
3064 // 1x toggle: Debug text with chat
3065 // 2x toggle: Debug text with profiler graph
3068 *show_profiler_graph = false;
3069 statustext = L"Debug info shown";
3070 } else if (*show_profiler_graph) {
3071 *show_debug = false;
3072 *show_profiler_graph = false;
3073 statustext = L"Debug info and profiler graph hidden";
3075 *show_profiler_graph = true;
3076 statustext = L"Profiler graph shown";
3078 *statustext_time = 0;
3082 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
3084 static const wchar_t *msg[] = {
3085 L"Camera update enabled",
3086 L"Camera update disabled"
3090 *statustext_time = 0;
3091 statustext = msg[*flag];
3095 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
3096 u32 profiler_max_page)
3098 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
3100 // FIXME: This updates the profiler with incomplete values
3101 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
3102 profiler_max_page, driver->getScreenSize().Height);
3104 if (*profiler_current_page != 0) {
3105 std::wstringstream sstr;
3106 sstr << "Profiler shown (page " << *profiler_current_page
3107 << " of " << profiler_max_page << ")";
3108 statustext = sstr.str();
3110 statustext = L"Profiler hidden";
3112 *statustext_time = 0;
3116 void Game::increaseViewRange(float *statustext_time)
3118 s16 range = g_settings->getS16("viewing_range");
3119 s16 range_new = range + 10;
3120 g_settings->set("viewing_range", itos(range_new));
3121 statustext = utf8_to_wide("Viewing range changed to "
3123 *statustext_time = 0;
3127 void Game::decreaseViewRange(float *statustext_time)
3129 s16 range = g_settings->getS16("viewing_range");
3130 s16 range_new = range - 10;
3135 g_settings->set("viewing_range", itos(range_new));
3136 statustext = utf8_to_wide("Viewing range changed to "
3138 *statustext_time = 0;
3142 void Game::toggleFullViewRange(float *statustext_time)
3144 static const wchar_t *msg[] = {
3145 L"Disabled full viewing range",
3146 L"Enabled full viewing range"
3149 draw_control->range_all = !draw_control->range_all;
3150 infostream << msg[draw_control->range_all] << std::endl;
3151 statustext = msg[draw_control->range_all];
3152 *statustext_time = 0;
3156 void Game::updateCameraDirection(CameraOrientation *cam,
3157 VolatileRunFlags *flags)
3159 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3162 if (!random_input) {
3163 // Mac OSX gets upset if this is set every frame
3164 if (device->getCursorControl()->isVisible())
3165 device->getCursorControl()->setVisible(false);
3169 if (flags->first_loop_after_window_activation)
3170 flags->first_loop_after_window_activation = false;
3172 updateCameraOrientation(cam, *flags);
3174 input->setMousePos((driver->getScreenSize().Width / 2),
3175 (driver->getScreenSize().Height / 2));
3179 // Mac OSX gets upset if this is set every frame
3180 if (device->getCursorControl()->isVisible() == false)
3181 device->getCursorControl()->setVisible(true);
3184 if (!flags->first_loop_after_window_activation)
3185 flags->first_loop_after_window_activation = true;
3191 void Game::updateCameraOrientation(CameraOrientation *cam,
3192 const VolatileRunFlags &flags)
3194 #ifdef HAVE_TOUCHSCREENGUI
3195 if (g_touchscreengui) {
3196 cam->camera_yaw = g_touchscreengui->getYaw();
3197 cam->camera_pitch = g_touchscreengui->getPitch();
3200 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3201 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3203 if (flags.invert_mouse
3204 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3208 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3209 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3211 #ifdef HAVE_TOUCHSCREENGUI
3215 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3219 void Game::updatePlayerControl(const CameraOrientation &cam)
3221 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3223 PlayerControl control(
3224 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3225 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3226 input->isKeyDown(keycache.key[KeyType::LEFT]),
3227 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3228 input->isKeyDown(keycache.key[KeyType::JUMP]),
3229 input->isKeyDown(keycache.key[KeyType::SPECIAL1]),
3230 input->isKeyDown(keycache.key[KeyType::SNEAK]),
3231 input->getLeftState(),
3232 input->getRightState(),
3238 ( (u32)(input->isKeyDown(keycache.key[KeyType::FORWARD]) & 0x1) << 0) |
3239 ( (u32)(input->isKeyDown(keycache.key[KeyType::BACKWARD]) & 0x1) << 1) |
3240 ( (u32)(input->isKeyDown(keycache.key[KeyType::LEFT]) & 0x1) << 2) |
3241 ( (u32)(input->isKeyDown(keycache.key[KeyType::RIGHT]) & 0x1) << 3) |
3242 ( (u32)(input->isKeyDown(keycache.key[KeyType::JUMP]) & 0x1) << 4) |
3243 ( (u32)(input->isKeyDown(keycache.key[KeyType::SPECIAL1]) & 0x1) << 5) |
3244 ( (u32)(input->isKeyDown(keycache.key[KeyType::SNEAK]) & 0x1) << 6) |
3245 ( (u32)(input->getLeftState() & 0x1) << 7) |
3246 ( (u32)(input->getRightState() & 0x1) << 8
3250 /* For Android, simulate holding down AUX1 (fast move) if the user has
3251 * the fast_move setting toggled on. If there is an aux1 key defined for
3252 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3255 if (m_cache_hold_aux1) {
3256 control.aux1 = control.aux1 ^ true;
3257 keypress_bits ^= ((u32)(1U << 5));
3261 client->setPlayerControl(control);
3262 LocalPlayer *player = client->getEnv().getLocalPlayer();
3263 player->keyPressed = keypress_bits;
3269 inline void Game::step(f32 *dtime)
3271 bool can_be_and_is_paused =
3272 (simple_singleplayer_mode && g_menumgr.pausesGame());
3274 if (can_be_and_is_paused) { // This is for a singleplayer server
3275 *dtime = 0; // No time passes
3277 if (server != NULL) {
3278 //TimeTaker timer("server->step(dtime)");
3279 server->step(*dtime);
3282 //TimeTaker timer("client.step(dtime)");
3283 client->step(*dtime);
3288 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3290 ClientEvent event = client->getClientEvent();
3292 LocalPlayer *player = client->getEnv().getLocalPlayer();
3294 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3296 if (event.type == CE_PLAYER_DAMAGE &&
3297 client->getHP() != 0) {
3298 //u16 damage = event.player_damage.amount;
3299 //infostream<<"Player damage: "<<damage<<std::endl;
3301 *damage_flash += 100.0;
3302 *damage_flash += 8.0 * event.player_damage.amount;
3304 player->hurt_tilt_timer = 1.5;
3305 player->hurt_tilt_strength = event.player_damage.amount / 4;
3306 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3308 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3309 gamedef->event()->put(e);
3310 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3311 cam->camera_yaw = event.player_force_move.yaw;
3312 cam->camera_pitch = event.player_force_move.pitch;
3313 } else if (event.type == CE_DEATHSCREEN) {
3314 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3317 chat_backend->addMessage(L"", L"You died.");
3319 /* Handle visualization */
3321 player->hurt_tilt_timer = 0;
3322 player->hurt_tilt_strength = 0;
3324 } else if (event.type == CE_SHOW_FORMSPEC) {
3325 FormspecFormSource *fs_src =
3326 new FormspecFormSource(*(event.show_formspec.formspec));
3327 TextDestPlayerInventory *txt_dst =
3328 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3330 create_formspec_menu(¤t_formspec, client, gamedef,
3331 texture_src, device, fs_src, txt_dst, client);
3333 delete(event.show_formspec.formspec);
3334 delete(event.show_formspec.formname);
3335 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3336 (event.type == CE_ADD_PARTICLESPAWNER) ||
3337 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3338 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3340 } else if (event.type == CE_HUDADD) {
3341 u32 id = event.hudadd.id;
3343 LocalPlayer *player = client->getEnv().getLocalPlayer();
3344 HudElement *e = player->getHud(id);
3347 delete event.hudadd.pos;
3348 delete event.hudadd.name;
3349 delete event.hudadd.scale;
3350 delete event.hudadd.text;
3351 delete event.hudadd.align;
3352 delete event.hudadd.offset;
3353 delete event.hudadd.world_pos;
3354 delete event.hudadd.size;
3359 e->type = (HudElementType)event.hudadd.type;
3360 e->pos = *event.hudadd.pos;
3361 e->name = *event.hudadd.name;
3362 e->scale = *event.hudadd.scale;
3363 e->text = *event.hudadd.text;
3364 e->number = event.hudadd.number;
3365 e->item = event.hudadd.item;
3366 e->dir = event.hudadd.dir;
3367 e->align = *event.hudadd.align;
3368 e->offset = *event.hudadd.offset;
3369 e->world_pos = *event.hudadd.world_pos;
3370 e->size = *event.hudadd.size;
3372 u32 new_id = player->addHud(e);
3373 //if this isn't true our huds aren't consistent
3374 sanity_check(new_id == id);
3376 delete event.hudadd.pos;
3377 delete event.hudadd.name;
3378 delete event.hudadd.scale;
3379 delete event.hudadd.text;
3380 delete event.hudadd.align;
3381 delete event.hudadd.offset;
3382 delete event.hudadd.world_pos;
3383 delete event.hudadd.size;
3384 } else if (event.type == CE_HUDRM) {
3385 HudElement *e = player->removeHud(event.hudrm.id);
3389 } else if (event.type == CE_HUDCHANGE) {
3390 u32 id = event.hudchange.id;
3391 HudElement *e = player->getHud(id);
3394 delete event.hudchange.v3fdata;
3395 delete event.hudchange.v2fdata;
3396 delete event.hudchange.sdata;
3397 delete event.hudchange.v2s32data;
3401 switch (event.hudchange.stat) {
3403 e->pos = *event.hudchange.v2fdata;
3407 e->name = *event.hudchange.sdata;
3410 case HUD_STAT_SCALE:
3411 e->scale = *event.hudchange.v2fdata;
3415 e->text = *event.hudchange.sdata;
3418 case HUD_STAT_NUMBER:
3419 e->number = event.hudchange.data;
3423 e->item = event.hudchange.data;
3427 e->dir = event.hudchange.data;
3430 case HUD_STAT_ALIGN:
3431 e->align = *event.hudchange.v2fdata;
3434 case HUD_STAT_OFFSET:
3435 e->offset = *event.hudchange.v2fdata;
3438 case HUD_STAT_WORLD_POS:
3439 e->world_pos = *event.hudchange.v3fdata;
3443 e->size = *event.hudchange.v2s32data;
3447 delete event.hudchange.v3fdata;
3448 delete event.hudchange.v2fdata;
3449 delete event.hudchange.sdata;
3450 delete event.hudchange.v2s32data;
3451 } else if (event.type == CE_SET_SKY) {
3452 sky->setVisible(false);
3459 // Handle according to type
3460 if (*event.set_sky.type == "regular") {
3461 sky->setVisible(true);
3462 } else if (*event.set_sky.type == "skybox" &&
3463 event.set_sky.params->size() == 6) {
3464 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3465 skybox = smgr->addSkyBoxSceneNode(
3466 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3467 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3468 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3469 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3470 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3471 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3473 // Handle everything else as plain color
3475 if (*event.set_sky.type != "plain")
3476 infostream << "Unknown sky type: "
3477 << (*event.set_sky.type) << std::endl;
3479 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3482 delete event.set_sky.bgcolor;
3483 delete event.set_sky.type;
3484 delete event.set_sky.params;
3485 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3486 bool enable = event.override_day_night_ratio.do_override;
3487 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3488 client->getEnv().setDayNightRatioOverride(enable, value);
3494 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3495 f32 dtime, float time_from_last_punch)
3497 LocalPlayer *player = client->getEnv().getLocalPlayer();
3500 For interaction purposes, get info about the held item
3502 - Is it a usable item?
3503 - Can it point to liquids?
3505 ItemStack playeritem;
3507 InventoryList *mlist = local_inventory->getList("main");
3509 if (mlist && client->getPlayerItem() < mlist->getSize())
3510 playeritem = mlist->getItem(client->getPlayerItem());
3513 ToolCapabilities playeritem_toolcap =
3514 playeritem.getToolCapabilities(itemdef_manager);
3516 v3s16 old_camera_offset = camera->getOffset();
3518 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3519 GenericCAO *playercao = player->getCAO();
3521 // If playercao not loaded, don't change camera
3522 if (playercao == NULL)
3525 camera->toggleCameraMode();
3527 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3528 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3531 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3532 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3534 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3535 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3537 camera->step(dtime);
3539 v3f camera_position = camera->getPosition();
3540 v3f camera_direction = camera->getDirection();
3541 f32 camera_fov = camera->getFovMax();
3542 v3s16 camera_offset = camera->getOffset();
3544 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3546 if (!flags->disable_camera_update) {
3547 client->getEnv().getClientMap().updateCamera(camera_position,
3548 camera_direction, camera_fov, camera_offset);
3550 if (flags->camera_offset_changed) {
3551 client->updateCameraOffset(camera_offset);
3552 client->getEnv().updateCameraOffset(camera_offset);
3555 clouds->updateCameraOffset(camera_offset);
3561 void Game::updateSound(f32 dtime)
3563 // Update sound listener
3564 v3s16 camera_offset = camera->getOffset();
3565 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3566 v3f(0, 0, 0), // velocity
3567 camera->getDirection(),
3568 camera->getCameraNode()->getUpVector());
3569 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3572 // Update sound maker
3573 soundmaker->step(dtime);
3575 LocalPlayer *player = client->getEnv().getLocalPlayer();
3577 ClientMap &map = client->getEnv().getClientMap();
3578 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3579 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3583 void Game::processPlayerInteraction(GameRunData *runData,
3584 f32 dtime, bool show_hud, bool show_debug)
3586 LocalPlayer *player = client->getEnv().getLocalPlayer();
3588 ItemStack playeritem;
3590 InventoryList *mlist = local_inventory->getList("main");
3592 if (mlist && client->getPlayerItem() < mlist->getSize())
3593 playeritem = mlist->getItem(client->getPlayerItem());
3596 const ItemDefinition &playeritem_def =
3597 playeritem.getDefinition(itemdef_manager);
3599 v3f player_position = player->getPosition();
3600 v3f camera_position = camera->getPosition();
3601 v3f camera_direction = camera->getDirection();
3602 v3s16 camera_offset = camera->getOffset();
3606 Calculate what block is the crosshair pointing to
3609 f32 d = playeritem_def.range; // max. distance
3610 f32 d_hand = itemdef_manager->get("").range;
3612 if (d < 0 && d_hand >= 0)
3617 core::line3d<f32> shootline;
3619 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3621 shootline = core::line3d<f32>(camera_position,
3622 camera_position + camera_direction * BS * (d + 1));
3625 // prevent player pointing anything in front-view
3626 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3627 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3630 #ifdef HAVE_TOUCHSCREENGUI
3632 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3633 shootline = g_touchscreengui->getShootline();
3634 shootline.start += intToFloat(camera_offset, BS);
3635 shootline.end += intToFloat(camera_offset, BS);
3640 PointedThing pointed = getPointedThing(
3642 client, hud, player_position, camera_direction,
3643 camera_position, shootline, d,
3644 playeritem_def.liquids_pointable,
3645 !runData->ldown_for_dig,
3648 runData->selected_object);
3650 if (pointed != runData->pointed_old) {
3651 infostream << "Pointing at " << pointed.dump() << std::endl;
3652 hud->updateSelectionMesh(camera_offset);
3657 - releasing left mouse button
3658 - pointing away from node
3660 if (runData->digging) {
3661 if (getLeftReleased()) {
3662 infostream << "Left button released"
3663 << " (stopped digging)" << std::endl;
3664 runData->digging = false;
3665 } else if (pointed != runData->pointed_old) {
3666 if (pointed.type == POINTEDTHING_NODE
3667 && runData->pointed_old.type == POINTEDTHING_NODE
3668 && pointed.node_undersurface
3669 == runData->pointed_old.node_undersurface) {
3670 // Still pointing to the same node, but a different face.
3673 infostream << "Pointing away from node"
3674 << " (stopped digging)" << std::endl;
3675 runData->digging = false;
3676 hud->updateSelectionMesh(camera_offset);
3680 if (!runData->digging) {
3681 client->interact(1, runData->pointed_old);
3682 client->setCrack(-1, v3s16(0, 0, 0));
3683 runData->dig_time = 0.0;
3687 if (!runData->digging && runData->ldown_for_dig && !isLeftPressed()) {
3688 runData->ldown_for_dig = false;
3691 runData->left_punch = false;
3693 soundmaker->m_player_leftpunch_sound.name = "";
3695 if (isRightPressed())
3696 runData->repeat_rightclick_timer += dtime;
3698 runData->repeat_rightclick_timer = 0;
3700 if (playeritem_def.usable && isLeftPressed()) {
3701 if (getLeftClicked())
3702 client->interact(4, pointed);
3703 } else if (pointed.type == POINTEDTHING_NODE) {
3704 ToolCapabilities playeritem_toolcap =
3705 playeritem.getToolCapabilities(itemdef_manager);
3706 handlePointingAtNode(runData, pointed, playeritem_def,
3707 playeritem_toolcap, dtime);
3708 } else if (pointed.type == POINTEDTHING_OBJECT) {
3709 handlePointingAtObject(runData, pointed, playeritem,
3710 player_position, show_debug);
3711 } else if (isLeftPressed()) {
3712 // When button is held down in air, show continuous animation
3713 runData->left_punch = true;
3714 } else if (getRightClicked()) {
3715 handlePointingAtNothing(runData, playeritem);
3718 runData->pointed_old = pointed;
3720 if (runData->left_punch || getLeftClicked())
3721 camera->setDigging(0); // left click animation
3723 input->resetLeftClicked();
3724 input->resetRightClicked();
3726 input->resetLeftReleased();
3727 input->resetRightReleased();
3731 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3733 infostream << "Right Clicked in Air" << std::endl;
3734 PointedThing fauxPointed;
3735 fauxPointed.type = POINTEDTHING_NOTHING;
3736 client->interact(5, fauxPointed);
3740 void Game::handlePointingAtNode(GameRunData *runData,
3741 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3742 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3744 v3s16 nodepos = pointed.node_undersurface;
3745 v3s16 neighbourpos = pointed.node_abovesurface;
3748 Check information text of node
3751 ClientMap &map = client->getEnv().getClientMap();
3752 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3755 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3757 MapNode n = map.getNodeNoEx(nodepos);
3759 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3760 infotext = L"Unknown node: ";
3761 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3765 if (runData->nodig_delay_timer <= 0.0 && isLeftPressed()
3766 && client->checkPrivilege("interact")) {
3767 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3770 if ((getRightClicked() ||
3771 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3772 client->checkPrivilege("interact")) {
3773 runData->repeat_rightclick_timer = 0;
3774 infostream << "Ground right-clicked" << std::endl;
3776 if (meta && meta->getString("formspec") != "" && !random_input
3777 && !isKeyDown(KeyType::SNEAK)) {
3778 infostream << "Launching custom inventory view" << std::endl;
3780 InventoryLocation inventoryloc;
3781 inventoryloc.setNodeMeta(nodepos);
3783 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3784 &client->getEnv().getClientMap(), nodepos);
3785 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3787 create_formspec_menu(¤t_formspec, client, gamedef,
3788 texture_src, device, fs_src, txt_dst, client);
3790 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3792 // Report right click to server
3794 camera->setDigging(1); // right click animation (always shown for feedback)
3796 // If the wielded item has node placement prediction,
3798 bool placed = nodePlacementPrediction(*client,
3800 nodepos, neighbourpos);
3804 client->interact(3, pointed);
3806 soundmaker->m_player_rightpunch_sound =
3807 playeritem_def.sound_place;
3809 soundmaker->m_player_rightpunch_sound =
3812 if (playeritem_def.node_placement_prediction == "" ||
3813 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3814 client->interact(3, pointed); // Report to server
3816 soundmaker->m_player_rightpunch_sound =
3817 playeritem_def.sound_place_failed;
3825 void Game::handlePointingAtObject(GameRunData *runData,
3826 const PointedThing &pointed,
3827 const ItemStack &playeritem,
3828 const v3f &player_position,
3831 infotext = unescape_enriched(
3832 utf8_to_wide(runData->selected_object->infoText()));
3835 if (infotext != L"") {
3838 infotext += unescape_enriched(utf8_to_wide(
3839 runData->selected_object->debugInfoText()));
3842 if (isLeftPressed()) {
3843 bool do_punch = false;
3844 bool do_punch_damage = false;
3846 if (runData->object_hit_delay_timer <= 0.0) {
3848 do_punch_damage = true;
3849 runData->object_hit_delay_timer = object_hit_delay;
3852 if (getLeftClicked())
3856 infostream << "Left-clicked object" << std::endl;
3857 runData->left_punch = true;
3860 if (do_punch_damage) {
3861 // Report direct punch
3862 v3f objpos = runData->selected_object->getPosition();
3863 v3f dir = (objpos - player_position).normalize();
3865 bool disable_send = runData->selected_object->directReportPunch(
3866 dir, &playeritem, runData->time_from_last_punch);
3867 runData->time_from_last_punch = 0;
3870 client->interact(0, pointed);
3872 } else if (getRightClicked()) {
3873 infostream << "Right-clicked object" << std::endl;
3874 client->interact(3, pointed); // place
3879 void Game::handleDigging(GameRunData *runData,
3880 const PointedThing &pointed, const v3s16 &nodepos,
3881 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3883 if (!runData->digging) {
3884 infostream << "Started digging" << std::endl;
3885 client->interact(0, pointed);
3886 runData->digging = true;
3887 runData->ldown_for_dig = true;
3890 LocalPlayer *player = client->getEnv().getLocalPlayer();
3891 ClientMap &map = client->getEnv().getClientMap();
3892 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3894 // NOTE: Similar piece of code exists on the server side for
3896 // Get digging parameters
3897 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3898 &playeritem_toolcap);
3900 // If can't dig, try hand
3901 if (!params.diggable) {
3902 const ItemDefinition &hand = itemdef_manager->get("");
3903 const ToolCapabilities *tp = hand.tool_capabilities;
3906 params = getDigParams(nodedef_manager->get(n).groups, tp);
3909 if (params.diggable == false) {
3910 // I guess nobody will wait for this long
3911 runData->dig_time_complete = 10000000.0;
3913 runData->dig_time_complete = params.time;
3915 if (m_cache_enable_particles) {
3916 const ContentFeatures &features =
3917 client->getNodeDefManager()->get(n);
3918 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3919 player, nodepos, features.tiles);
3923 if (runData->dig_time_complete >= 0.001) {
3924 runData->dig_index = (float)crack_animation_length
3926 / runData->dig_time_complete;
3928 // This is for torches
3929 runData->dig_index = crack_animation_length;
3932 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3934 if (sound_dig.exists() && params.diggable) {
3935 if (sound_dig.name == "__group") {
3936 if (params.main_group != "") {
3937 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3938 soundmaker->m_player_leftpunch_sound.name =
3939 std::string("default_dig_") +
3943 soundmaker->m_player_leftpunch_sound = sound_dig;
3947 // Don't show cracks if not diggable
3948 if (runData->dig_time_complete >= 100000.0) {
3949 } else if (runData->dig_index < crack_animation_length) {
3950 //TimeTaker timer("client.setTempMod");
3951 //infostream<<"dig_index="<<dig_index<<std::endl;
3952 client->setCrack(runData->dig_index, nodepos);
3954 infostream << "Digging completed" << std::endl;
3955 client->interact(2, pointed);
3956 client->setCrack(-1, v3s16(0, 0, 0));
3957 bool is_valid_position;
3958 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3959 if (is_valid_position)
3960 client->removeNode(nodepos);
3962 if (m_cache_enable_particles) {
3963 const ContentFeatures &features =
3964 client->getNodeDefManager()->get(wasnode);
3965 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3966 player, nodepos, features.tiles);
3969 runData->dig_time = 0;
3970 runData->digging = false;
3972 runData->nodig_delay_timer =
3973 runData->dig_time_complete / (float)crack_animation_length;
3975 // We don't want a corresponding delay to
3976 // very time consuming nodes
3977 if (runData->nodig_delay_timer > 0.3)
3978 runData->nodig_delay_timer = 0.3;
3980 // We want a slight delay to very little
3981 // time consuming nodes
3982 const float mindelay = 0.15;
3984 if (runData->nodig_delay_timer < mindelay)
3985 runData->nodig_delay_timer = mindelay;
3987 // Send event to trigger sound
3988 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3989 gamedef->event()->put(e);
3992 if (runData->dig_time_complete < 100000.0) {
3993 runData->dig_time += dtime;
3995 runData->dig_time = 0;
3996 client->setCrack(-1, nodepos);
3999 camera->setDigging(0); // left click animation
4003 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
4004 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
4005 const CameraOrientation &cam)
4007 LocalPlayer *player = client->getEnv().getLocalPlayer();
4013 if (draw_control->range_all) {
4014 runData->fog_range = 100000 * BS;
4016 runData->fog_range = 0.9 * draw_control->wanted_range * BS;
4020 Calculate general brightness
4022 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4023 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4024 float direct_brightness;
4027 if (g_settings->getBool("free_move")) {
4028 direct_brightness = time_brightness;
4029 sunlight_seen = true;
4031 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4032 float old_brightness = sky->getBrightness();
4033 direct_brightness = client->getEnv().getClientMap()
4034 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
4035 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4039 float time_of_day = runData->time_of_day;
4040 float time_of_day_smooth = runData->time_of_day_smooth;
4042 time_of_day = client->getEnv().getTimeOfDayF();
4044 const float maxsm = 0.05;
4045 const float todsm = 0.05;
4047 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4048 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4049 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4050 time_of_day_smooth = time_of_day;
4052 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4053 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4054 + (time_of_day + 1.0) * todsm;
4056 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4057 + time_of_day * todsm;
4059 runData->time_of_day = time_of_day;
4060 runData->time_of_day_smooth = time_of_day_smooth;
4062 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4063 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4064 player->getPitch());
4070 v3f player_position = player->getPosition();
4071 if (sky->getCloudsVisible()) {
4072 clouds->setVisible(true);
4073 clouds->step(dtime);
4074 clouds->update(v2f(player_position.X, player_position.Z),
4075 sky->getCloudColor());
4077 clouds->setVisible(false);
4084 client->getParticleManager()->step(dtime);
4090 if (m_cache_enable_fog && !flags.force_fog_off) {
4093 video::EFT_FOG_LINEAR,
4094 runData->fog_range * 0.4,
4095 runData->fog_range * 1.0,
4103 video::EFT_FOG_LINEAR,
4113 Get chat messages from client
4116 v2u32 screensize = driver->getScreenSize();
4118 updateChat(*client, dtime, flags.show_debug, screensize,
4119 flags.show_chat, runData->profiler_current_page,
4120 *chat_backend, guitext_chat);
4126 if (client->getPlayerItem() != runData->new_playeritem)
4127 client->selectPlayerItem(runData->new_playeritem);
4129 // Update local inventory if it has changed
4130 if (client->getLocalInventoryUpdated()) {
4131 //infostream<<"Updating local inventory"<<std::endl;
4132 client->getLocalInventory(*local_inventory);
4133 runData->update_wielded_item_trigger = true;
4136 if (runData->update_wielded_item_trigger) {
4137 // Update wielded tool
4138 InventoryList *mlist = local_inventory->getList("main");
4140 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4141 ItemStack item = mlist->getItem(client->getPlayerItem());
4142 camera->wield(item);
4144 runData->update_wielded_item_trigger = false;
4148 Update block draw list every 200ms or when camera direction has
4151 runData->update_draw_list_timer += dtime;
4153 v3f camera_direction = camera->getDirection();
4154 if (runData->update_draw_list_timer >= 0.2
4155 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4156 || flags.camera_offset_changed) {
4157 runData->update_draw_list_timer = 0;
4158 client->getEnv().getClientMap().updateDrawList(driver);
4159 runData->update_draw_list_last_cam_dir = camera_direction;
4162 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4165 make sure menu is on top
4166 1. Delete formspec menu reference if menu was removed
4167 2. Else, make sure formspec menu is on top
4169 if (current_formspec) {
4170 if (current_formspec->getReferenceCount() == 1) {
4171 current_formspec->drop();
4172 current_formspec = NULL;
4173 } else if (!noMenuActive()) {
4174 guiroot->bringToFront(current_formspec);
4182 video::SColor skycolor = sky->getSkyColor();
4184 TimeTaker tt_draw("mainloop: draw");
4186 TimeTaker timer("beginScene");
4187 driver->beginScene(true, true, skycolor);
4188 stats->beginscenetime = timer.stop(true);
4191 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4192 guienv, screensize, skycolor, flags.show_hud,
4193 flags.show_minimap);
4198 if (flags.show_profiler_graph)
4199 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4204 if (runData->damage_flash > 0.0) {
4205 video::SColor color(std::min(runData->damage_flash, 180.0f),
4209 driver->draw2DRectangle(color,
4210 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4213 runData->damage_flash -= 100.0 * dtime;
4219 if (player->hurt_tilt_timer > 0.0) {
4220 player->hurt_tilt_timer -= dtime * 5;
4222 if (player->hurt_tilt_timer < 0)
4223 player->hurt_tilt_strength = 0;
4227 Update minimap pos and rotation
4229 if (flags.show_minimap && flags.show_hud) {
4230 mapper->setPos(floatToInt(player->getPosition(), BS));
4231 mapper->setAngle(player->getYaw());
4238 TimeTaker timer("endScene");
4240 stats->endscenetime = timer.stop(true);
4243 stats->drawtime = tt_draw.stop(true);
4244 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4248 inline static const char *yawToDirectionString(int yaw)
4250 // NOTE: TODO: This can be done mathematically without the else/else-if
4253 const char *player_direction;
4255 yaw = wrapDegrees_0_360(yaw);
4257 if (yaw >= 45 && yaw < 135)
4258 player_direction = "West [-X]";
4259 else if (yaw >= 135 && yaw < 225)
4260 player_direction = "South [-Z]";
4261 else if (yaw >= 225 && yaw < 315)
4262 player_direction = "East [+X]";
4264 player_direction = "North [+Z]";
4266 return player_direction;
4270 void Game::updateGui(float *statustext_time, const RunStats &stats,
4271 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4272 const CameraOrientation &cam)
4274 v2u32 screensize = driver->getScreenSize();
4275 LocalPlayer *player = client->getEnv().getLocalPlayer();
4276 v3f player_position = player->getPosition();
4278 if (flags.show_debug) {
4279 static float drawtime_avg = 0;
4280 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4282 u16 fps = 1.0 / stats.dtime_jitter.avg;
4283 //s32 fps = driver->getFPS();
4285 std::ostringstream os(std::ios_base::binary);
4287 << PROJECT_NAME_C " " << g_version_hash
4289 << " (R: range_all=" << draw_control->range_all << ")"
4290 << std::setprecision(0)
4291 << " drawtime = " << drawtime_avg
4292 << std::setprecision(1)
4293 << ", dtime_jitter = "
4294 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4295 << std::setprecision(1)
4296 << ", v_range = " << draw_control->wanted_range
4297 << std::setprecision(3)
4298 << ", RTT = " << client->getRTT();
4299 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4300 guitext->setVisible(true);
4301 } else if (flags.show_hud || flags.show_chat) {
4302 std::ostringstream os(std::ios_base::binary);
4303 os << PROJECT_NAME_C " " << g_version_hash;
4304 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4305 guitext->setVisible(true);
4307 guitext->setVisible(false);
4310 if (guitext->isVisible()) {
4311 core::rect<s32> rect(
4313 screensize.X, 5 + g_fontengine->getTextHeight()
4315 guitext->setRelativePosition(rect);
4318 if (flags.show_debug) {
4319 std::ostringstream os(std::ios_base::binary);
4320 os << std::setprecision(1) << std::fixed
4321 << "(" << (player_position.X / BS)
4322 << ", " << (player_position.Y / BS)
4323 << ", " << (player_position.Z / BS)
4324 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4325 << " " << yawToDirectionString(cam.camera_yaw)
4326 << ") (seed = " << ((u64)client->getMapSeed())
4329 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4330 ClientMap &map = client->getEnv().getClientMap();
4331 const INodeDefManager *nodedef = client->getNodeDefManager();
4332 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4333 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4334 const ContentFeatures &features = nodedef->get(n);
4335 os << " (pointing_at = " << nodedef->get(n).name
4336 << " - " << features.tiledef[0].name.c_str()
4341 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4342 guitext2->setVisible(true);
4344 core::rect<s32> rect(
4345 5, 5 + g_fontengine->getTextHeight(),
4346 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4348 guitext2->setRelativePosition(rect);
4350 guitext2->setVisible(false);
4353 setStaticText(guitext_info, infotext.c_str());
4354 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4356 float statustext_time_max = 1.5;
4358 if (!statustext.empty()) {
4359 *statustext_time += dtime;
4361 if (*statustext_time >= statustext_time_max) {
4363 *statustext_time = 0;
4367 setStaticText(guitext_status, statustext.c_str());
4368 guitext_status->setVisible(!statustext.empty());
4370 if (!statustext.empty()) {
4371 s32 status_width = guitext_status->getTextWidth();
4372 s32 status_height = guitext_status->getTextHeight();
4373 s32 status_y = screensize.Y - 150;
4374 s32 status_x = (screensize.X - status_width) / 2;
4375 core::rect<s32> rect(
4376 status_x , status_y - status_height,
4377 status_x + status_width, status_y
4379 guitext_status->setRelativePosition(rect);
4382 video::SColor initial_color(255, 0, 0, 0);
4384 if (guienv->getSkin())
4385 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4387 video::SColor final_color = initial_color;
4388 final_color.setAlpha(0);
4389 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4390 initial_color, final_color,
4391 pow(*statustext_time / statustext_time_max, 2.0f));
4392 guitext_status->setOverrideColor(fade_color);
4393 guitext_status->enableOverrideColor(true);
4398 /* Log times and stuff for visualization */
4399 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4401 Profiler::GraphValues values;
4402 g_profiler->graphGet(values);
4408 /****************************************************************************
4410 ****************************************************************************/
4412 /* On some computers framerate doesn't seem to be automatically limited
4414 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4416 // not using getRealTime is necessary for wine
4417 device->getTimer()->tick(); // Maker sure device time is up-to-date
4418 u32 time = device->getTimer()->getTime();
4419 u32 last_time = fps_timings->last_time;
4421 if (time > last_time) // Make sure time hasn't overflowed
4422 fps_timings->busy_time = time - last_time;
4424 fps_timings->busy_time = 0;
4426 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4427 ? g_settings->getFloat("pause_fps_max")
4428 : g_settings->getFloat("fps_max"));
4430 if (fps_timings->busy_time < frametime_min) {
4431 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4432 device->sleep(fps_timings->sleep_time);
4434 fps_timings->sleep_time = 0;
4437 /* Get the new value of the device timer. Note that device->sleep() may
4438 * not sleep for the entire requested time as sleep may be interrupted and
4439 * therefore it is arguably more accurate to get the new time from the
4440 * device rather than calculating it by adding sleep_time to time.
4443 device->getTimer()->tick(); // Update device timer
4444 time = device->getTimer()->getTime();
4446 if (time > last_time) // Make sure last_time hasn't overflowed
4447 *dtime = (time - last_time) / 1000.0;
4451 fps_timings->last_time = time;
4454 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4455 // pass a copy of it to this function
4456 // Note: \p msg must be allocated using new (not malloc())
4457 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4458 int percent, bool draw_clouds)
4460 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4464 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4466 ((Game *)data)->readSettings();
4469 void Game::readSettings()
4471 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4472 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4473 m_cache_enable_particles = g_settings->getBool("enable_particles");
4474 m_cache_enable_fog = g_settings->getBool("enable_fog");
4475 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4476 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4478 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4481 /****************************************************************************/
4482 /****************************************************************************
4484 ****************************************************************************/
4485 /****************************************************************************/
4487 void Game::extendedResourceCleanup()
4489 // Extended resource accounting
4490 infostream << "Irrlicht resources after cleanup:" << std::endl;
4491 infostream << "\tRemaining meshes : "
4492 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4493 infostream << "\tRemaining textures : "
4494 << driver->getTextureCount() << std::endl;
4496 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4497 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4498 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4502 clearTextureNameCache();
4503 infostream << "\tRemaining materials: "
4504 << driver-> getMaterialRendererCount()
4505 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4509 /****************************************************************************/
4510 /****************************************************************************
4511 extern function for launching the game
4512 ****************************************************************************/
4513 /****************************************************************************/
4515 void the_game(bool *kill,
4517 InputHandler *input,
4518 IrrlichtDevice *device,
4520 const std::string &map_dir,
4521 const std::string &playername,
4522 const std::string &password,
4523 const std::string &address, // If empty local server is created
4526 std::string &error_message,
4527 ChatBackend &chat_backend,
4528 bool *reconnect_requested,
4529 const SubgameSpec &gamespec, // Used for local game
4530 bool simple_singleplayer_mode)
4534 /* Make a copy of the server address because if a local singleplayer server
4535 * is created then this is updated and we don't want to change the value
4536 * passed to us by the calling function
4538 std::string server_address = address;
4542 if (game.startup(kill, random_input, input, device, map_dir,
4543 playername, password, &server_address, port, error_message,
4544 reconnect_requested, &chat_backend, gamespec,
4545 simple_singleplayer_mode)) {
4550 } catch (SerializationError &e) {
4551 error_message = std::string("A serialization error occurred:\n")
4552 + e.what() + "\n\nThe server is probably "
4553 " running a different version of " PROJECT_NAME_C ".";
4554 errorstream << error_message << std::endl;
4555 } catch (ServerError &e) {
4556 error_message = e.what();
4557 errorstream << "ServerError: " << error_message << std::endl;
4558 } catch (ModError &e) {
4559 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4560 errorstream << "ModError: " << error_message << std::endl;